@nocios/crudify-components 2.0.0 → 2.0.1
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/chunk-47SM45CV.js +1 -0
- package/dist/{chunk-4VN5YRYZ.js → chunk-5HFI5CZ5.js} +1 -1
- package/dist/chunk-72CJ7DHU.mjs +1 -0
- package/dist/{chunk-XZ6OGRJR.mjs → chunk-C35OZ7PU.mjs} +1 -1
- package/dist/chunk-ISEMM6ZR.mjs +1 -0
- package/dist/chunk-JNEWPO2J.mjs +1 -0
- package/dist/chunk-MFYHD6S5.js +1 -0
- package/dist/chunk-MGJZTOEM.mjs +1 -0
- package/dist/chunk-QXKVRWT3.js +1 -0
- package/dist/{chunk-RORGWKHP.js → chunk-U5NSADER.js} +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/errorTranslation-DGdrMidg.d.ts +143 -0
- package/dist/errorTranslation-qwwQTvCO.d.mts +143 -0
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/index.d.mts +45 -8
- package/dist/index.d.ts +45 -8
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/utils.d.mts +48 -2
- package/dist/utils.d.ts +48 -2
- package/dist/utils.js +1 -1
- package/dist/utils.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-4ILUXVPW.mjs +0 -1
- package/dist/chunk-7ORHVSWL.mjs +0 -1
- package/dist/chunk-AOPB3KXB.js +0 -1
- package/dist/chunk-CR5KJUST.js +0 -1
- package/dist/chunk-GT7B57S5.mjs +0 -1
- package/dist/chunk-LK6QVSG4.js +0 -1
- package/dist/chunk-RJBX4MWF.mjs +0 -1
- package/dist/errorTranslation-By5Av0tL.d.ts +0 -335
- package/dist/errorTranslation-DeeDj7Vt.d.mts +0 -335
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { J as JwtPayload } from './api-B4uXiHF0.mjs';
|
|
2
|
+
|
|
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 storage;
|
|
14
|
+
private encryptionKey;
|
|
15
|
+
private salt;
|
|
16
|
+
private initPromise;
|
|
17
|
+
private initialized;
|
|
18
|
+
constructor(storageType?: "localStorage" | "sessionStorage");
|
|
19
|
+
/**
|
|
20
|
+
* Initialize encryption key asynchronously
|
|
21
|
+
* Must be called before using encryption methods
|
|
22
|
+
*/
|
|
23
|
+
private ensureInitialized;
|
|
24
|
+
private initialize;
|
|
25
|
+
private generateFingerprint;
|
|
26
|
+
private clearLegacyData;
|
|
27
|
+
setItem(key: string, value: string, expiryMinutes?: number): Promise<void>;
|
|
28
|
+
getItem(key: string): Promise<string | null>;
|
|
29
|
+
removeItem(key: string): void;
|
|
30
|
+
clear(): void;
|
|
31
|
+
setToken(token: string): Promise<void>;
|
|
32
|
+
getToken(): Promise<string | null>;
|
|
33
|
+
hasValidToken(): Promise<boolean>;
|
|
34
|
+
migrateFromLocalStorage(key: string): Promise<void>;
|
|
35
|
+
private uint8ArrayToBase64;
|
|
36
|
+
private base64ToUint8Array;
|
|
37
|
+
}
|
|
38
|
+
declare const secureSessionStorage: SecureStorage;
|
|
39
|
+
declare const secureLocalStorage: SecureStorage;
|
|
40
|
+
|
|
41
|
+
declare const ERROR_CODES: {
|
|
42
|
+
readonly INVALID_CREDENTIALS: "INVALID_CREDENTIALS";
|
|
43
|
+
readonly UNAUTHORIZED: "UNAUTHORIZED";
|
|
44
|
+
readonly INVALID_API_KEY: "INVALID_API_KEY";
|
|
45
|
+
readonly USER_NOT_FOUND: "USER_NOT_FOUND";
|
|
46
|
+
readonly USER_NOT_ACTIVE: "USER_NOT_ACTIVE";
|
|
47
|
+
readonly NO_PERMISSION: "NO_PERMISSION";
|
|
48
|
+
readonly ITEM_NOT_FOUND: "ITEM_NOT_FOUND";
|
|
49
|
+
readonly NOT_FOUND: "NOT_FOUND";
|
|
50
|
+
readonly IN_USE: "IN_USE";
|
|
51
|
+
readonly FIELD_ERROR: "FIELD_ERROR";
|
|
52
|
+
readonly BAD_REQUEST: "BAD_REQUEST";
|
|
53
|
+
readonly INVALID_EMAIL: "INVALID_EMAIL";
|
|
54
|
+
readonly INVALID_CODE: "INVALID_CODE";
|
|
55
|
+
readonly INTERNAL_SERVER_ERROR: "INTERNAL_SERVER_ERROR";
|
|
56
|
+
readonly DATABASE_CONNECTION_ERROR: "DATABASE_CONNECTION_ERROR";
|
|
57
|
+
readonly INVALID_CONFIGURATION: "INVALID_CONFIGURATION";
|
|
58
|
+
readonly UNKNOWN_OPERATION: "UNKNOWN_OPERATION";
|
|
59
|
+
readonly TOO_MANY_REQUESTS: "TOO_MANY_REQUESTS";
|
|
60
|
+
readonly NETWORK_ERROR: "NETWORK_ERROR";
|
|
61
|
+
readonly TIMEOUT_ERROR: "TIMEOUT_ERROR";
|
|
62
|
+
};
|
|
63
|
+
type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
|
|
64
|
+
type ErrorSeverity = "info" | "warning" | "error" | "critical";
|
|
65
|
+
declare const ERROR_SEVERITY_MAP: Record<ErrorCode, ErrorSeverity>;
|
|
66
|
+
interface ParsedError {
|
|
67
|
+
code: ErrorCode;
|
|
68
|
+
message: string;
|
|
69
|
+
severity: ErrorSeverity;
|
|
70
|
+
field?: string;
|
|
71
|
+
details?: Record<string, unknown>;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Parse a Crudify API response and extract standardized error information
|
|
75
|
+
*/
|
|
76
|
+
declare function parseApiError(response: unknown): ParsedError[];
|
|
77
|
+
/**
|
|
78
|
+
* Parse transaction response errors
|
|
79
|
+
*/
|
|
80
|
+
declare function parseTransactionError(response: unknown): ParsedError[];
|
|
81
|
+
/**
|
|
82
|
+
* Get a human-readable error message for an error code
|
|
83
|
+
*/
|
|
84
|
+
declare function getErrorMessage(code: ErrorCode): string;
|
|
85
|
+
/**
|
|
86
|
+
* Handle JavaScript/Network errors and convert to ParsedError
|
|
87
|
+
*/
|
|
88
|
+
declare function parseJavaScriptError(error: unknown): ParsedError;
|
|
89
|
+
/**
|
|
90
|
+
* Universal error handler that can process any type of error from Crudify APIs
|
|
91
|
+
*/
|
|
92
|
+
declare function handleCrudifyError(error: unknown): ParsedError[];
|
|
93
|
+
|
|
94
|
+
interface ErrorTranslationConfig {
|
|
95
|
+
/** Función de traducción de i18next */
|
|
96
|
+
translateFn: (key: string) => string;
|
|
97
|
+
/** Idioma actual (opcional, para logging) */
|
|
98
|
+
currentLanguage?: string;
|
|
99
|
+
/** Habilitar logs de debug */
|
|
100
|
+
enableDebug?: boolean;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Traduce un código de error usando jerarquía de fallbacks
|
|
104
|
+
*/
|
|
105
|
+
declare function translateErrorCode(errorCode: string, config: ErrorTranslationConfig): string;
|
|
106
|
+
/**
|
|
107
|
+
* Traduce múltiples códigos de error
|
|
108
|
+
*/
|
|
109
|
+
declare function translateErrorCodes(errorCodes: string[], config: ErrorTranslationConfig): string[];
|
|
110
|
+
/**
|
|
111
|
+
* Traduce un error completo (código + mensaje personalizado)
|
|
112
|
+
*/
|
|
113
|
+
declare function translateError(error: {
|
|
114
|
+
code: string;
|
|
115
|
+
message?: string;
|
|
116
|
+
field?: string;
|
|
117
|
+
}, config: ErrorTranslationConfig): string;
|
|
118
|
+
/**
|
|
119
|
+
* Hook para usar en componentes React con i18next
|
|
120
|
+
*/
|
|
121
|
+
declare function createErrorTranslator(translateFn: (key: string) => string, options?: {
|
|
122
|
+
currentLanguage?: string;
|
|
123
|
+
enableDebug?: boolean;
|
|
124
|
+
}): {
|
|
125
|
+
translateErrorCode: (code: string) => string;
|
|
126
|
+
translateErrorCodes: (codes: string[]) => string[];
|
|
127
|
+
translateError: (error: {
|
|
128
|
+
code: string;
|
|
129
|
+
message?: string;
|
|
130
|
+
field?: string;
|
|
131
|
+
}) => string;
|
|
132
|
+
translateApiError: (apiResponse: {
|
|
133
|
+
data?: {
|
|
134
|
+
response?: {
|
|
135
|
+
status?: string;
|
|
136
|
+
};
|
|
137
|
+
};
|
|
138
|
+
status?: string;
|
|
139
|
+
code?: string;
|
|
140
|
+
} | null | undefined) => string;
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
export { ERROR_CODES as E, type ParsedError as P, getCookie as a, secureLocalStorage as b, parseTransactionError as c, decodeJwtSafely as d, parseJavaScriptError as e, getErrorMessage as f, getCurrentUserEmail as g, handleCrudifyError as h, isTokenExpired as i, ERROR_SEVERITY_MAP as j, translateErrorCodes as k, translateError as l, createErrorTranslator as m, type ErrorCode as n, type ErrorSeverity as o, parseApiError as p, type ErrorTranslationConfig as q, secureSessionStorage as s, translateErrorCode as t };
|
package/dist/hooks.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkU5NSADERjs = require('./chunk-U5NSADER.js');var _chunk47SM45CVjs = require('./chunk-47SM45CV.js');require('./chunk-MFYHD6S5.js');exports.useAuth = _chunkU5NSADERjs.b; exports.useAutoGenerate = _chunk47SM45CVjs.p; exports.useCrudifyWithNotifications = _chunkU5NSADERjs.d; exports.useData = _chunkU5NSADERjs.c; exports.useFileUpload = _chunk47SM45CVjs.s; exports.useSession = _chunk47SM45CVjs.f; exports.useUserData = _chunkU5NSADERjs.a; exports.useUserProfile = _chunk47SM45CVjs.o;
|
package/dist/hooks.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as s,b as p,c as u,d as a}from"./chunk-
|
|
1
|
+
import{a as s,b as p,c as u,d as a}from"./chunk-C35OZ7PU.mjs";import{f as e,o as t,p as o,s as r}from"./chunk-72CJ7DHU.mjs";import"./chunk-MGJZTOEM.mjs";export{p as useAuth,o as useAutoGenerate,a as useCrudifyWithNotifications,u as useData,r as useFileUpload,e as useSession,s as useUserData,t as useUserProfile};
|
package/dist/index.d.mts
CHANGED
|
@@ -9,7 +9,7 @@ export { F as FileItem, v as FileStatus, L as LoginResult, N as NotificationOpti
|
|
|
9
9
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
10
10
|
import { ThemeOptions } from '@mui/material';
|
|
11
11
|
export { A as AutoGenerateConfig, G as GlobalNotificationProvider, a as GlobalNotificationProviderProps, N as Notification, b as NotificationSeverity, d as UseAutoGenerateOptions, U as UseAutoGenerateReturn, c as useAutoGenerate, u as useGlobalNotification } from './GlobalNotificationProvider-Zq18OkpI.mjs';
|
|
12
|
-
export {
|
|
12
|
+
export { E as ERROR_CODES, j as ERROR_SEVERITY_MAP, n as ErrorCode, o as ErrorSeverity, q as ErrorTranslationConfig, P as ParsedError, m 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, l as translateError, t as translateErrorCode, k as translateErrorCodes } from './errorTranslation-qwwQTvCO.mjs';
|
|
13
13
|
import { ApiResponse, IModule, ModuleCreateInput, ModuleEditInput, ActionListFilters, IAction, ActionCreateInput, ActionEditInput, UpdateActionsProfilesInput, UpdateActionsProfilesResponse, CalculatePermissionsInput, CalculatePermissionsResponse } from '@nocios/crudify-admin-sdk';
|
|
14
14
|
export { ActionCreateInput, ActionEditInput, ActionListFilters, ApiResponse, IAction, IModule, ModuleCreateInput, ModuleEditInput, UpdateActionsProfilesInput, UpdateActionsProfilesResponse } from '@nocios/crudify-admin-sdk';
|
|
15
15
|
|
|
@@ -120,6 +120,44 @@ declare class CrossTabSyncManager {
|
|
|
120
120
|
*/
|
|
121
121
|
declare const crossTabSync: CrossTabSyncManager;
|
|
122
122
|
|
|
123
|
+
/**
|
|
124
|
+
* CookieManager - Manages cross-subdomain cookies for authentication
|
|
125
|
+
*
|
|
126
|
+
* Cookie Configuration:
|
|
127
|
+
* - Name: crudify_auth
|
|
128
|
+
* - Domain: .nocios.link (STG) or .crudia.com (PROD)
|
|
129
|
+
* - Secure: true (HTTPS only)
|
|
130
|
+
* - SameSite: Lax (allows cross-subdomain, prevents CSRF)
|
|
131
|
+
* - Path: /
|
|
132
|
+
* - Max-Age: 7 days (matching token refresh cycle)
|
|
133
|
+
*
|
|
134
|
+
* This enables authentication to work across subdomains:
|
|
135
|
+
* - munisanjusto.nocios.link (sets cookie)
|
|
136
|
+
* - files.nocios.link (reads cookie via Lambda@Edge)
|
|
137
|
+
*/
|
|
138
|
+
declare const CookieManager: {
|
|
139
|
+
/**
|
|
140
|
+
* Set auth token cookie for cross-subdomain authentication
|
|
141
|
+
* @param token JWT access token
|
|
142
|
+
*/
|
|
143
|
+
setToken(token: string): void;
|
|
144
|
+
/**
|
|
145
|
+
* Get auth token from cookie
|
|
146
|
+
* @returns JWT token string or null if not found
|
|
147
|
+
*/
|
|
148
|
+
getToken(): string | null;
|
|
149
|
+
/**
|
|
150
|
+
* Remove auth token cookie (on logout)
|
|
151
|
+
*/
|
|
152
|
+
removeToken(): void;
|
|
153
|
+
/**
|
|
154
|
+
* Sync cookie with localStorage token
|
|
155
|
+
* Call this on app initialization to ensure cookie is in sync
|
|
156
|
+
* @param accessToken Current access token from localStorage, or null if not authenticated
|
|
157
|
+
*/
|
|
158
|
+
syncWithLocalStorage(accessToken: string | null): void;
|
|
159
|
+
};
|
|
160
|
+
|
|
123
161
|
type CrudifyThemeProviderProps = {
|
|
124
162
|
children: ReactNode;
|
|
125
163
|
defaultTheme?: ThemeOptions;
|
|
@@ -127,8 +165,7 @@ type CrudifyThemeProviderProps = {
|
|
|
127
165
|
};
|
|
128
166
|
/**
|
|
129
167
|
* Provider de tema para aplicaciones Crudify
|
|
130
|
-
* Lee automáticamente
|
|
131
|
-
* y aplica el tema a Material-UI
|
|
168
|
+
* Lee automáticamente la cookie "theme" y aplica el tema a Material-UI
|
|
132
169
|
*
|
|
133
170
|
* @example
|
|
134
171
|
* ```tsx
|
|
@@ -181,11 +218,11 @@ declare function allPasswordRulesPassed(evaluated: EvaluatedPasswordRule[]): boo
|
|
|
181
218
|
* - dev/stg: All logs (error, warn, info, debug)
|
|
182
219
|
* - prod: Only errors (default)
|
|
183
220
|
*
|
|
184
|
-
* AUTO-DETECTION
|
|
221
|
+
* AUTO-DETECTION:
|
|
185
222
|
* The logger will automatically detect the environment from:
|
|
186
223
|
* 1. Explicit setEnvironment() call (highest priority)
|
|
187
|
-
* 2.
|
|
188
|
-
* 3. window.__CRUDIFY_ENV__ global variable
|
|
224
|
+
* 2. Cookie named 'environment' (for production with Lambda@Edge)
|
|
225
|
+
* 3. window.__CRUDIFY_ENV__ global variable
|
|
189
226
|
* 4. Default to "prod" for safety
|
|
190
227
|
*
|
|
191
228
|
* Usage:
|
|
@@ -194,7 +231,7 @@ declare function allPasswordRulesPassed(evaluated: EvaluatedPasswordRule[]): boo
|
|
|
194
231
|
* // Option 1: Explicit configuration (recommended for apps)
|
|
195
232
|
* logger.setEnvironment('dev'); // or 'stg', 'prod'
|
|
196
233
|
*
|
|
197
|
-
* // Option 2: Auto-detection (reads
|
|
234
|
+
* // Option 2: Auto-detection (reads cookie or global)
|
|
198
235
|
* // Just use the logger - it will auto-detect
|
|
199
236
|
*
|
|
200
237
|
* logger.error('Something failed', { userId: '123' });
|
|
@@ -1272,4 +1309,4 @@ declare const crudifyAdmin: {
|
|
|
1272
1309
|
calculatePermissions: (data: CalculatePermissionsInput) => Promise<ApiResponse<CalculatePermissionsResponse>>;
|
|
1273
1310
|
};
|
|
1274
1311
|
|
|
1275
|
-
export { AuthRoute, type AuthRouteProps, CRITICAL_TRANSLATIONS, type CriticalTranslationKey, type CrossTabListener, type CrossTabMessage, type CrossTabMessageType, CrossTabSyncManager, CrudifyInitializationManager, CrudifyInitializer, type CrudifyInitializerConfig, type CrudifyInitializerProps, CrudifyLoginConfig, CrudifyProvider, CrudifyThemeProvider, type CrudifyThemeProviderProps, EvaluatedPasswordRule, type FetchTranslationsOptions, GuestRoute, type GuestRouteBehavior, type GuestRouteProps, type InitializationPriority, type InitializationRequest, type InitializationStatus, type LogContext, type LogLevel, PasswordRequirements, type PasswordRequirementsProps, PasswordRule, ProtectedRoute, type ProtectedRouteProps, SessionLoadingScreen, type SessionLoadingScreenProps, type SupportedLanguage, type TranslationResponse, TranslationService, type TranslationsContextValue, TranslationsProvider, type TranslationsProviderProps, allPasswordRulesPassed, clearCorruptedTokens, crossTabSync, crudifyAdmin, crudifyInitManager, evaluatePasswordRules, extractSafeRedirectFromUrl, getCriticalLanguages, getCriticalTranslations, hasCorruptedTokens, hasEncryptionKeyHash, hasStoredTokens, logger, shouldWaitForInitialization, translationService, useCrudify, useCrudifyInitializer, useTranslations, validateInternalRedirect };
|
|
1312
|
+
export { AuthRoute, type AuthRouteProps, CRITICAL_TRANSLATIONS, CookieManager, type CriticalTranslationKey, type CrossTabListener, type CrossTabMessage, type CrossTabMessageType, CrossTabSyncManager, CrudifyInitializationManager, CrudifyInitializer, type CrudifyInitializerConfig, type CrudifyInitializerProps, CrudifyLoginConfig, CrudifyProvider, CrudifyThemeProvider, type CrudifyThemeProviderProps, EvaluatedPasswordRule, type FetchTranslationsOptions, GuestRoute, type GuestRouteBehavior, type GuestRouteProps, type InitializationPriority, type InitializationRequest, type InitializationStatus, type LogContext, type LogLevel, PasswordRequirements, type PasswordRequirementsProps, PasswordRule, ProtectedRoute, type ProtectedRouteProps, SessionLoadingScreen, type SessionLoadingScreenProps, type SupportedLanguage, type TranslationResponse, TranslationService, type TranslationsContextValue, TranslationsProvider, type TranslationsProviderProps, allPasswordRulesPassed, clearCorruptedTokens, crossTabSync, crudifyAdmin, crudifyInitManager, evaluatePasswordRules, extractSafeRedirectFromUrl, getCriticalLanguages, getCriticalTranslations, hasCorruptedTokens, hasEncryptionKeyHash, hasStoredTokens, logger, shouldWaitForInitialization, translationService, useCrudify, useCrudifyInitializer, useTranslations, validateInternalRedirect };
|
package/dist/index.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ export { F as FileItem, v as FileStatus, L as LoginResult, N as NotificationOpti
|
|
|
9
9
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
10
10
|
import { ThemeOptions } from '@mui/material';
|
|
11
11
|
export { A as AutoGenerateConfig, G as GlobalNotificationProvider, a as GlobalNotificationProviderProps, N as Notification, b as NotificationSeverity, d as UseAutoGenerateOptions, U as UseAutoGenerateReturn, c as useAutoGenerate, u as useGlobalNotification } from './GlobalNotificationProvider-Zq18OkpI.js';
|
|
12
|
-
export {
|
|
12
|
+
export { E as ERROR_CODES, j as ERROR_SEVERITY_MAP, n as ErrorCode, o as ErrorSeverity, q as ErrorTranslationConfig, P as ParsedError, m 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, l as translateError, t as translateErrorCode, k as translateErrorCodes } from './errorTranslation-DGdrMidg.js';
|
|
13
13
|
import { ApiResponse, IModule, ModuleCreateInput, ModuleEditInput, ActionListFilters, IAction, ActionCreateInput, ActionEditInput, UpdateActionsProfilesInput, UpdateActionsProfilesResponse, CalculatePermissionsInput, CalculatePermissionsResponse } from '@nocios/crudify-admin-sdk';
|
|
14
14
|
export { ActionCreateInput, ActionEditInput, ActionListFilters, ApiResponse, IAction, IModule, ModuleCreateInput, ModuleEditInput, UpdateActionsProfilesInput, UpdateActionsProfilesResponse } from '@nocios/crudify-admin-sdk';
|
|
15
15
|
|
|
@@ -120,6 +120,44 @@ declare class CrossTabSyncManager {
|
|
|
120
120
|
*/
|
|
121
121
|
declare const crossTabSync: CrossTabSyncManager;
|
|
122
122
|
|
|
123
|
+
/**
|
|
124
|
+
* CookieManager - Manages cross-subdomain cookies for authentication
|
|
125
|
+
*
|
|
126
|
+
* Cookie Configuration:
|
|
127
|
+
* - Name: crudify_auth
|
|
128
|
+
* - Domain: .nocios.link (STG) or .crudia.com (PROD)
|
|
129
|
+
* - Secure: true (HTTPS only)
|
|
130
|
+
* - SameSite: Lax (allows cross-subdomain, prevents CSRF)
|
|
131
|
+
* - Path: /
|
|
132
|
+
* - Max-Age: 7 days (matching token refresh cycle)
|
|
133
|
+
*
|
|
134
|
+
* This enables authentication to work across subdomains:
|
|
135
|
+
* - munisanjusto.nocios.link (sets cookie)
|
|
136
|
+
* - files.nocios.link (reads cookie via Lambda@Edge)
|
|
137
|
+
*/
|
|
138
|
+
declare const CookieManager: {
|
|
139
|
+
/**
|
|
140
|
+
* Set auth token cookie for cross-subdomain authentication
|
|
141
|
+
* @param token JWT access token
|
|
142
|
+
*/
|
|
143
|
+
setToken(token: string): void;
|
|
144
|
+
/**
|
|
145
|
+
* Get auth token from cookie
|
|
146
|
+
* @returns JWT token string or null if not found
|
|
147
|
+
*/
|
|
148
|
+
getToken(): string | null;
|
|
149
|
+
/**
|
|
150
|
+
* Remove auth token cookie (on logout)
|
|
151
|
+
*/
|
|
152
|
+
removeToken(): void;
|
|
153
|
+
/**
|
|
154
|
+
* Sync cookie with localStorage token
|
|
155
|
+
* Call this on app initialization to ensure cookie is in sync
|
|
156
|
+
* @param accessToken Current access token from localStorage, or null if not authenticated
|
|
157
|
+
*/
|
|
158
|
+
syncWithLocalStorage(accessToken: string | null): void;
|
|
159
|
+
};
|
|
160
|
+
|
|
123
161
|
type CrudifyThemeProviderProps = {
|
|
124
162
|
children: ReactNode;
|
|
125
163
|
defaultTheme?: ThemeOptions;
|
|
@@ -127,8 +165,7 @@ type CrudifyThemeProviderProps = {
|
|
|
127
165
|
};
|
|
128
166
|
/**
|
|
129
167
|
* Provider de tema para aplicaciones Crudify
|
|
130
|
-
* Lee automáticamente
|
|
131
|
-
* y aplica el tema a Material-UI
|
|
168
|
+
* Lee automáticamente la cookie "theme" y aplica el tema a Material-UI
|
|
132
169
|
*
|
|
133
170
|
* @example
|
|
134
171
|
* ```tsx
|
|
@@ -181,11 +218,11 @@ declare function allPasswordRulesPassed(evaluated: EvaluatedPasswordRule[]): boo
|
|
|
181
218
|
* - dev/stg: All logs (error, warn, info, debug)
|
|
182
219
|
* - prod: Only errors (default)
|
|
183
220
|
*
|
|
184
|
-
* AUTO-DETECTION
|
|
221
|
+
* AUTO-DETECTION:
|
|
185
222
|
* The logger will automatically detect the environment from:
|
|
186
223
|
* 1. Explicit setEnvironment() call (highest priority)
|
|
187
|
-
* 2.
|
|
188
|
-
* 3. window.__CRUDIFY_ENV__ global variable
|
|
224
|
+
* 2. Cookie named 'environment' (for production with Lambda@Edge)
|
|
225
|
+
* 3. window.__CRUDIFY_ENV__ global variable
|
|
189
226
|
* 4. Default to "prod" for safety
|
|
190
227
|
*
|
|
191
228
|
* Usage:
|
|
@@ -194,7 +231,7 @@ declare function allPasswordRulesPassed(evaluated: EvaluatedPasswordRule[]): boo
|
|
|
194
231
|
* // Option 1: Explicit configuration (recommended for apps)
|
|
195
232
|
* logger.setEnvironment('dev'); // or 'stg', 'prod'
|
|
196
233
|
*
|
|
197
|
-
* // Option 2: Auto-detection (reads
|
|
234
|
+
* // Option 2: Auto-detection (reads cookie or global)
|
|
198
235
|
* // Just use the logger - it will auto-detect
|
|
199
236
|
*
|
|
200
237
|
* logger.error('Something failed', { userId: '123' });
|
|
@@ -1272,4 +1309,4 @@ declare const crudifyAdmin: {
|
|
|
1272
1309
|
calculatePermissions: (data: CalculatePermissionsInput) => Promise<ApiResponse<CalculatePermissionsResponse>>;
|
|
1273
1310
|
};
|
|
1274
1311
|
|
|
1275
|
-
export { AuthRoute, type AuthRouteProps, CRITICAL_TRANSLATIONS, type CriticalTranslationKey, type CrossTabListener, type CrossTabMessage, type CrossTabMessageType, CrossTabSyncManager, CrudifyInitializationManager, CrudifyInitializer, type CrudifyInitializerConfig, type CrudifyInitializerProps, CrudifyLoginConfig, CrudifyProvider, CrudifyThemeProvider, type CrudifyThemeProviderProps, EvaluatedPasswordRule, type FetchTranslationsOptions, GuestRoute, type GuestRouteBehavior, type GuestRouteProps, type InitializationPriority, type InitializationRequest, type InitializationStatus, type LogContext, type LogLevel, PasswordRequirements, type PasswordRequirementsProps, PasswordRule, ProtectedRoute, type ProtectedRouteProps, SessionLoadingScreen, type SessionLoadingScreenProps, type SupportedLanguage, type TranslationResponse, TranslationService, type TranslationsContextValue, TranslationsProvider, type TranslationsProviderProps, allPasswordRulesPassed, clearCorruptedTokens, crossTabSync, crudifyAdmin, crudifyInitManager, evaluatePasswordRules, extractSafeRedirectFromUrl, getCriticalLanguages, getCriticalTranslations, hasCorruptedTokens, hasEncryptionKeyHash, hasStoredTokens, logger, shouldWaitForInitialization, translationService, useCrudify, useCrudifyInitializer, useTranslations, validateInternalRedirect };
|
|
1312
|
+
export { AuthRoute, type AuthRouteProps, CRITICAL_TRANSLATIONS, CookieManager, type CriticalTranslationKey, type CrossTabListener, type CrossTabMessage, type CrossTabMessageType, CrossTabSyncManager, CrudifyInitializationManager, CrudifyInitializer, type CrudifyInitializerConfig, type CrudifyInitializerProps, CrudifyLoginConfig, CrudifyProvider, CrudifyThemeProvider, type CrudifyThemeProviderProps, EvaluatedPasswordRule, type FetchTranslationsOptions, GuestRoute, type GuestRouteBehavior, type GuestRouteProps, type InitializationPriority, type InitializationRequest, type InitializationStatus, type LogContext, type LogLevel, PasswordRequirements, type PasswordRequirementsProps, PasswordRule, ProtectedRoute, type ProtectedRouteProps, SessionLoadingScreen, type SessionLoadingScreenProps, type SupportedLanguage, type TranslationResponse, TranslationService, type TranslationsContextValue, TranslationsProvider, type TranslationsProviderProps, allPasswordRulesPassed, clearCorruptedTokens, crossTabSync, crudifyAdmin, crudifyInitManager, evaluatePasswordRules, extractSafeRedirectFromUrl, getCriticalLanguages, getCriticalTranslations, hasCorruptedTokens, hasEncryptionKeyHash, hasStoredTokens, logger, shouldWaitForInitialization, translationService, useCrudify, useCrudifyInitializer, useTranslations, validateInternalRedirect };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createStarExport(obj) { Object.keys(obj) .filter((key) => key !== "default" && key !== "__esModule") .forEach((key) => { if (exports.hasOwnProperty(key)) { return; } Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]}); }); } 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; } async function _asyncOptionalChain(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 = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createStarExport(obj) { Object.keys(obj) .filter((key) => key !== "default" && key !== "__esModule") .forEach((key) => { if (exports.hasOwnProperty(key)) { return; } Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]}); }); } 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; } async function _asyncOptionalChain(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 = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkQXKVRWT3js = require('./chunk-QXKVRWT3.js');var _chunkU5NSADERjs = require('./chunk-U5NSADER.js');var _chunk47SM45CVjs = require('./chunk-47SM45CV.js');var _chunk5HFI5CZ5js = require('./chunk-5HFI5CZ5.js');var _chunkNSV6ECYOjs = require('./chunk-NSV6ECYO.js');var _chunkMFYHD6S5js = require('./chunk-MFYHD6S5.js');var _crudifysdk = require('@nocios/crudify-sdk'); var _crudifysdk2 = _interopRequireDefault(_crudifysdk); _createStarExport(_crudifysdk);var _react = require('react');var _material = require('@mui/material');var _jsxruntime = require('react/jsx-runtime');var nr=(e={})=>{try{let r=_chunkMFYHD6S5js.b.call(void 0, "theme");if(r){let t=JSON.parse(decodeURIComponent(r));return{...e,...t}}}catch(r){_chunkMFYHD6S5js.a.warn("Error parsing theme from cookie",r instanceof Error?{errorMessage:r.message}:{message:String(r)})}return e};function sr({children:e,defaultTheme:r={},disableCssBaseline:t=!1}){let o=_react.useMemo.call(void 0, ()=>{let n=nr(r);return _material.createTheme.call(void 0, n)},[r]);return _jsxruntime.jsxs.call(void 0, _material.ThemeProvider,{theme:o,children:[!t&&_jsxruntime.jsx.call(void 0, _material.CssBaseline,{}),e]})}var _reactrouterdom = require('react-router-dom');var ur={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},cr=()=>_jsxruntime.jsx.call(void 0, "style",{children:`
|
|
2
2
|
@keyframes spin {
|
|
3
3
|
0% { transform: rotate(0deg); }
|
|
4
4
|
100% { transform: rotate(360deg); }
|
|
5
5
|
}
|
|
6
|
-
`});function g({stage:e="loading",message:r}){let o=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, cr,{}),_jsxruntime.jsxs.call(void 0, "div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[_jsxruntime.jsx.call(void 0, "div",{style:ur}),_jsxruntime.jsx.call(void 0, "p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:o})]})]})}var dr=/^[a-zA-Z0-9\-_./\?=&%#]+$/,fr=[/^https?:\/\//i,/^ftp:\/\//i,/^\/\//,/javascript:/i,/data:/i,/vbscript:/i,/about:/i,/\.\.\//,/\.\.\\/,/%2e%2e%2f/i,/%2e%2e%5c/i,/%2f%2f/i,/%5c%5c/i,/[\x00-\x1f\x7f-\x9f]/,/\\/],k= exports.validateInternalRedirect =(e,r="/")=>{if(!e||typeof e!="string")return r;let t=e.trim();if(!t)return r;if(!t.startsWith("/"))return _chunkCR5KJUSTjs.a.warn("Open redirect blocked (relative path)",{path:e}),r;if(!dr.test(t))return _chunkCR5KJUSTjs.a.warn("Open redirect blocked (invalid characters)",{path:e}),r;let o=t.toLowerCase();for(let i of fr)if(i.test(o))return _chunkCR5KJUSTjs.a.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let n=t.split("?")[0].split("/").filter(Boolean);if(n.length===0)return t;for(let i of n)if(i===".."||i.includes(":")||i.length>100)return _chunkCR5KJUSTjs.a.warn("Open redirect blocked (suspicious path part)",{part:i}),r;return t},M= exports.extractSafeRedirectFromUrl =(e,r="/")=>{try{let o=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!o)return r;let n=decodeURIComponent(o);return k(n,r)}catch(t){return _chunkCR5KJUSTjs.a.warn("Error parsing redirect parameter",t instanceof Error?{errorMessage:t.message}:{message:String(t)}),r}};function V({children:e,loadingComponent:r,loginPath:t="/login"}){let{isAuthenticated:o,isLoading:n,isLoggingOut:i,isInitialized:y,tokens:c,error:f}=_chunkLK6QVSG4js.l.call(void 0, ),u=_reactrouterdom.useLocation.call(void 0, );if(!y||n&&!i)return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:r||_jsxruntime.jsx.call(void 0, g,{stage:"validating-session"})});let l=o&&_optionalChain([c, 'optionalAccess', _2 => _2.accessToken])&&c.accessToken.length>0;if(f||!o||!l){if(i)return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:t,replace:!0});let R=u.pathname+u.search;if(u.pathname===t||u.pathname.startsWith(t))return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:t,replace:!0});let S=k(R),w=encodeURIComponent(S);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:`${t}?redirect=${w}`,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}var L="crudify_tokens",gr="crudify_enc_key";function B(){try{let e=localStorage.getItem(L);return e?e.startsWith("v2:")&&e.length>50:!1}catch (e2){return!1}}function W(){try{let e=localStorage.getItem(gr);return e!==null&&e.length>=32}catch (e3){return!1}}function U(){return B()&&W()}function H(){try{let e=localStorage.getItem(L);return e?!e.startsWith("v2:")||e.length<50:!1}catch (e4){return!1}}function yr(){try{H()&&localStorage.removeItem(L)}catch (e5){}}function Y({children:e,redirectTo:r="/",loadingComponent:t,initTimeout:o=3e3}){let{isAuthenticated:n,isInitialized:i}=_chunkLK6QVSG4js.l.call(void 0, ),y=_reactrouterdom.useLocation.call(void 0, ),[c]=_react.useState.call(void 0, ()=>U()),[f,u]=_react.useState.call(void 0, !1);if(_react.useEffect.call(void 0, ()=>{if(!i&&c){let l=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(l)}},[i,c,o]),i&&n){let l=new URLSearchParams(y.search),R=M(l,r);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:R,replace:!0})}return i&&!n?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e}):c&&!f?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:t||_jsxruntime.jsx.call(void 0, g,{stage:"validating-session"})}):_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function $({children:e,behavior:r="redirect-if-authenticated",redirectTo:t="/",loadingComponent:o}){let{isAuthenticated:n,isInitialized:i}=_chunkLK6QVSG4js.l.call(void 0, );return i?r==="allow-all"?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e}):n?_jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:t,replace:!0}):_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e}):_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:o||_jsxruntime.jsx.call(void 0, g,{stage:"validating-session"})})}var Q=_react.createContext.call(void 0, void 0),Sr= exports.CrudifyInitializer =({config:e,children:r,fallback:t=null,onInitialized:o,onError:n})=>{let[i,y]=_react.useState.call(void 0, !1),[c,f]=_react.useState.call(void 0, !1),[u,l]=_react.useState.call(void 0, null),R=_react.useRef.call(void 0, !1),S=_react.useRef.call(void 0, !1);_react.useEffect.call(void 0, ()=>{R.current||(_chunkLK6QVSG4js.q.registerHighPriorityInitializer(),R.current=!0),S.current||(S.current=!0,(async()=>{f(!0),l(null);try{let d=_chunkCR5KJUSTjs.d.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _3 => _3.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _4 => _4.env]),enableDebug:_optionalChain([e, 'optionalAccess', _5 => _5.enableLogging])});if(!d.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");let v=d.env||"prod";_chunkCR5KJUSTjs.a.setEnvironment(v),await _chunkLK6QVSG4js.q.initialize({priority:"HIGH",publicApiKey:d.publicApiKey,env:d.env||"prod",enableLogging:_optionalChain([e, 'optionalAccess', _6 => _6.enableLogging]),requestedBy:"CrudifyInitializer"}),y(!0),f(!1),o&&o()}catch(d){let v=d instanceof Error?d:new Error(String(d));l(v),f(!1),n&&n(v)}})())},[_optionalChain([e, 'optionalAccess', _7 => _7.publicApiKey]),_optionalChain([e, 'optionalAccess', _8 => _8.env]),_optionalChain([e, 'optionalAccess', _9 => _9.enableLogging]),o,n]);let w={isInitialized:i,isInitializing:c,error:u};return c&&t?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:t}):(u&&_chunkCR5KJUSTjs.a.error("[CrudifyInitializer] Initialization failed",u),_jsxruntime.jsx.call(void 0, Q.Provider,{value:w,children:r}))},vr= exports.useCrudifyInitializer =()=>{let e=_react.useContext.call(void 0, Q);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};var _crudifyadminsdk = require('@nocios/crudify-admin-sdk'); var _crudifyadminsdk2 = _interopRequireDefault(_crudifyadminsdk);var X=!1,I=null,h=null;async function Er(){let r=await _chunkLK6QVSG4js.d.getInstance().getTokenInfo(),t=_optionalChain([r, 'optionalAccess', _10 => _10.apiEndpointAdmin]),o=_optionalChain([r, 'optionalAccess', _11 => _11.apiKeyEndpointAdmin]);return t&&o?{apiUrl:t,apiKey:o}:_chunkLK6QVSG4js.h.waitForCredentials()}async function kr(){if(!X)return I||(I=(async()=>{try{let e=_chunkLK6QVSG4js.d.getInstance(),{apiUrl:r,apiKey:t}=await Er();h=await _asyncOptionalChain([(await e.getTokenInfo()), 'optionalAccess', async _12 => _12.crudifyTokens, 'optionalAccess', async _13 => _13.accessToken])||null,_crudifyadminsdk2.default.init({url:r,apiKey:t,getAdditionalHeaders:()=>h?{Authorization:`Bearer ${h}`}:{}}),X=!0}catch(e){throw I=null,_chunkCR5KJUSTjs.a.error("[crudifyAdminWrapper] Initialization failed",e instanceof Error?e:{message:String(e)}),e}})(),I)}async function a(e){try{await kr();let r=_chunkLK6QVSG4js.d.getInstance();h=await _asyncOptionalChain([(await r.getTokenInfo()), 'optionalAccess', async _14 => _14.crudifyTokens, 'optionalAccess', async _15 => _15.accessToken])||null;let o=await e(),n=o.errors&&(typeof o.errors=="string"&&o.errors.includes("401")||Array.isArray(o.errors)&&o.errors.some(i=>typeof i=="string"&&i.includes("401")));return!o.success&&n?await r.refreshTokens()?(h=await _asyncOptionalChain([(await r.getTokenInfo()), 'optionalAccess', async _16 => _16.crudifyTokens, 'optionalAccess', async _17 => _17.accessToken])||null,await e()):(_chunkCR5KJUSTjs.a.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),o):o}catch(r){return _chunkCR5KJUSTjs.a.error("[crudifyAdmin] Operation error",r instanceof Error?r:{message:String(r)}),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var wr={listModules:()=>a(()=>_crudifyadminsdk2.default.listModules()),getModule:e=>a(()=>_crudifyadminsdk2.default.getModule(e)),createModule:e=>a(()=>_crudifyadminsdk2.default.createModule(e)),editModule:(e,r)=>a(()=>_crudifyadminsdk2.default.editModule(e,r)),deleteModule:e=>a(()=>_crudifyadminsdk2.default.deleteModule(e)),activateModule:e=>a(()=>_crudifyadminsdk2.default.activateModule(e)),deactivateModule:e=>a(()=>_crudifyadminsdk2.default.deactivateModule(e)),getModuleVersions:e=>a(()=>_crudifyadminsdk2.default.getModuleVersions(e)),listActions:e=>a(()=>_crudifyadminsdk2.default.listActions(e)),getAction:e=>a(()=>_crudifyadminsdk2.default.getAction(e)),createAction:e=>a(()=>_crudifyadminsdk2.default.createAction(e)),editAction:(e,r)=>a(()=>_crudifyadminsdk2.default.editAction(e,r)),deleteAction:e=>a(()=>_crudifyadminsdk2.default.deleteAction(e)),activateAction:e=>a(()=>_crudifyadminsdk2.default.activateAction(e)),deactivateAction:e=>a(()=>_crudifyadminsdk2.default.deactivateAction(e)),getActionVersions:e=>a(()=>_crudifyadminsdk2.default.getActionVersions(e)),getActionsByProfile:e=>a(()=>_crudifyadminsdk2.default.getActionsByProfile(e)),updateActionsProfiles:e=>a(()=>_crudifyadminsdk2.default.updateActionsProfiles(e)),calculatePermissions:e=>a(()=>_crudifyadminsdk2.default.calculatePermissions(e))};exports.AuthRoute = Y; exports.CRITICAL_TRANSLATIONS = _chunkAOPB3KXBjs.a; exports.CrossTabSyncManager = _chunkLK6QVSG4js.b; exports.CrudiaAutoGenerate = _chunkAOPB3KXBjs.s; exports.CrudiaFileField = _chunkAOPB3KXBjs.t; exports.CrudiaMarkdownField = _chunkAOPB3KXBjs.u; exports.CrudifyInitializationManager = _chunkLK6QVSG4js.p; exports.CrudifyInitializer = Sr; exports.CrudifyLogin = _chunkAOPB3KXBjs.l; exports.CrudifyProvider = _chunkLK6QVSG4js.i; exports.CrudifyThemeProvider = sr; exports.DEFAULT_PASSWORD_RULES = _chunkAOPB3KXBjs.k; exports.ERROR_CODES = _chunkNSV6ECYOjs.a; exports.ERROR_SEVERITY_MAP = _chunkNSV6ECYOjs.b; exports.GlobalNotificationProvider = _chunkLK6QVSG4js.f; exports.GuestRoute = $; exports.LoginComponent = _chunkAOPB3KXBjs.q; exports.POLICY_ACTIONS = _chunkAOPB3KXBjs.n; exports.PREFERRED_POLICY_ORDER = _chunkAOPB3KXBjs.o; exports.PasswordRequirements = _chunkAOPB3KXBjs.h; exports.Policies = _chunkAOPB3KXBjs.p; exports.ProtectedRoute = V; exports.SessionDebugInfo = _chunkLK6QVSG4js.m; exports.SessionLoadingScreen = g; exports.SessionManager = _chunkLK6QVSG4js.d; exports.SessionProvider = _chunkLK6QVSG4js.k; exports.SessionStatus = _chunkAOPB3KXBjs.r; exports.TokenStorage = _chunkLK6QVSG4js.a; exports.TranslationService = _chunkAOPB3KXBjs.d; exports.TranslationsProvider = _chunkAOPB3KXBjs.f; exports.UserProfileDisplay = _chunkAOPB3KXBjs.m; exports.allPasswordRulesPassed = _chunkAOPB3KXBjs.j; exports.clearCorruptedTokens = yr; exports.createErrorTranslator = _chunkCR5KJUSTjs.p; exports.crossTabSync = _chunkLK6QVSG4js.c; exports.crudify = _crudifysdk2.default; exports.crudifyAdmin = wr; exports.crudifyInitManager = _chunkLK6QVSG4js.q; exports.decodeJwtSafely = _chunkCR5KJUSTjs.r; exports.evaluatePasswordRules = _chunkAOPB3KXBjs.i; exports.extractSafeRedirectFromUrl = M; exports.getCriticalLanguages = _chunkAOPB3KXBjs.b; exports.getCriticalTranslations = _chunkAOPB3KXBjs.c; exports.getCurrentUserEmail = _chunkCR5KJUSTjs.s; exports.getErrorMessage = _chunkNSV6ECYOjs.e; exports.handleCrudifyError = _chunkNSV6ECYOjs.g; exports.hasCorruptedTokens = H; exports.hasEncryptionKeyHash = W; exports.hasStoredTokens = B; exports.isTokenExpired = _chunkCR5KJUSTjs.t; exports.logger = _chunkCR5KJUSTjs.a; exports.parseApiError = _chunkNSV6ECYOjs.c; exports.parseJavaScriptError = _chunkNSV6ECYOjs.f; exports.parseTransactionError = _chunkNSV6ECYOjs.d; exports.resolveTenantConfig = _chunkCR5KJUSTjs.b; exports.secureLocalStorage = _chunk4VN5YRYZjs.b; exports.secureSessionStorage = _chunk4VN5YRYZjs.a; exports.shouldWaitForInitialization = U; exports.translateError = _chunkCR5KJUSTjs.o; exports.translateErrorCode = _chunkCR5KJUSTjs.m; exports.translateErrorCodes = _chunkCR5KJUSTjs.n; exports.translationService = _chunkAOPB3KXBjs.e; exports.useAuth = _chunkRORGWKHPjs.b; exports.useAutoGenerate = _chunkLK6QVSG4js.o; exports.useCrudify = _chunkLK6QVSG4js.j; exports.useCrudifyInitializer = vr; exports.useCrudifyWithNotifications = _chunkRORGWKHPjs.d; exports.useData = _chunkRORGWKHPjs.c; exports.useFileUpload = _chunkLK6QVSG4js.r; exports.useGlobalNotification = _chunkLK6QVSG4js.g; exports.useSession = _chunkLK6QVSG4js.e; exports.useSessionContext = _chunkLK6QVSG4js.l; exports.useTenantConfig = _chunkCR5KJUSTjs.c; exports.useTranslations = _chunkAOPB3KXBjs.g; exports.useUserData = _chunkRORGWKHPjs.a; exports.useUserProfile = _chunkLK6QVSG4js.n; exports.validateInternalRedirect = k;
|
|
6
|
+
`});function g({stage:e="loading",message:r}){let o=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, cr,{}),_jsxruntime.jsxs.call(void 0, "div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[_jsxruntime.jsx.call(void 0, "div",{style:ur}),_jsxruntime.jsx.call(void 0, "p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:o})]})]})}var dr=/^[a-zA-Z0-9\-_./\?=&%#]+$/,fr=[/^https?:\/\//i,/^ftp:\/\//i,/^\/\//,/javascript:/i,/data:/i,/vbscript:/i,/about:/i,/\.\.\//,/\.\.\\/,/%2e%2e%2f/i,/%2e%2e%5c/i,/%2f%2f/i,/%5c%5c/i,/[\x00-\x1f\x7f-\x9f]/,/\\/],E= exports.validateInternalRedirect =(e,r="/")=>{if(!e||typeof e!="string")return r;let t=e.trim();if(!t)return r;if(!t.startsWith("/"))return _chunkMFYHD6S5js.a.warn("Open redirect blocked (relative path)",{path:e}),r;if(!dr.test(t))return _chunkMFYHD6S5js.a.warn("Open redirect blocked (invalid characters)",{path:e}),r;let o=t.toLowerCase();for(let i of fr)if(i.test(o))return _chunkMFYHD6S5js.a.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let n=t.split("?")[0].split("/").filter(Boolean);if(n.length===0)return t;for(let i of n)if(i===".."||i.includes(":")||i.length>100)return _chunkMFYHD6S5js.a.warn("Open redirect blocked (suspicious path part)",{part:i}),r;return t},M= exports.extractSafeRedirectFromUrl =(e,r="/")=>{try{let o=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!o)return r;let n=decodeURIComponent(o);return E(n,r)}catch(t){return _chunkMFYHD6S5js.a.warn("Error parsing redirect parameter",t instanceof Error?{errorMessage:t.message}:{message:String(t)}),r}};function V({children:e,loadingComponent:r,loginPath:t="/login"}){let{isAuthenticated:o,isLoading:n,isLoggingOut:i,isInitialized:y,tokens:c,error:f}=_chunk47SM45CVjs.m.call(void 0, ),u=_reactrouterdom.useLocation.call(void 0, );if(!y||n&&!i)return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:r||_jsxruntime.jsx.call(void 0, g,{stage:"validating-session"})});let l=o&&_optionalChain([c, 'optionalAccess', _2 => _2.accessToken])&&c.accessToken.length>0;if(f||!o||!l){if(i)return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:t,replace:!0});let R=u.pathname+u.search;if(u.pathname===t||u.pathname.startsWith(t))return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:t,replace:!0});let S=E(R),w=encodeURIComponent(S);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:`${t}?redirect=${w}`,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}var L="crudify_tokens",gr="crudify_enc_key";function B(){try{let e=localStorage.getItem(L);return e?e.startsWith("v2:")&&e.length>50:!1}catch (e2){return!1}}function W(){try{let e=localStorage.getItem(gr);return e!==null&&e.length>=32}catch (e3){return!1}}function U(){return B()&&W()}function H(){try{let e=localStorage.getItem(L);return e?!e.startsWith("v2:")||e.length<50:!1}catch (e4){return!1}}function yr(){try{H()&&localStorage.removeItem(L)}catch (e5){}}function Y({children:e,redirectTo:r="/",loadingComponent:t,initTimeout:o=3e3}){let{isAuthenticated:n,isInitialized:i}=_chunk47SM45CVjs.m.call(void 0, ),y=_reactrouterdom.useLocation.call(void 0, ),[c]=_react.useState.call(void 0, ()=>U()),[f,u]=_react.useState.call(void 0, !1);if(_react.useEffect.call(void 0, ()=>{if(!i&&c){let l=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(l)}},[i,c,o]),i&&n){let l=new URLSearchParams(y.search),R=M(l,r);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:R,replace:!0})}return i&&!n?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e}):c&&!f?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:t||_jsxruntime.jsx.call(void 0, g,{stage:"validating-session"})}):_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function J({children:e,behavior:r="redirect-if-authenticated",redirectTo:t="/",loadingComponent:o}){let{isAuthenticated:n,isInitialized:i}=_chunk47SM45CVjs.m.call(void 0, );return i?r==="allow-all"?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e}):n?_jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:t,replace:!0}):_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e}):_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:o||_jsxruntime.jsx.call(void 0, g,{stage:"validating-session"})})}var Q=_react.createContext.call(void 0, void 0),Sr= exports.CrudifyInitializer =({config:e,children:r,fallback:t=null,onInitialized:o,onError:n})=>{let[i,y]=_react.useState.call(void 0, !1),[c,f]=_react.useState.call(void 0, !1),[u,l]=_react.useState.call(void 0, null),R=_react.useRef.call(void 0, !1),S=_react.useRef.call(void 0, !1);_react.useEffect.call(void 0, ()=>{R.current||(_chunk47SM45CVjs.r.registerHighPriorityInitializer(),R.current=!0),S.current||(S.current=!0,(async()=>{f(!0),l(null);try{let d=_chunkMFYHD6S5js.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _3 => _3.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _4 => _4.env]),enableDebug:_optionalChain([e, 'optionalAccess', _5 => _5.enableLogging])});if(!d.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");let v=d.env||"prod";_chunkMFYHD6S5js.a.setEnvironment(v),await _chunk47SM45CVjs.r.initialize({priority:"HIGH",publicApiKey:d.publicApiKey,env:d.env||"prod",enableLogging:_optionalChain([e, 'optionalAccess', _6 => _6.enableLogging]),requestedBy:"CrudifyInitializer"}),y(!0),f(!1),o&&o()}catch(d){let v=d instanceof Error?d:new Error(String(d));l(v),f(!1),n&&n(v)}})())},[_optionalChain([e, 'optionalAccess', _7 => _7.publicApiKey]),_optionalChain([e, 'optionalAccess', _8 => _8.env]),_optionalChain([e, 'optionalAccess', _9 => _9.enableLogging]),o,n]);let w={isInitialized:i,isInitializing:c,error:u};return c&&t?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:t}):(u&&_chunkMFYHD6S5js.a.error("[CrudifyInitializer] Initialization failed",u),_jsxruntime.jsx.call(void 0, Q.Provider,{value:w,children:r}))},vr= exports.useCrudifyInitializer =()=>{let e=_react.useContext.call(void 0, Q);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};var _crudifyadminsdk = require('@nocios/crudify-admin-sdk'); var _crudifyadminsdk2 = _interopRequireDefault(_crudifyadminsdk);var X=!1,I=null,h=null;async function kr(){let r=await _chunk47SM45CVjs.e.getInstance().getTokenInfo(),t=_optionalChain([r, 'optionalAccess', _10 => _10.apiEndpointAdmin]),o=_optionalChain([r, 'optionalAccess', _11 => _11.apiKeyEndpointAdmin]);return t&&o?{apiUrl:t,apiKey:o}:_chunk47SM45CVjs.i.waitForCredentials()}async function Er(){if(!X)return I||(I=(async()=>{try{let e=_chunk47SM45CVjs.e.getInstance(),{apiUrl:r,apiKey:t}=await kr();h=await _asyncOptionalChain([(await e.getTokenInfo()), 'optionalAccess', async _12 => _12.crudifyTokens, 'optionalAccess', async _13 => _13.accessToken])||null,_crudifyadminsdk2.default.init({url:r,apiKey:t,getAdditionalHeaders:()=>h?{Authorization:`Bearer ${h}`}:{}}),X=!0}catch(e){throw I=null,_chunkMFYHD6S5js.a.error("[crudifyAdminWrapper] Initialization failed",e instanceof Error?e:{message:String(e)}),e}})(),I)}async function a(e){try{await Er();let r=_chunk47SM45CVjs.e.getInstance();h=await _asyncOptionalChain([(await r.getTokenInfo()), 'optionalAccess', async _14 => _14.crudifyTokens, 'optionalAccess', async _15 => _15.accessToken])||null;let o=await e(),n=o.errors&&(typeof o.errors=="string"&&o.errors.includes("401")||Array.isArray(o.errors)&&o.errors.some(i=>typeof i=="string"&&i.includes("401")));return!o.success&&n?await r.refreshTokens()?(h=await _asyncOptionalChain([(await r.getTokenInfo()), 'optionalAccess', async _16 => _16.crudifyTokens, 'optionalAccess', async _17 => _17.accessToken])||null,await e()):(_chunkMFYHD6S5js.a.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),o):o}catch(r){return _chunkMFYHD6S5js.a.error("[crudifyAdmin] Operation error",r instanceof Error?r:{message:String(r)}),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var wr={listModules:()=>a(()=>_crudifyadminsdk2.default.listModules()),getModule:e=>a(()=>_crudifyadminsdk2.default.getModule(e)),createModule:e=>a(()=>_crudifyadminsdk2.default.createModule(e)),editModule:(e,r)=>a(()=>_crudifyadminsdk2.default.editModule(e,r)),deleteModule:e=>a(()=>_crudifyadminsdk2.default.deleteModule(e)),activateModule:e=>a(()=>_crudifyadminsdk2.default.activateModule(e)),deactivateModule:e=>a(()=>_crudifyadminsdk2.default.deactivateModule(e)),getModuleVersions:e=>a(()=>_crudifyadminsdk2.default.getModuleVersions(e)),listActions:e=>a(()=>_crudifyadminsdk2.default.listActions(e)),getAction:e=>a(()=>_crudifyadminsdk2.default.getAction(e)),createAction:e=>a(()=>_crudifyadminsdk2.default.createAction(e)),editAction:(e,r)=>a(()=>_crudifyadminsdk2.default.editAction(e,r)),deleteAction:e=>a(()=>_crudifyadminsdk2.default.deleteAction(e)),activateAction:e=>a(()=>_crudifyadminsdk2.default.activateAction(e)),deactivateAction:e=>a(()=>_crudifyadminsdk2.default.deactivateAction(e)),getActionVersions:e=>a(()=>_crudifyadminsdk2.default.getActionVersions(e)),getActionsByProfile:e=>a(()=>_crudifyadminsdk2.default.getActionsByProfile(e)),updateActionsProfiles:e=>a(()=>_crudifyadminsdk2.default.updateActionsProfiles(e)),calculatePermissions:e=>a(()=>_crudifyadminsdk2.default.calculatePermissions(e))};exports.AuthRoute = Y; exports.CRITICAL_TRANSLATIONS = _chunkQXKVRWT3js.a; exports.CookieManager = _chunk47SM45CVjs.d; exports.CrossTabSyncManager = _chunk47SM45CVjs.b; exports.CrudiaAutoGenerate = _chunkQXKVRWT3js.s; exports.CrudiaFileField = _chunkQXKVRWT3js.t; exports.CrudiaMarkdownField = _chunkQXKVRWT3js.u; exports.CrudifyInitializationManager = _chunk47SM45CVjs.q; exports.CrudifyInitializer = Sr; exports.CrudifyLogin = _chunkQXKVRWT3js.l; exports.CrudifyProvider = _chunk47SM45CVjs.j; exports.CrudifyThemeProvider = sr; exports.DEFAULT_PASSWORD_RULES = _chunkQXKVRWT3js.k; exports.ERROR_CODES = _chunkNSV6ECYOjs.a; exports.ERROR_SEVERITY_MAP = _chunkNSV6ECYOjs.b; exports.GlobalNotificationProvider = _chunk47SM45CVjs.g; exports.GuestRoute = J; exports.LoginComponent = _chunkQXKVRWT3js.q; exports.POLICY_ACTIONS = _chunkQXKVRWT3js.n; exports.PREFERRED_POLICY_ORDER = _chunkQXKVRWT3js.o; exports.PasswordRequirements = _chunkQXKVRWT3js.h; exports.Policies = _chunkQXKVRWT3js.p; exports.ProtectedRoute = V; exports.SessionDebugInfo = _chunk47SM45CVjs.n; exports.SessionLoadingScreen = g; exports.SessionManager = _chunk47SM45CVjs.e; exports.SessionProvider = _chunk47SM45CVjs.l; exports.SessionStatus = _chunkQXKVRWT3js.r; exports.TokenStorage = _chunk47SM45CVjs.a; exports.TranslationService = _chunkQXKVRWT3js.d; exports.TranslationsProvider = _chunkQXKVRWT3js.f; exports.UserProfileDisplay = _chunkQXKVRWT3js.m; exports.allPasswordRulesPassed = _chunkQXKVRWT3js.j; exports.clearCorruptedTokens = yr; exports.createErrorTranslator = _chunkMFYHD6S5js.o; exports.crossTabSync = _chunk47SM45CVjs.c; exports.crudify = _crudifysdk2.default; exports.crudifyAdmin = wr; exports.crudifyInitManager = _chunk47SM45CVjs.r; exports.decodeJwtSafely = _chunkMFYHD6S5js.q; exports.evaluatePasswordRules = _chunkQXKVRWT3js.i; exports.extractSafeRedirectFromUrl = M; exports.getCookie = _chunkMFYHD6S5js.b; exports.getCriticalLanguages = _chunkQXKVRWT3js.b; exports.getCriticalTranslations = _chunkQXKVRWT3js.c; exports.getCurrentUserEmail = _chunkMFYHD6S5js.r; exports.getErrorMessage = _chunkNSV6ECYOjs.e; exports.handleCrudifyError = _chunkNSV6ECYOjs.g; exports.hasCorruptedTokens = H; exports.hasEncryptionKeyHash = W; exports.hasStoredTokens = B; exports.isTokenExpired = _chunkMFYHD6S5js.s; exports.logger = _chunkMFYHD6S5js.a; exports.parseApiError = _chunkNSV6ECYOjs.c; exports.parseJavaScriptError = _chunkNSV6ECYOjs.f; exports.parseTransactionError = _chunkNSV6ECYOjs.d; exports.secureLocalStorage = _chunk5HFI5CZ5js.b; exports.secureSessionStorage = _chunk5HFI5CZ5js.a; exports.shouldWaitForInitialization = U; exports.translateError = _chunkMFYHD6S5js.n; exports.translateErrorCode = _chunkMFYHD6S5js.l; exports.translateErrorCodes = _chunkMFYHD6S5js.m; exports.translationService = _chunkQXKVRWT3js.e; exports.useAuth = _chunkU5NSADERjs.b; exports.useAutoGenerate = _chunk47SM45CVjs.p; exports.useCrudify = _chunk47SM45CVjs.k; exports.useCrudifyInitializer = vr; exports.useCrudifyWithNotifications = _chunkU5NSADERjs.d; exports.useData = _chunkU5NSADERjs.c; exports.useFileUpload = _chunk47SM45CVjs.s; exports.useGlobalNotification = _chunk47SM45CVjs.h; exports.useSession = _chunk47SM45CVjs.f; exports.useSessionContext = _chunk47SM45CVjs.m; exports.useTranslations = _chunkQXKVRWT3js.g; exports.useUserData = _chunkU5NSADERjs.a; exports.useUserProfile = _chunk47SM45CVjs.o; exports.validateInternalRedirect = E;
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as j,b as ee,c as re,d as te,e as oe,f as
|
|
1
|
+
import{a as j,b as ee,c as re,d as te,e as oe,f as ie,g as ne,h as Me,i as ze,j as Le,k as Ue,l as Oe,m as Ne,n as Ge,o as De,p as Ke,q as _e,r as Ve,s as We,t as Ye,u as Je}from"./chunk-ISEMM6ZR.mjs";import{a as $e,b as Ze,c as Qe,d as er}from"./chunk-C35OZ7PU.mjs";import{a as se,b as le,c as de,d as fe,e as C,f as me,g as xe,h as Ce,i as D,j as Ae,k as Pe,l as Ie,m,n as he,o as Fe,p as Be,q as He,r as T,s as qe}from"./chunk-72CJ7DHU.mjs";import{a as Xe,b as je}from"./chunk-JNEWPO2J.mjs";import{a as Se,b as ve,c as Te,d as ke,e as Ee,f as we,g as be}from"./chunk-JAPL7EZJ.mjs";import{a as p,b,c as G,l as ae,m as pe,n as ue,o as ce,q as ge,r as ye,s as Re}from"./chunk-MGJZTOEM.mjs";import{default as kt}from"@nocios/crudify-sdk";export*from"@nocios/crudify-sdk";import{useMemo as rr}from"react";import{ThemeProvider as tr,createTheme as or,CssBaseline as ir}from"@mui/material";import{jsx as ar,jsxs as pr}from"react/jsx-runtime";var nr=(e={})=>{try{let r=b("theme");if(r){let t=JSON.parse(decodeURIComponent(r));return{...e,...t}}}catch(r){p.warn("Error parsing theme from cookie",r instanceof Error?{errorMessage:r.message}:{message:String(r)})}return e};function sr({children:e,defaultTheme:r={},disableCssBaseline:t=!1}){let o=rr(()=>{let n=nr(r);return or(n)},[r]);return pr(tr,{theme:o,children:[!t&&ar(ir,{}),e]})}import{Navigate as z,useLocation as mr}from"react-router-dom";import{Fragment as lr,jsx as k,jsxs as K}from"react/jsx-runtime";var ur={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},cr=()=>k("style",{children:`
|
|
2
2
|
@keyframes spin {
|
|
3
3
|
0% { transform: rotate(0deg); }
|
|
4
4
|
100% { transform: rotate(360deg); }
|
|
5
5
|
}
|
|
6
|
-
`});function g({stage:e="loading",message:r}){let o=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return K(lr,{children:[
|
|
6
|
+
`});function g({stage:e="loading",message:r}){let o=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return K(lr,{children:[k(cr,{}),K("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[k("div",{style:ur}),k("p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:o})]})]})}var dr=/^[a-zA-Z0-9\-_./\?=&%#]+$/,fr=[/^https?:\/\//i,/^ftp:\/\//i,/^\/\//,/javascript:/i,/data:/i,/vbscript:/i,/about:/i,/\.\.\//,/\.\.\\/,/%2e%2e%2f/i,/%2e%2e%5c/i,/%2f%2f/i,/%5c%5c/i,/[\x00-\x1f\x7f-\x9f]/,/\\/],E=(e,r="/")=>{if(!e||typeof e!="string")return r;let t=e.trim();if(!t)return r;if(!t.startsWith("/"))return p.warn("Open redirect blocked (relative path)",{path:e}),r;if(!dr.test(t))return p.warn("Open redirect blocked (invalid characters)",{path:e}),r;let o=t.toLowerCase();for(let i of fr)if(i.test(o))return p.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let n=t.split("?")[0].split("/").filter(Boolean);if(n.length===0)return t;for(let i of n)if(i===".."||i.includes(":")||i.length>100)return p.warn("Open redirect blocked (suspicious path part)",{part:i}),r;return t},M=(e,r="/")=>{try{let o=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!o)return r;let n=decodeURIComponent(o);return E(n,r)}catch(t){return p.warn("Error parsing redirect parameter",t instanceof Error?{errorMessage:t.message}:{message:String(t)}),r}};import{Fragment as _,jsx as x}from"react/jsx-runtime";function V({children:e,loadingComponent:r,loginPath:t="/login"}){let{isAuthenticated:o,isLoading:n,isLoggingOut:i,isInitialized:y,tokens:c,error:f}=m(),u=mr();if(!y||n&&!i)return x(_,{children:r||x(g,{stage:"validating-session"})});let l=o&&c?.accessToken&&c.accessToken.length>0;if(f||!o||!l){if(i)return x(z,{to:t,replace:!0});let R=u.pathname+u.search;if(u.pathname===t||u.pathname.startsWith(t))return x(z,{to:t,replace:!0});let S=E(R),w=encodeURIComponent(S);return x(z,{to:`${t}?redirect=${w}`,replace:!0})}return x(_,{children:e})}import{useState as q,useEffect as Rr}from"react";import{Navigate as xr,useLocation as Cr}from"react-router-dom";var L="crudify_tokens",gr="crudify_enc_key";function B(){try{let e=localStorage.getItem(L);return e?e.startsWith("v2:")&&e.length>50:!1}catch{return!1}}function W(){try{let e=localStorage.getItem(gr);return e!==null&&e.length>=32}catch{return!1}}function U(){return B()&&W()}function H(){try{let e=localStorage.getItem(L);return e?!e.startsWith("v2:")||e.length<50:!1}catch{return!1}}function yr(){try{H()&&localStorage.removeItem(L)}catch{}}import{Fragment as O,jsx as A}from"react/jsx-runtime";function Y({children:e,redirectTo:r="/",loadingComponent:t,initTimeout:o=3e3}){let{isAuthenticated:n,isInitialized:i}=m(),y=Cr(),[c]=q(()=>U()),[f,u]=q(!1);if(Rr(()=>{if(!i&&c){let l=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(l)}},[i,c,o]),i&&n){let l=new URLSearchParams(y.search),R=M(l,r);return A(xr,{to:R,replace:!0})}return i&&!n?A(O,{children:e}):c&&!f?A(O,{children:t||A(g,{stage:"validating-session"})}):A(O,{children:e})}import{Navigate as Ar}from"react-router-dom";import{Fragment as F,jsx as P}from"react/jsx-runtime";function J({children:e,behavior:r="redirect-if-authenticated",redirectTo:t="/",loadingComponent:o}){let{isAuthenticated:n,isInitialized:i}=m();return i?r==="allow-all"?P(F,{children:e}):n?P(Ar,{to:t,replace:!0}):P(F,{children:e}):P(F,{children:o||P(g,{stage:"validating-session"})})}import{createContext as Pr,useContext as Ir,useEffect as hr,useRef as $,useState as N}from"react";import{Fragment as Tr,jsx as Z}from"react/jsx-runtime";var Q=Pr(void 0),Sr=({config:e,children:r,fallback:t=null,onInitialized:o,onError:n})=>{let[i,y]=N(!1),[c,f]=N(!1),[u,l]=N(null),R=$(!1),S=$(!1);hr(()=>{R.current||(T.registerHighPriorityInitializer(),R.current=!0),S.current||(S.current=!0,(async()=>{f(!0),l(null);try{let d=G({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:e?.enableLogging});if(!d.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");let v=d.env||"prod";p.setEnvironment(v),await T.initialize({priority:"HIGH",publicApiKey:d.publicApiKey,env:d.env||"prod",enableLogging:e?.enableLogging,requestedBy:"CrudifyInitializer"}),y(!0),f(!1),o&&o()}catch(d){let v=d instanceof Error?d:new Error(String(d));l(v),f(!1),n&&n(v)}})())},[e?.publicApiKey,e?.env,e?.enableLogging,o,n]);let w={isInitialized:i,isInitializing:c,error:u};return c&&t?Z(Tr,{children:t}):(u&&p.error("[CrudifyInitializer] Initialization failed",u),Z(Q.Provider,{value:w,children:r}))},vr=()=>{let e=Ir(Q);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};import s from"@nocios/crudify-admin-sdk";var X=!1,I=null,h=null;async function kr(){let r=await C.getInstance().getTokenInfo(),t=r?.apiEndpointAdmin,o=r?.apiKeyEndpointAdmin;return t&&o?{apiUrl:t,apiKey:o}:D.waitForCredentials()}async function Er(){if(!X)return I||(I=(async()=>{try{let e=C.getInstance(),{apiUrl:r,apiKey:t}=await kr();h=(await e.getTokenInfo())?.crudifyTokens?.accessToken||null,s.init({url:r,apiKey:t,getAdditionalHeaders:()=>h?{Authorization:`Bearer ${h}`}:{}}),X=!0}catch(e){throw I=null,p.error("[crudifyAdminWrapper] Initialization failed",e instanceof Error?e:{message:String(e)}),e}})(),I)}async function a(e){try{await Er();let r=C.getInstance();h=(await r.getTokenInfo())?.crudifyTokens?.accessToken||null;let o=await e(),n=o.errors&&(typeof o.errors=="string"&&o.errors.includes("401")||Array.isArray(o.errors)&&o.errors.some(i=>typeof i=="string"&&i.includes("401")));return!o.success&&n?await r.refreshTokens()?(h=(await r.getTokenInfo())?.crudifyTokens?.accessToken||null,await e()):(p.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),o):o}catch(r){return p.error("[crudifyAdmin] Operation error",r instanceof Error?r:{message:String(r)}),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var wr={listModules:()=>a(()=>s.listModules()),getModule:e=>a(()=>s.getModule(e)),createModule:e=>a(()=>s.createModule(e)),editModule:(e,r)=>a(()=>s.editModule(e,r)),deleteModule:e=>a(()=>s.deleteModule(e)),activateModule:e=>a(()=>s.activateModule(e)),deactivateModule:e=>a(()=>s.deactivateModule(e)),getModuleVersions:e=>a(()=>s.getModuleVersions(e)),listActions:e=>a(()=>s.listActions(e)),getAction:e=>a(()=>s.getAction(e)),createAction:e=>a(()=>s.createAction(e)),editAction:(e,r)=>a(()=>s.editAction(e,r)),deleteAction:e=>a(()=>s.deleteAction(e)),activateAction:e=>a(()=>s.activateAction(e)),deactivateAction:e=>a(()=>s.deactivateAction(e)),getActionVersions:e=>a(()=>s.getActionVersions(e)),getActionsByProfile:e=>a(()=>s.getActionsByProfile(e)),updateActionsProfiles:e=>a(()=>s.updateActionsProfiles(e)),calculatePermissions:e=>a(()=>s.calculatePermissions(e))};export{Y as AuthRoute,j as CRITICAL_TRANSLATIONS,fe as CookieManager,le as CrossTabSyncManager,We as CrudiaAutoGenerate,Ye as CrudiaFileField,Je as CrudiaMarkdownField,He as CrudifyInitializationManager,Sr as CrudifyInitializer,Oe as CrudifyLogin,Ae as CrudifyProvider,sr as CrudifyThemeProvider,Ue as DEFAULT_PASSWORD_RULES,Se as ERROR_CODES,ve as ERROR_SEVERITY_MAP,xe as GlobalNotificationProvider,J as GuestRoute,_e as LoginComponent,Ge as POLICY_ACTIONS,De as PREFERRED_POLICY_ORDER,Me as PasswordRequirements,Ke as Policies,V as ProtectedRoute,he as SessionDebugInfo,g as SessionLoadingScreen,C as SessionManager,Ie as SessionProvider,Ve as SessionStatus,se as TokenStorage,te as TranslationService,ie as TranslationsProvider,Ne as UserProfileDisplay,Le as allPasswordRulesPassed,yr as clearCorruptedTokens,ce as createErrorTranslator,de as crossTabSync,kt as crudify,wr as crudifyAdmin,T as crudifyInitManager,ge as decodeJwtSafely,ze as evaluatePasswordRules,M as extractSafeRedirectFromUrl,b as getCookie,ee as getCriticalLanguages,re as getCriticalTranslations,ye as getCurrentUserEmail,Ee as getErrorMessage,be as handleCrudifyError,H as hasCorruptedTokens,W as hasEncryptionKeyHash,B as hasStoredTokens,Re as isTokenExpired,p as logger,Te as parseApiError,we as parseJavaScriptError,ke as parseTransactionError,je as secureLocalStorage,Xe as secureSessionStorage,U as shouldWaitForInitialization,ue as translateError,ae as translateErrorCode,pe as translateErrorCodes,oe as translationService,Ze as useAuth,Be as useAutoGenerate,Pe as useCrudify,vr as useCrudifyInitializer,er as useCrudifyWithNotifications,Qe as useData,qe as useFileUpload,Ce as useGlobalNotification,me as useSession,m as useSessionContext,ne as useTranslations,$e as useUserData,Fe as useUserProfile,E as validateInternalRedirect};
|
package/dist/utils.d.mts
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { E as ERROR_CODES, j as ERROR_SEVERITY_MAP, n as ErrorCode, o as ErrorSeverity, q as ErrorTranslationConfig, P as ParsedError, m 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, l as translateError, t as translateErrorCode, k as translateErrorCodes } from './errorTranslation-qwwQTvCO.mjs';
|
|
2
2
|
import './api-B4uXiHF0.mjs';
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* Sistema centralizado de resolución de configuración para npm-crudify-ui
|
|
6
|
+
*
|
|
7
|
+
* Prioridad:
|
|
8
|
+
* 1. Cookies (producción con Lambda@Edge multitenancy) - MAYOR PRIORIDAD
|
|
9
|
+
* 2. Props explícitas (desarrollo local con .env) - FALLBACK
|
|
10
|
+
* 3. Error (ninguna configuración disponible)
|
|
11
|
+
*
|
|
12
|
+
* En producción, Lambda@Edge inyecta cookies con la configuración del tenant.
|
|
13
|
+
* En desarrollo local, no hay cookies y se usan las variables de .env como fallback.
|
|
14
|
+
*/
|
|
15
|
+
type CrudifyEnvironment = "dev" | "stg" | "api" | "prod";
|
|
16
|
+
interface ResolvedConfig {
|
|
17
|
+
publicApiKey?: string;
|
|
18
|
+
env?: CrudifyEnvironment;
|
|
19
|
+
appName?: string;
|
|
20
|
+
logo?: string;
|
|
21
|
+
loginActions?: string[];
|
|
22
|
+
featureKeys?: string[];
|
|
23
|
+
theme?: Record<string, unknown>;
|
|
24
|
+
configSource: "props" | "cookies" | "none";
|
|
25
|
+
}
|
|
26
|
+
interface ConfigResolverOptions {
|
|
27
|
+
publicApiKey?: string;
|
|
28
|
+
env?: CrudifyEnvironment;
|
|
29
|
+
appName?: string;
|
|
30
|
+
logo?: string;
|
|
31
|
+
loginActions?: string[];
|
|
32
|
+
featureKeys?: string[];
|
|
33
|
+
enableDebug?: boolean;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Resolves Crudify configuration with the following priority:
|
|
37
|
+
* 1. Cookies (production with Lambda multitenancy) - HIGHEST PRIORITY
|
|
38
|
+
* 2. Props (local development with .env) - FALLBACK
|
|
39
|
+
* 3. None (error - missing configuration)
|
|
40
|
+
*
|
|
41
|
+
* This resolver is responsible for reading cookies and applying correct priority.
|
|
42
|
+
*/
|
|
43
|
+
declare function resolveConfig(options?: ConfigResolverOptions): ResolvedConfig;
|
|
44
|
+
/**
|
|
45
|
+
* React hook to use config resolver
|
|
46
|
+
* Useful when you need config in a component
|
|
47
|
+
*/
|
|
48
|
+
declare function useResolvedConfig(options?: ConfigResolverOptions): ResolvedConfig;
|
|
49
|
+
|
|
4
50
|
/**
|
|
5
51
|
* Event Bus para coordinar acciones de autenticación
|
|
6
52
|
* Previene race conditions y asegura respuesta única a errores
|
|
@@ -126,4 +172,4 @@ declare class NavigationTracker {
|
|
|
126
172
|
isActive(): boolean;
|
|
127
173
|
}
|
|
128
174
|
|
|
129
|
-
export { type AuthEvent, type AuthEventDetails, type AuthEventType, NavigationTracker, authEventBus };
|
|
175
|
+
export { type AuthEvent, type AuthEventDetails, type AuthEventType, type ConfigResolverOptions, type CrudifyEnvironment, NavigationTracker, type ResolvedConfig, authEventBus, resolveConfig, useResolvedConfig };
|
package/dist/utils.d.ts
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { E as ERROR_CODES, j as ERROR_SEVERITY_MAP, n as ErrorCode, o as ErrorSeverity, q as ErrorTranslationConfig, P as ParsedError, m 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, l as translateError, t as translateErrorCode, k as translateErrorCodes } from './errorTranslation-DGdrMidg.js';
|
|
2
2
|
import './api-B4uXiHF0.js';
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* Sistema centralizado de resolución de configuración para npm-crudify-ui
|
|
6
|
+
*
|
|
7
|
+
* Prioridad:
|
|
8
|
+
* 1. Cookies (producción con Lambda@Edge multitenancy) - MAYOR PRIORIDAD
|
|
9
|
+
* 2. Props explícitas (desarrollo local con .env) - FALLBACK
|
|
10
|
+
* 3. Error (ninguna configuración disponible)
|
|
11
|
+
*
|
|
12
|
+
* En producción, Lambda@Edge inyecta cookies con la configuración del tenant.
|
|
13
|
+
* En desarrollo local, no hay cookies y se usan las variables de .env como fallback.
|
|
14
|
+
*/
|
|
15
|
+
type CrudifyEnvironment = "dev" | "stg" | "api" | "prod";
|
|
16
|
+
interface ResolvedConfig {
|
|
17
|
+
publicApiKey?: string;
|
|
18
|
+
env?: CrudifyEnvironment;
|
|
19
|
+
appName?: string;
|
|
20
|
+
logo?: string;
|
|
21
|
+
loginActions?: string[];
|
|
22
|
+
featureKeys?: string[];
|
|
23
|
+
theme?: Record<string, unknown>;
|
|
24
|
+
configSource: "props" | "cookies" | "none";
|
|
25
|
+
}
|
|
26
|
+
interface ConfigResolverOptions {
|
|
27
|
+
publicApiKey?: string;
|
|
28
|
+
env?: CrudifyEnvironment;
|
|
29
|
+
appName?: string;
|
|
30
|
+
logo?: string;
|
|
31
|
+
loginActions?: string[];
|
|
32
|
+
featureKeys?: string[];
|
|
33
|
+
enableDebug?: boolean;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Resolves Crudify configuration with the following priority:
|
|
37
|
+
* 1. Cookies (production with Lambda multitenancy) - HIGHEST PRIORITY
|
|
38
|
+
* 2. Props (local development with .env) - FALLBACK
|
|
39
|
+
* 3. None (error - missing configuration)
|
|
40
|
+
*
|
|
41
|
+
* This resolver is responsible for reading cookies and applying correct priority.
|
|
42
|
+
*/
|
|
43
|
+
declare function resolveConfig(options?: ConfigResolverOptions): ResolvedConfig;
|
|
44
|
+
/**
|
|
45
|
+
* React hook to use config resolver
|
|
46
|
+
* Useful when you need config in a component
|
|
47
|
+
*/
|
|
48
|
+
declare function useResolvedConfig(options?: ConfigResolverOptions): ResolvedConfig;
|
|
49
|
+
|
|
4
50
|
/**
|
|
5
51
|
* Event Bus para coordinar acciones de autenticación
|
|
6
52
|
* Previene race conditions y asegura respuesta única a errores
|
|
@@ -126,4 +172,4 @@ declare class NavigationTracker {
|
|
|
126
172
|
isActive(): boolean;
|
|
127
173
|
}
|
|
128
174
|
|
|
129
|
-
export { type AuthEvent, type AuthEventDetails, type AuthEventType, NavigationTracker, authEventBus };
|
|
175
|
+
export { type AuthEvent, type AuthEventDetails, type AuthEventType, type ConfigResolverOptions, type CrudifyEnvironment, NavigationTracker, type ResolvedConfig, authEventBus, resolveConfig, useResolvedConfig };
|