@nocios/crudify-ui 4.4.26 → 4.4.28

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.
@@ -131,4 +131,91 @@ interface CrudiaAutoGenerateProps {
131
131
  */
132
132
  declare const CrudiaAutoGenerate: React.FC<CrudiaAutoGenerateProps>;
133
133
 
134
- export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, CrudiaAutoGenerate as a, type CrudifyLoginConfig as b, type CrudifyLoginProps as c, type CrudifyLoginTranslations as d, type UserLoginData as e, type PolicyAction as f, type CrudiaAutoGenerateProps as g, POLICY_ACTIONS as h, PREFERRED_POLICY_ORDER as i };
134
+ /**
135
+ * Componente de campo de archivo con:
136
+ * - Drag & drop
137
+ * - Vista previa de archivos
138
+ * - Progress bar durante upload
139
+ * - Eliminar archivos (soft delete)
140
+ * - Validación de tipos y tamaños
141
+ * - Soporte single/multiple
142
+ */
143
+
144
+ /**
145
+ * Props del componente CrudiaFileField
146
+ */
147
+ interface CrudiaFileFieldProps {
148
+ /** Label del campo */
149
+ label?: string;
150
+ /** Tipos MIME permitidos (ej: ["image/png", "image/jpeg"]) */
151
+ accept?: string[];
152
+ /** Tamaño máximo por archivo en bytes */
153
+ maxFileSize?: number;
154
+ /** Permitir múltiples archivos */
155
+ multiple?: boolean;
156
+ /** Número máximo de archivos (solo si multiple=true) */
157
+ maxFiles?: number;
158
+ /** Número mínimo de archivos requeridos */
159
+ minFiles?: number;
160
+ /** Campo requerido */
161
+ required?: boolean;
162
+ /** Campo deshabilitado */
163
+ disabled?: boolean;
164
+ /** Error externo */
165
+ error?: boolean;
166
+ /** Texto de ayuda o error */
167
+ helperText?: string;
168
+ /**
169
+ * Callback cuando cambian los filePaths de archivos completados
170
+ * Los filePaths son rutas relativas sin subscriberKey
171
+ */
172
+ onChange?: (filePaths: string[]) => void;
173
+ /** Callback cuando se valida el campo */
174
+ onValidation?: (isValid: boolean, error: string | null) => void;
175
+ /** Archivos existentes (para edición) - usar filePath (ruta relativa sin subscriberKey) */
176
+ initialFiles?: Array<{
177
+ filePath: string;
178
+ name: string;
179
+ size?: number;
180
+ contentType?: string;
181
+ }>;
182
+ /** Texto placeholder para drag zone */
183
+ placeholder?: string;
184
+ /** Mostrar lista de archivos */
185
+ showFileList?: boolean;
186
+ }
187
+ /**
188
+ * Componente principal de campo de archivo
189
+ *
190
+ * @example
191
+ * ```tsx
192
+ * // Uso básico - archivo único
193
+ * <CrudiaFileField
194
+ * label="Documento"
195
+ * accept={["application/pdf"]}
196
+ * onChange={(filePaths) => setFormData({ ...formData, document: filePaths[0] })}
197
+ * />
198
+ *
199
+ * // Múltiples archivos con límites
200
+ * <CrudiaFileField
201
+ * label="Imágenes"
202
+ * accept={["image/png", "image/jpeg"]}
203
+ * multiple
204
+ * maxFiles={5}
205
+ * minFiles={1}
206
+ * maxFileSize={5 * 1024 * 1024}
207
+ * onChange={(filePaths) => setFormData({ ...formData, images: filePaths })}
208
+ * />
209
+ *
210
+ * // Con archivos iniciales (modo edición)
211
+ * <CrudiaFileField
212
+ * label="Adjuntos"
213
+ * multiple
214
+ * initialFiles={existingFiles}
215
+ * onChange={handleFilesChange}
216
+ * />
217
+ * ```
218
+ */
219
+ declare const CrudiaFileField: React.FC<CrudiaFileFieldProps>;
220
+
221
+ export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, CrudiaAutoGenerate as a, CrudiaFileField as b, type CrudifyLoginConfig as c, type CrudifyLoginProps as d, type CrudifyLoginTranslations as e, type UserLoginData as f, type PolicyAction as g, type CrudiaAutoGenerateProps as h, type CrudiaFileFieldProps as i, POLICY_ACTIONS as j, PREFERRED_POLICY_ORDER as k };
@@ -131,4 +131,91 @@ interface CrudiaAutoGenerateProps {
131
131
  */
132
132
  declare const CrudiaAutoGenerate: React.FC<CrudiaAutoGenerateProps>;
133
133
 
134
- export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, CrudiaAutoGenerate as a, type CrudifyLoginConfig as b, type CrudifyLoginProps as c, type CrudifyLoginTranslations as d, type UserLoginData as e, type PolicyAction as f, type CrudiaAutoGenerateProps as g, POLICY_ACTIONS as h, PREFERRED_POLICY_ORDER as i };
134
+ /**
135
+ * Componente de campo de archivo con:
136
+ * - Drag & drop
137
+ * - Vista previa de archivos
138
+ * - Progress bar durante upload
139
+ * - Eliminar archivos (soft delete)
140
+ * - Validación de tipos y tamaños
141
+ * - Soporte single/multiple
142
+ */
143
+
144
+ /**
145
+ * Props del componente CrudiaFileField
146
+ */
147
+ interface CrudiaFileFieldProps {
148
+ /** Label del campo */
149
+ label?: string;
150
+ /** Tipos MIME permitidos (ej: ["image/png", "image/jpeg"]) */
151
+ accept?: string[];
152
+ /** Tamaño máximo por archivo en bytes */
153
+ maxFileSize?: number;
154
+ /** Permitir múltiples archivos */
155
+ multiple?: boolean;
156
+ /** Número máximo de archivos (solo si multiple=true) */
157
+ maxFiles?: number;
158
+ /** Número mínimo de archivos requeridos */
159
+ minFiles?: number;
160
+ /** Campo requerido */
161
+ required?: boolean;
162
+ /** Campo deshabilitado */
163
+ disabled?: boolean;
164
+ /** Error externo */
165
+ error?: boolean;
166
+ /** Texto de ayuda o error */
167
+ helperText?: string;
168
+ /**
169
+ * Callback cuando cambian los filePaths de archivos completados
170
+ * Los filePaths son rutas relativas sin subscriberKey
171
+ */
172
+ onChange?: (filePaths: string[]) => void;
173
+ /** Callback cuando se valida el campo */
174
+ onValidation?: (isValid: boolean, error: string | null) => void;
175
+ /** Archivos existentes (para edición) - usar filePath (ruta relativa sin subscriberKey) */
176
+ initialFiles?: Array<{
177
+ filePath: string;
178
+ name: string;
179
+ size?: number;
180
+ contentType?: string;
181
+ }>;
182
+ /** Texto placeholder para drag zone */
183
+ placeholder?: string;
184
+ /** Mostrar lista de archivos */
185
+ showFileList?: boolean;
186
+ }
187
+ /**
188
+ * Componente principal de campo de archivo
189
+ *
190
+ * @example
191
+ * ```tsx
192
+ * // Uso básico - archivo único
193
+ * <CrudiaFileField
194
+ * label="Documento"
195
+ * accept={["application/pdf"]}
196
+ * onChange={(filePaths) => setFormData({ ...formData, document: filePaths[0] })}
197
+ * />
198
+ *
199
+ * // Múltiples archivos con límites
200
+ * <CrudiaFileField
201
+ * label="Imágenes"
202
+ * accept={["image/png", "image/jpeg"]}
203
+ * multiple
204
+ * maxFiles={5}
205
+ * minFiles={1}
206
+ * maxFileSize={5 * 1024 * 1024}
207
+ * onChange={(filePaths) => setFormData({ ...formData, images: filePaths })}
208
+ * />
209
+ *
210
+ * // Con archivos iniciales (modo edición)
211
+ * <CrudiaFileField
212
+ * label="Adjuntos"
213
+ * multiple
214
+ * initialFiles={existingFiles}
215
+ * onChange={handleFilesChange}
216
+ * />
217
+ * ```
218
+ */
219
+ declare const CrudiaFileField: React.FC<CrudiaFileFieldProps>;
220
+
221
+ export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, CrudiaAutoGenerate as a, CrudiaFileField as b, type CrudifyLoginConfig as c, type CrudifyLoginProps as d, type CrudifyLoginTranslations as e, type UserLoginData as f, type PolicyAction as g, type CrudiaAutoGenerateProps as h, type CrudiaFileFieldProps as i, POLICY_ACTIONS as j, PREFERRED_POLICY_ORDER as k };
@@ -0,0 +1 @@
1
+ import{b as ie,d as ce,h as F,i as ue,j as de,k as fe}from"./chunk-6GPSBDW6.mjs";import{createContext as Ce,useContext as Pe,useEffect as we,useState as $}from"react";import X from"@nocios/crudify-browser";var re=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(t){this.credentials=t,this.isReady=!0,this.listeners.forEach(e=>{try{e(t)}catch(i){console.error("[CredentialsEventBus] Error in listener:",i)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(t=>{this.listeners.push(t)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},ge=re.getInstance();import{jsx as Le}from"react/jsx-runtime";var pe=Ce(void 0),ye=({config:r,children:t})=>{let[e,i]=$(!0),[s,u]=$(null),[T,v]=$(!1),[S,f]=$(""),[x,c]=$();we(()=>{if(!r.publicApiKey){u("No publicApiKey provided"),i(!1),v(!1);return}let a=`${r.publicApiKey}-${r.env}`;if(a===S&&T){i(!1);return}(async()=>{i(!0),u(null),v(!1);try{X.config(r.env||"prod");let g=await X.init(r.publicApiKey,"none");if(c(g),typeof X.transaction=="function"&&typeof X.login=="function")v(!0),f(a),g.apiEndpointAdmin&&g.apiKeyEndpointAdmin&&ge.notifyCredentialsReady({apiUrl:g.apiEndpointAdmin,apiKey:g.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(g){let A=g instanceof Error?g.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",g),u(A),v(!1)}finally{i(!1)}})()},[r.publicApiKey,r.env,S,T]);let o={crudify:T?X:null,isLoading:e,error:s,isInitialized:T,adminCredentials:x};return Le(pe.Provider,{value:o,children:t})},he=()=>{let r=Pe(pe);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import B from"crypto-js";var d=class d{static setStorageType(t){d.storageType=t}static generateEncryptionKey(){let t=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return B.SHA256(t).toString()}static getEncryptionKey(){if(d.encryptionKey)return d.encryptionKey;let t=window.localStorage;if(!t)return d.encryptionKey=d.generateEncryptionKey(),d.encryptionKey;try{let e=t.getItem(d.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=d.generateEncryptionKey(),t.setItem(d.ENCRYPTION_KEY_STORAGE,e)),d.encryptionKey=e,e}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),d.encryptionKey=d.generateEncryptionKey(),d.encryptionKey}}static isStorageAvailable(t){try{let e=window[t],i="__storage_test__";return e.setItem(i,"test"),e.removeItem(i),!0}catch{return!1}}static getStorage(){return d.storageType==="none"?null:d.isStorageAvailable(d.storageType)?window[d.storageType]:(console.warn(`Crudify: ${d.storageType} not available, tokens won't persist`),null)}static encrypt(t){try{let e=d.getEncryptionKey();return B.AES.encrypt(t,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),t}}static decrypt(t){try{let e=d.getEncryptionKey();return B.AES.decrypt(t,e).toString(B.enc.Utf8)||t}catch(e){return console.error("Crudify: Decryption failed",e),t}}static saveTokens(t){let e=d.getStorage();if(e)try{let i={accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt,savedAt:Date.now()},s=d.encrypt(JSON.stringify(i));e.setItem(d.TOKEN_KEY,s),console.debug("Crudify: Tokens saved successfully")}catch(i){console.error("Crudify: Failed to save tokens",i)}}static getTokens(){let t=d.getStorage();if(!t)return null;try{let e=t.getItem(d.TOKEN_KEY);if(!e)return null;let i=d.decrypt(e),s=JSON.parse(i);return!s.accessToken||!s.refreshToken||!s.expiresAt||!s.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),d.clearTokens(),null):Date.now()>=s.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),d.clearTokens(),null):{accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),d.clearTokens(),null}}static clearTokens(){let t=d.getStorage();if(t)try{t.removeItem(d.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{d.clearTokens(),d.encryptionKey=null;let t=window.localStorage;t&&t.removeItem(d.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(t){console.error("Crudify: Failed to rotate encryption key",t)}}static hasValidTokens(){return d.getTokens()!==null}static getExpirationInfo(){let t=d.getTokens();if(!t)return null;let e=Date.now();return{accessExpired:e>=t.expiresAt,refreshExpired:e>=t.refreshExpiresAt,accessExpiresIn:Math.max(0,t.expiresAt-e),refreshExpiresIn:Math.max(0,t.refreshExpiresAt-e)}}static updateAccessToken(t,e){let i=d.getTokens();if(!i){console.warn("Crudify: Cannot update access token, no existing tokens found");return}d.saveTokens({...i,accessToken:t,expiresAt:e})}static subscribeToChanges(t){let e=i=>{if(i.key===d.TOKEN_KEY){if(i.newValue===null){console.debug("Crudify: Tokens removed in another tab"),t(null);return}if(i.newValue){console.debug("Crudify: Tokens updated in another tab");let s=d.getTokens();t(s)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};d.TOKEN_KEY="crudify_tokens",d.ENCRYPTION_KEY_STORAGE="crudify_enc_key",d.encryptionKey=null,d.storageType="localStorage";var E=d;import C from"@nocios/crudify-browser";var q=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(t={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...t},E.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),C.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),F.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=E.getTokens();e?E.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):E.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(t,e){try{let i=await C.login(t,e);if(!i.success)return{success:!1,error:this.formatError(i.errors),rawResponse:i};let s=E.getTokens(),u={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt,apiEndpointAdmin:s?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:s?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return E.saveTokens(u),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(u),{success:!0,tokens:u,data:i.data}}catch(i){return console.error("[SessionManager] Login error:",i),{success:!1,error:i instanceof Error?i.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await C.logout(),E.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(t){this.log("Logout error:",t),E.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let t=E.getTokens();if(!t)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=t.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),E.clearTokens(),!1;if(C.setTokens({accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt}),C.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<t.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let s=E.getTokens();return s&&this.config.onSessionRestored?.(s),!0}return E.clearTokens(),await C.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(t),!0}catch(t){return this.log("Session restore error:",t),E.clearTokens(),await C.logout(),!1}}isAuthenticated(){return C.isLogin()||E.hasValidTokens()}getTokenInfo(){let t=C.getTokenData(),e=E.getExpirationInfo(),i=E.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:t,storageInfo:e,hasValidTokens:E.hasValidTokens(),apiEndpointAdmin:i?.apiEndpointAdmin,apiKeyEndpointAdmin:i?.apiKeyEndpointAdmin}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let t=await C.refreshAccessToken();if(!t.success)return this.log("Token refresh failed:",t.errors),E.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt};return E.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(t){return this.log("Token refresh error:",t),E.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){C.setResponseInterceptor(async t=>{this.updateLastActivity();let e=this.detectAuthorizationError(t);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),F.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),t;e.shouldTriggerLogout&&(E.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),F.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),F.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return t}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let t=C.getTokenData();if(t&&t.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";C.config(e);let i=this.config.publicApiKey,s=this.config.enableLogging?"debug":"none",u=await C.init(i,s);if(u&&u.success===!1&&u.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(u.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(t){throw console.error("[SessionManager] Failed to initialize crudify:",t),t}}detectAuthorizationError(t){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(t.errors&&Array.isArray(t.errors)){let i=t.errors.find(s=>s.errorType==="Unauthorized"||s.message?.includes("Unauthorized")||s.message?.includes("Not Authorized")||s.message?.includes("NOT_AUTHORIZED")||s.message?.includes("Token")||s.message?.includes("TOKEN")||s.message?.includes("Authentication")||s.message?.includes("UNAUTHENTICATED")||s.extensions?.code==="UNAUTHENTICATED"||s.extensions?.code==="FORBIDDEN");i&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=i,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(i.message?.includes("TOKEN")||i.message?.includes("Token"))&&(e.isTokenExpired=!0),i.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&t.errors&&typeof t.errors=="object"&&!Array.isArray(t.errors)){let s=Object.values(t.errors).flat().find(u=>typeof u=="string"&&(u.includes("NOT_AUTHORIZED")||u.includes("TOKEN_REFRESH_FAILED")||u.includes("TOKEN_HAS_EXPIRED")||u.includes("PLEASE_LOGIN")||u.includes("Unauthorized")||u.includes("UNAUTHENTICATED")||u.includes("SESSION_EXPIRED")||u.includes("INVALID_TOKEN")));s&&typeof s=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=t.errors,e.shouldTriggerLogout=!0,s.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):s.includes("TOKEN_HAS_EXPIRED")||s.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):s.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&t.data?.response?.status){let i=t.data.response.status.toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=t.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&t.data?.response?.data)try{let i=typeof t.data.response.data=="string"?JSON.parse(t.data.response.data):t.data.response.data;(i.error==="REFRESH_TOKEN_INVALID"||i.error==="TOKEN_EXPIRED"||i.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=i,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,i.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch{}if(!e.isAuthError&&t.errorCode){let i=t.errorCode.toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED"||i==="TOKEN_EXPIRED"||i==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:i},e.shouldTriggerLogout=!0,i==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let t=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return t>e?(this.log(`Inactivity timeout: ${Math.floor(t/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){E.clearTokens(),C.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?ce("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(t,...e){this.config.enableLogging&&console.log(`[SessionManager] ${t}`,...e)}formatError(t){return t?typeof t=="string"?t:typeof t=="object"?Object.values(t).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as De,useEffect as W,useCallback as M}from"react";function me(r={}){let[t,e]=De({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),i=q.getInstance(),s=M(async()=>{console.log("\u{1F535} [useSession] initialize() CALLED"),console.log("\u{1F50D} [useSession] options received:",{autoRestore:r.autoRestore,enableLogging:r.enableLogging,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin});try{e(n=>({...n,isLoading:!0,error:null}));let c={autoRestore:r.autoRestore??!0,enableLogging:r.enableLogging??!1,showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:"Session expired"})),r.onSessionExpired?.()},onSessionRestored:n=>{e(g=>({...g,isAuthenticated:!0,tokens:n,error:null})),r.onSessionRestored?.(n)},onLoginSuccess:n=>{e(g=>({...g,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",c),await i.initialize(c),console.log("\u2705 [useSession] sessionManager.initialize() completed"),i.setupResponseInterceptor();let o=i.isAuthenticated(),a=i.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",o),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",a),e(n=>({...n,isAuthenticated:o,isInitialized:!0,isLoading:!1,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let o=c instanceof Error?c.message:"Initialization failed";e(a=>({...a,isLoading:!1,isInitialized:!0,error:o}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),u=M(async(c,o)=>{e(a=>({...a,isLoading:!0,error:null}));try{let a=await i.login(c,o);return a.success&&a.tokens?e(n=>({...n,isAuthenticated:!0,tokens:a.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),a}catch(a){let n=a instanceof Error?a.message:"Login failed",g=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(A=>({...A,isAuthenticated:!1,tokens:null,isLoading:!1,error:g?null:n})),{success:!1,error:n}}},[i]),T=M(async()=>{e(c=>({...c,isLoading:!0}));try{await i.logout(),e(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){e(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[i]),v=M(async()=>{try{let c=await i.refreshTokens();if(c){let o=i.getTokenInfo();e(a=>({...a,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(o=>({...o,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return e(o=>({...o,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[i]),S=M(()=>{e(c=>({...c,error:null}))},[]),f=M(()=>i.getTokenInfo(),[i]);W(()=>{s()},[s]),W(()=>{if(!t.isAuthenticated||!t.tokens)return;let c=ue.getInstance(),o=()=>{i.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},a=c.subscribe(o);window.addEventListener("popstate",o);let n=()=>{let P=i.getTokenInfo().crudifyTokens.expiresIn||0;return P<300*1e3?30*1e3:P<1800*1e3?60*1e3:120*1e3},g,A=()=>{let R=n();g=setTimeout(async()=>{if(i.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),A();return}let P=i.getTokenInfo(),k=P.crudifyTokens.expiresIn||0,D=(P.crudifyTokens.expiresAt||0)-(Date.now()-k),m=D*.5;if(k>0&&k<=m){let _=Math.round(k/D*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${_}% of TTL (${Math.round(k/6e4)}min remaining), refreshing...`),e(l=>({...l,isLoading:!0})),await i.refreshTokens()){let l=i.getTokenInfo();e(y=>({...y,isLoading:!1,tokens:l.crudifyTokens.accessToken?{accessToken:l.crudifyTokens.accessToken,refreshToken:l.crudifyTokens.refreshToken,expiresAt:l.crudifyTokens.expiresAt,refreshExpiresAt:l.crudifyTokens.refreshExpiresAt}:null}))}else e(l=>({...l,isLoading:!1,isAuthenticated:!1,tokens:null}))}let G=i.getTimeSinceLastActivity(),z=1800*1e3;G>z?(r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout (30min) - logging out"),await T()):A()},R)};return A(),()=>{clearTimeout(g),window.removeEventListener("popstate",o),a()}},[t.isAuthenticated,t.tokens,i,r.enableLogging,T]),W(()=>{let c=F.subscribe(async o=>{if(r.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${o.type}`),o.type==="TOKEN_EXPIRED"){if(i.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping TOKEN_EXPIRED handler");return}r.enableLogging&&console.log("\u{1F504} Token expired, attempting refresh..."),e(a=>({...a,isLoading:!0}));try{if(await i.refreshTokens()){r.enableLogging&&console.log("\u2705 Token refreshed successfully");let n=i.getTokenInfo();e(g=>({...g,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else r.enableLogging&&console.log("\u274C Token refresh failed, session expired"),F.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(a){r.enableLogging&&console.error("\u274C Error during token refresh:",a),F.emit("SESSION_EXPIRED",{message:a instanceof Error?a.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(o.type==="SESSION_EXPIRED"||o.type==="TOKEN_REFRESH_FAILED")&&(r.enableLogging&&console.log(`\u{1F534} Session expired (${o.type}), logging out...`),e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:o.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>c()},[r.enableLogging,r.onSessionExpired,i]),W(()=>{let c=E.subscribeToChanges(o=>{o?(r.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(a=>({...a,tokens:o,isAuthenticated:!0}))):(r.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(a=>({...a,isAuthenticated:!1,tokens:null})),F.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[r.enableLogging]);let x=M(()=>{i.updateLastActivity()},[i]);return{...t,login:u,logout:T,refreshTokens:v,clearError:S,getTokenInfo:f,updateActivity:x,isExpiringSoon:t.tokens?t.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:t.tokens?Math.max(0,t.tokens.expiresAt-Date.now()):0,refreshExpiresIn:t.tokens?Math.max(0,t.tokens.refreshExpiresAt-Date.now()):0}}import{useState as Ee,createContext as Fe,useContext as Ke,useCallback as j,useEffect as Oe}from"react";import{Snackbar as Ue,Alert as ze,Box as Me,Portal as He}from"@mui/material";import{v4 as Ge}from"uuid";import _e from"dompurify";import{jsx as H,jsxs as Xe}from"react/jsx-runtime";var Te=Fe(null),Ve=r=>_e.sanitize(r,{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}),ne=({children:r,maxNotifications:t=5,defaultAutoHideDuration:e=6e3,position:i={vertical:"top",horizontal:"right"},enabled:s=!1,allowHtml:u=!1})=>{let[T,v]=Ee([]),S=j((o,a="info",n)=>{if(!s)return"";if(!o||typeof o!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";o.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),o=o.substring(0,1e3)+"...");let g=Ge(),A={id:g,message:o,severity:a,autoHideDuration:n?.autoHideDuration??e,persistent:n?.persistent??!1,allowHtml:n?.allowHtml??u};return v(R=>[...R.length>=t?R.slice(-(t-1)):R,A]),g},[t,e,s,u]),f=j(o=>{v(a=>a.filter(n=>n.id!==o))},[]),x=j(()=>{v([])},[]),c={showNotification:S,hideNotification:f,clearAllNotifications:x};return Xe(Te.Provider,{value:c,children:[r,s&&H(He,{children:H(Me,{sx:{position:"fixed",zIndex:9999,[i.vertical]:(i.vertical==="top",24),[i.horizontal]:i.horizontal==="right"||i.horizontal==="left"?24:"50%",...i.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:i.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:T.map(o=>H($e,{notification:o,onClose:()=>f(o.id)},o.id))})})]})},$e=({notification:r,onClose:t})=>{let[e,i]=Ee(!0),s=j((u,T)=>{T!=="clickaway"&&(i(!1),setTimeout(t,300))},[t]);return Oe(()=>{if(!r.persistent&&r.autoHideDuration){let u=setTimeout(()=>{s()},r.autoHideDuration);return()=>clearTimeout(u)}},[r.autoHideDuration,r.persistent,s]),H(Ue,{open:e,onClose:s,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:H(ze,{variant:"filled",severity:r.severity,onClose:s,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?H("span",{dangerouslySetInnerHTML:{__html:Ve(r.message)}}):H("span",{children:r.message})})})},ve=()=>{let r=Ke(Te);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import Ye,{createContext as Be,useContext as qe,useMemo as oe}from"react";import{Fragment as je,jsx as N,jsxs as K}from"react/jsx-runtime";var ke=Be(void 0);function Ae({children:r,options:t={},config:e,showNotifications:i=!1,notificationOptions:s={}}){let u;try{let{showNotification:n}=ve();u=n}catch{}let T={};try{let n=he();n.isInitialized&&n.adminCredentials&&(T=n.adminCredentials)}catch{}let v=oe(()=>{let n=ie({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:t?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,t?.enableLogging]),S=Ye.useMemo(()=>({...t,showNotification:u,apiEndpointAdmin:T.apiEndpointAdmin,apiKeyEndpointAdmin:T.apiKeyEndpointAdmin,publicApiKey:v.publicApiKey,env:v.env,onSessionExpired:()=>{t.onSessionExpired?.()}}),[t,u,T.apiEndpointAdmin,T.apiKeyEndpointAdmin,v]),f=me(S),x=oe(()=>{let n=ie({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:t?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,t?.enableLogging]),c=oe(()=>{if(!f.tokens?.accessToken||!f.isAuthenticated)return null;try{let n=de(f.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let g={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(A=>{["sub","email","subscriber"].includes(A)||(g[A]=n[A])}),g}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[f.tokens?.accessToken,f.isAuthenticated]),o={...f,sessionData:c,config:x},a={enabled:i,maxNotifications:s.maxNotifications||5,defaultAutoHideDuration:s.defaultAutoHideDuration||6e3,position:s.position||{vertical:"top",horizontal:"right"}};return N(ke.Provider,{value:o,children:r})}function $t(r){let t={enabled:r.showNotifications,maxNotifications:r.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:r.notificationOptions?.defaultAutoHideDuration||6e3,position:r.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:r.notificationOptions?.allowHtml||!1};return r.config?.publicApiKey?N(ye,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:N(ne,{...t,children:N(Ae,{...r})})}):N(ne,{...t,children:N(Ae,{...r})})}function We(){let r=qe(ke);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Xt(){let r=We();return r.isInitialized?K("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[N("h4",{children:"Session Debug Info"}),K("div",{children:[N("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),K("div",{children:[N("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),K("div",{children:[N("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&K(je,{children:[K("div",{children:[N("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),K("div",{children:[N("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),K("div",{children:[N("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),K("div",{children:[N("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),K("div",{children:[N("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):N("div",{children:"Session not initialized"})}import{useState as J,useEffect as be,useCallback as xe,useRef as Z}from"react";import Je from"@nocios/crudify-browser";var Jt=(r={})=>{let{autoFetch:t=!0,retryOnError:e=!1,maxRetries:i=3}=r,[s,u]=J(null),[T,v]=J(!1),[S,f]=J(null),[x,c]=J({}),o=Z(null),a=Z(!0),n=Z(0),g=Z(0),A=xe(()=>{u(null),f(null),v(!1),c({})},[]),R=xe(async()=>{let P=fe();if(!P){a.current&&(f("No user email available"),v(!1));return}o.current&&o.current.abort();let k=new AbortController;o.current=k;let I=++n.current;try{a.current&&(v(!0),f(null));let D=await Je.readItems("users",{filter:{email:P},pagination:{limit:1}});if(I===n.current&&a.current&&!k.signal.aborted)if(D.success&&D.data&&D.data.length>0){let m=D.data[0];u(m);let G={fullProfile:m,totalFields:Object.keys(m).length,displayData:{id:m.id,email:m.email,username:m.username,firstName:m.firstName,lastName:m.lastName,fullName:m.fullName||`${m.firstName||""} ${m.lastName||""}`.trim(),role:m.role,permissions:m.permissions||[],isActive:m.isActive,lastLogin:m.lastLogin,createdAt:m.createdAt,updatedAt:m.updatedAt,...Object.keys(m).filter(z=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(z)).reduce((z,_)=>({...z,[_]:m[_]}),{})}};c(G),f(null),g.current=0}else f("User profile not found"),u(null),c({})}catch(D){if(I===n.current&&a.current){let m=D;if(m.name==="AbortError")return;e&&g.current<i&&(m.message?.includes("Network Error")||m.message?.includes("Failed to fetch"))?(g.current++,setTimeout(()=>{a.current&&R()},1e3*g.current)):(f("Failed to load user profile"),u(null),c({}))}}finally{I===n.current&&a.current&&v(!1),o.current===k&&(o.current=null)}},[e,i]);return be(()=>{t&&R()},[t,R]),be(()=>(a.current=!0,()=>{a.current=!1,o.current&&(o.current.abort(),o.current=null)}),[]),{userProfile:s,loading:T,error:S,extendedData:x,refreshProfile:R,clearProfile:A}};import{useState as se,useEffect as Ze,useCallback as Q,useRef as Qe}from"react";import et from"@nocios/crudify-browser";var ti=(r,t={})=>{let{autoFetch:e=!0,onSuccess:i,onError:s}=t,{prefix:u,padding:T=0,separator:v=""}=r,[S,f]=se(""),[x,c]=se(!1),[o,a]=se(null),n=Qe(!1),g=Q(k=>{let I=String(k).padStart(T,"0");return`${u}${v}${I}`},[u,T,v]),A=Q(async()=>{c(!0),a(null);try{let k=await et.getNextSequence(u);if(k.success&&k.data?.value){let I=g(k.data.value);f(I),i?.(I)}else{let I=k.errors?._error?.[0]||"Failed to generate code";a(I),s?.(I)}}catch(k){let I=k instanceof Error?k.message:"Unknown error";a(I),s?.(I)}finally{c(!1)}},[u,g,i,s]),R=Q(async()=>{await A()},[A]),P=Q(()=>{a(null)},[]);return Ze(()=>{e&&!S&&!n.current&&(n.current=!0,A())},[e,S,A]),{value:S,loading:x,error:o,regenerate:R,clearError:P}};import{useState as tt,useCallback as O,useRef as it,useMemo as ee}from"react";import Se from"@nocios/crudify-browser";var Ie=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,oi=(r={})=>{let{acceptedTypes:t,maxFileSize:e=10*1024*1024,maxFiles:i,minFiles:s=0,onUploadComplete:u,onUploadError:T,onFileRemoved:v,onFilesChange:S}=r,[f,x]=tt([]),c=it(new Map),o=O((l,y)=>{x(p=>p.map(h=>h.id===l?{...h,...y}:h))},[]),a=O(l=>{S?.(l)},[S]),n=O(l=>t&&t.length>0&&!t.includes(l.type)?{valid:!1,error:`Tipo de archivo no permitido: ${l.type}`}:l.size>e?{valid:!1,error:`El archivo excede el tama\xF1o m\xE1ximo de ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[t,e]),g=O(async(l,y)=>{try{let p=await Se.generateSignedUrl({fileName:y.name,contentType:y.type});if(!p.success||!p.data)throw new Error("No se pudo obtener URL de upload");let w=p.data,h=new URL(w),b=decodeURIComponent(h.pathname.substring(1)),U=b.indexOf("/"),Ne=U>0?b.substring(U+1):b;o(l.id,{status:"uploading",progress:0}),await new Promise((Y,V)=>{let L=new XMLHttpRequest;L.upload.addEventListener("progress",te=>{if(te.lengthComputable){let Re=Math.round(te.loaded/te.total*100);o(l.id,{progress:Re})}}),L.addEventListener("load",()=>{L.status>=200&&L.status<300?Y():V(new Error(`Upload fall\xF3 con status ${L.status}`))}),L.addEventListener("error",()=>{V(new Error("Error de red durante el upload"))}),L.addEventListener("abort",()=>{V(new Error("Upload cancelado"))}),L.open("PUT",w),L.setRequestHeader("Content-Type",y.type),L.send(y)});let le={status:"completed",progress:100,filePath:Ne,file:void 0};o(l.id,le),x(Y=>{let V=Y.find(L=>L.id===l.id);return V&&u?.({...V,...le}),Y})}catch(p){let w=p instanceof Error?p.message:"Error desconocido";o(l.id,{status:"error",progress:0,errorMessage:w}),x(h=>{let b=h.find(U=>U.id===l.id);return b&&T?.(b,w),h})}},[o,u,T]),A=O(async l=>{let y=Array.from(l);if(i!==void 0){let h=f.filter(U=>U.status!=="error").length,b=i-h;if(b<=0){console.warn(`Ya se alcanz\xF3 el l\xEDmite de ${i} archivos`);return}y.length>b&&(y.splice(b),console.warn(`Solo se agregar\xE1n ${b} archivos para no exceder el l\xEDmite`))}let p=[];for(let h of y){let b=n(h),U={id:Ie(),name:h.name,size:h.size,contentType:h.type,status:b.valid?"pending":"error",progress:0,createdAt:Date.now(),file:b.valid?h:void 0,errorMessage:b.error};p.push(U)}x(h=>{let b=[...h,...p];return a(b),b});let w=p.filter(h=>h.status==="pending"&&h.file);for(let h of w)if(h.file){let b=g(h,h.file);c.current.set(h.id,b),b.finally(()=>{c.current.delete(h.id)})}},[f,i,n,g,a]),R=O(async l=>{let y=f.find(p=>p.id===l);if(!y)return!1;o(l,{status:"removing"});try{if(y.filePath&&!(await Se.disableFile({filePath:y.filePath})).success)throw new Error("No se pudo eliminar el archivo del servidor");return x(p=>{let w=p.filter(h=>h.id!==l);return a(w),w}),v?.(y),!0}catch(p){return o(l,{status:y.filePath?"completed":"error",errorMessage:p instanceof Error?p.message:"Error al eliminar"}),!1}},[f,o,a,v]),P=O(()=>{x([]),a([])},[a]),k=O(async l=>{let y=f.find(w=>w.id===l);if(!y||y.status!=="error"||!y.file){console.warn("No se puede reintentar: archivo no encontrado o sin archivo original");return}o(l,{status:"pending",progress:0,errorMessage:void 0});let p=g(y,y.file);c.current.set(l,p),p.finally(()=>{c.current.delete(l)})},[f,o,g]),I=O(async()=>{let l=Array.from(c.current.values());l.length>0&&await Promise.allSettled(l)},[]),D=O(l=>{let y=l.map(p=>({id:Ie(),name:p.name,size:p.size||0,contentType:p.contentType||"application/octet-stream",status:"completed",progress:100,filePath:p.filePath,createdAt:Date.now()}));x(y),a(y)},[a]),m=ee(()=>f.some(l=>l.status==="uploading"||l.status==="pending"),[f]),G=ee(()=>f.filter(l=>l.status==="uploading"||l.status==="pending").length,[f]),z=ee(()=>f.filter(l=>l.status==="completed"&&l.filePath).map(l=>l.filePath),[f]),{isValid:_,validationError:ae}=ee(()=>{let l=f.filter(p=>p.status==="completed").length;return l<s?{isValid:!1,validationError:s===1?"Se requiere al menos un archivo":`Se requieren al menos ${s} archivos`}:i!==void 0&&l>i?{isValid:!1,validationError:`M\xE1ximo ${i} archivos permitidos`}:f.some(p=>p.status==="error")?{isValid:!1,validationError:"Algunos archivos tienen errores"}:{isValid:!0,validationError:null}},[f,s,i]);return{files:f,isUploading:m,pendingCount:G,addFiles:A,removeFile:R,clearFiles:P,retryUpload:k,isValid:_,validationError:ae,waitForUploads:I,completedFilePaths:z,initializeFiles:D}};export{ge as a,ye as b,he as c,E as d,q as e,me as f,ne as g,ve as h,$t as i,We as j,Xt as k,Jt as l,ti as m,oi as n};
@@ -1 +1 @@
1
- import{h as $,j as D}from"./chunk-TZKAMU3P.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=D(),[E,d]=K(null),[y,A]=K(a&&T),[_,p]=K(null),u=v(null),o=v(!0),m=v(0),l=v(0),x=j(()=>c&&(c.email||c["cognito:username"])||null,[c]),P=j(()=>{d(null),p(null),A(!1),l.current=0},[]),w=j(async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await Q.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return z(()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!a&&!N,[S,a,N]),c=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),_=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:a}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=C(e=>["create","update","delete"].includes(e),[]),_=C((e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(s?.response?.errorCode){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(s?.response?.data)return s.response.data}if(n?.response?.message){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"create",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r),n=r?.skipNotifications===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=r?.actionConfig,f=s?.key||"update",O=s?.moduleKey||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"delete",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(i?.actionConfig?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
1
+ import{h as $,j as D}from"./chunk-4E2PRDUC.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-browser";var G=(S={})=>{let{autoFetch:a=!0,retryOnError:N=!1,maxRetries:g=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:c,tokens:R}=D(),[E,d]=K(null),[y,A]=K(a&&T),[_,p]=K(null),u=v(null),o=v(!0),m=v(0),l=v(0),x=j(()=>c&&(c.email||c["cognito:username"])||null,[c]),P=j(()=>{d(null),p(null),A(!1),l.current=0},[]),w=j(async()=>{let F=x();if(!F){o.current&&(p("No user email available from session data"),A(!1));return}if(!I){o.current&&(p("Session not initialized"),A(!1));return}u.current&&u.current.abort();let e=new AbortController;u.current=e;let i=++m.current;try{o.current&&(A(!0),p(null));let r=await Q.readItems("users",{filter:{email:F},pagination:{limit:1}});if(i===m.current&&o.current&&!e.signal.aborted){let t=null;if(r.success){if(Array.isArray(r.data)&&r.data.length>0)t=r.data[0];else if(r.data?.response?.data)try{let n=r.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}else if(r.data&&typeof r.data=="object")r.data.items&&Array.isArray(r.data.items)&&r.data.items.length>0&&(t=r.data.items[0]);else if(r.data?.data?.response?.data)try{let n=r.data.data.response.data,s=typeof n=="string"?JSON.parse(n):n;s&&s.items&&Array.isArray(s.items)&&s.items.length>0&&(t=s.items[0])}catch{}}t?(d(t),p(null),l.current=0):(p("User profile not found in database"),d(null))}}catch(r){if(i===m.current&&o.current){let t=r;if(t.name==="AbortError")return;N&&l.current<g&&(t.message?.includes("Network Error")||t.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{o.current&&w()},1e3*l.current)):(p("Failed to load user profile from database"),d(null))}}finally{i===m.current&&o.current&&A(!1),u.current===e&&(u.current=null)}},[I,x,N,g]);return z(()=>{a&&T&&I?w():T||P()},[a,T,I,w,P]),z(()=>(o.current=!0,()=>{o.current=!1,u.current&&(u.current.abort(),u.current=null)}),[]),{user:{session:c,data:E},loading:y,error:_,refreshProfile:w,clearProfile:P}};import{useCallback as W}from"react";var ee=()=>{let{isAuthenticated:S,isLoading:a,isInitialized:N,tokens:g,error:T,sessionData:I,login:c,logout:R,refreshTokens:E,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p}=D(),u=W(m=>{m?console.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):R()},[R]),o=g?.expiresAt?new Date(g.expiresAt):null;return{isAuthenticated:S,loading:a,error:T,token:g?.accessToken||null,user:I,tokenExpiration:o,setToken:u,logout:R,refreshToken:E,login:c,isExpiringSoon:A,expiresIn:_,refreshExpiresIn:p,getTokenInfo:y,clearError:d}};import{useCallback as h}from"react";import U from"@nocios/crudify-browser";var oe=()=>{let{isInitialized:S,isLoading:a,error:N,isAuthenticated:g,login:T}=D(),I=h(()=>S&&!a&&!N,[S,a,N]),c=h(async()=>new Promise((o,m)=>{let l=()=>{I()?o():N?m(new Error(N)):setTimeout(l,100)};l()}),[I,N]),R=h(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),E=h(async(o,m,l)=>(await R(),await U.readItems(o,m||{},l)),[R]),d=h(async(o,m,l)=>(await R(),await U.readItem(o,m,l)),[R]),y=h(async(o,m,l)=>(await R(),await U.createItem(o,m,l)),[R]),A=h(async(o,m,l)=>(await R(),await U.updateItem(o,m,l)),[R]),_=h(async(o,m,l)=>(await R(),await U.deleteItem(o,m,l)),[R]),p=h(async(o,m)=>(await R(),await U.transaction(o,m)),[R]),u=h(async(o,m)=>{try{let l=await T(o,m);return l.success?{success:!0,data:l.tokens}:{success:!1,errors:l.error||"Login failed"}}catch(l){return{success:!1,errors:l instanceof Error?l.message:"Login failed"}}},[T]);return{readItems:E,readItem:d,createItem:y,updateItem:A,deleteItem:_,transaction:p,login:u,isInitialized:S,isInitializing:a,initializationError:N,isReady:I,waitForReady:c}};import{useCallback as C}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},le=(S={})=>{let{showNotification:a}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:g=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:c=6e3,appStructure:R=[],translateFn:E=e=>e}=S,d=C(e=>!(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS"))||!e.success&&e.data?.response?.status==="TOO_MANY_REQUESTS"),[]),y=C((e,i)=>{let r=E(e);return r===e?i||E("error.unknown"):r},[E]),A=C(e=>["create","update","delete"].includes(e),[]),_=C((e,i)=>N?A(e)&&i?!0:R.some(r=>r.key===e):!1,[N,R,A]),p=C((e,i,r)=>{let t=r?.key&&typeof r.key=="string"?r.key:e,n=`action.onSuccess.${t}`,s=y(n);if(s!==E("error.unknown")){if(A(t)&&i){let f=`action.${i}Singular`,O=y(f);if(O!==E("error.unknown"))return E(n,{item:O});{let k=`action.onSuccess.${t}WithoutItem`,L=y(k);return L!==E("error.unknown")?L:s}}return s}return E("success.transaction")},[y,E,A]),u=C(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let r of i){let t=y(r);if(t!==E("error.unknown"))return t}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==E("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let r=e.errors._transaction;if(r?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(r)&&r.length>0){let t=r[0];if(typeof t=="string"&&t!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let n=JSON.parse(t);if(Array.isArray(n)&&n.length>0){let s=n[0];if(s?.response?.errorCode){let f=s.response.errorCode;if(M[f])return y(M[f]);let O=[`errors.auth.${f}`,`errors.data.${f}`,`errors.system.${f}`,`errors.${f}`];for(let k of O){let L=y(k);if(L!==y("error.unknown"))return L}}if(s?.response?.data)return s.response.data}if(n?.response?.message){let s=n.response.message.toLowerCase();return s.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):s.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):n.response.message}}catch{return t.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):t.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let r=e.errors._error;return Array.isArray(r)?r[0]:String(r)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||E("error.unknown")},[T,I,E,y]),o=C(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),m=C(async(e,i,r)=>{let t=await b.createItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"create",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),l=C(async(e,i,r)=>{let t=await b.updateItem(e,i,r),n=r?.skipNotifications===!0;if(!n&&!t.success&&g&&d(t)){let s=u(t),f=o(t);a(s,f,{autoHideDuration:c})}else if(!n&&t.success){let s=r?.actionConfig,f=s?.key||"update",O=s?.moduleKey||e;if(_(f,O)){let k=p(f,O,s);a(k,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),x=C(async(e,i,r)=>{let t=await b.deleteItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}else if(t.success){let n=r?.actionConfig,s=n?.key||"delete",f=n?.moduleKey||e;if(_(s,f)){let O=p(s,f,n);a(O,"success",{autoHideDuration:c})}}return t},[g,_,a,u,o,p,c,d]),P=C(async(e,i,r)=>{let t=await b.readItem(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),w=C(async(e,i,r)=>{let t=await b.readItems(e,i,r);if(!t.success&&g&&d(t)){let n=u(t),s=o(t);a(n,s,{autoHideDuration:c})}return t},[g,a,u,o,c,d]),V=C(async(e,i)=>{let r=await b.transaction(e,i),t=i?.skipNotifications===!0;if(!t&&!r.success&&g&&d(r)){let n=u(r),s=o(r);a(n,s,{autoHideDuration:c})}else if(!t&&r.success){let n="transaction",s,f=null;if(i?.actionConfig?(f=i.actionConfig,n=f.key,s=f.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(n=e[0].operation,f=R.find(O=>O.key===n),f&&(s=f.moduleKey)),_(n,s)){let O=p(n,s,f);a(O,"success",{autoHideDuration:c})}}return r},[g,_,a,u,o,p,c,d,R]),F=C((e,i)=>{if(!e.success&&g&&d(e)){let r=u(e),t=o(e);a(r,t,{autoHideDuration:c})}else e.success&&N&&i&&a(i,"success",{autoHideDuration:c});return e},[g,N,a,u,o,c,d,E]);return{createItem:m,updateItem:l,deleteItem:x,readItem:P,readItems:w,transaction:V,handleResponse:F,getErrorMessage:u,getErrorSeverity:o,shouldShowNotification:d}};export{G as a,ee as b,oe as c,le as d};
@@ -0,0 +1 @@
1
+ import{b as ho,c as oe,h as wo,j as ie,l as Co,m as Po,n as xo}from"./chunk-4E2PRDUC.mjs";import{g as j}from"./chunk-BJ6PIVZR.mjs";import{a as po,b as yo,g as bo}from"./chunk-6GPSBDW6.mjs";var ne={es:{"checkCode.codeLabel":"C\xF3digo de Verificaci\xF3n","checkCode.codePlaceholder":"Ingresa el c\xF3digo de 6 d\xEDgitos","checkCode.codeRequired":"El c\xF3digo es obligatorio","checkCode.emailLabel":"Correo Electr\xF3nico","checkCode.emailPlaceholder":"Ingresa tu correo electr\xF3nico","checkCode.emailRequired":"El correo electr\xF3nico es obligatorio","checkCode.instructions":"Ingresa el c\xF3digo de 6 d\xEDgitos que enviamos a tu correo electr\xF3nico.","checkCode.invalidEmail":"Ingresa un correo electr\xF3nico v\xE1lido","checkCode.resendCodeLink":"Reenviar c\xF3digo","checkCode.title":"Verificar C\xF3digo","checkCode.verifyButton":"Verificar C\xF3digo","common.back":"Volver","common.backToLogin":"Volver","error.app.config":"Error de Configuraci\xF3n: {{message}}","error.app.initialization":"Error durante la inicializaci\xF3n final de la aplicaci\xF3n.","error.transaction":"Error en la operaci\xF3n","error.unknown":"Ocurri\xF3 un error desconocido.","errors.DUPLICATE":"El campo <b>{{field}}</b> debe ser \xFAnico.","errors.FOREIGN_KEY_NOT_FOUND":"El campo <b>{{field}}</b> debe referenciar un \xEDtem existente.","errors.INVALID_EMAIL":"El campo <b>{{field}}</b> debe ser un correo electr\xF3nico v\xE1lido.","errors.INVALID_OBJECT_ID":"El campo <b>{{field}}</b> debe ser un valor v\xE1lido.","errors.IN_USE":"El \xEDtem est\xE1 en uso y no puede ser eliminado.","errors.MAX_LENGTH":"El campo <b>{{field}}</b> no debe exceder los <b>{{length}}</b> caracteres.","errors.MIN_LENGTH":"El campo <b>{{field}}</b> debe tener al menos <b>{{length}}</b> caracteres.","errors.MUST_NOT_BE_EMAIL":"El campo <b>{{field}}</b> no debe ser un correo electr\xF3nico.","errors.NO_PERMISSION":"No tienes permiso para realizar esta acci\xF3n.","errors.NO_SPACES":"El campo <b>{{field}}</b> no debe contener espacios.","errors.ONE_OR_MORE_OPERATIONS_FAILED":"Error en la operaci\xF3n","errors.REQUIRED":"El campo <b>{{field}}</b> es obligatorio.","errors.TOKEN_HAS_EXPIRED":"La sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.","errors.TOO_MANY_REQUESTS":"L\xEDmite de solicitudes alcanzado. Por favor intenta m\xE1s tarde.","errors.UNAUTHORIZED":"No est\xE1s autorizado para realizar esta acci\xF3n.","errors.all_password_fields_required":"Todos los campos de contrase\xF1a son obligatorios","errors.auth.INVALID_API_KEY":"Clave de API inv\xE1lida","errors.auth.INVALID_CREDENTIALS":"Usuario y/o contrase\xF1a incorrectos","errors.auth.NO_PERMISSION":"No tienes permisos suficientes","errors.auth.SESSION_EXPIRED":"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.","errors.auth.TOO_MANY_REQUESTS":"Demasiados intentos. Por favor espera 15 minutos e intenta nuevamente","errors.auth.UNAUTHORIZED":"No tienes permisos para realizar esta acci\xF3n","errors.auth.USER_NOT_ACTIVE":"Usuario no activo","errors.auth.USER_NOT_FOUND":"Usuario no encontrado","errors.data.BAD_REQUEST":"Solicitud inv\xE1lida","errors.data.FIELD_ERROR":"Error en los datos ingresados","errors.data.IN_USE":"El elemento est\xE1 en uso y no puede ser eliminado","errors.data.ITEM_NOT_FOUND":"El elemento solicitado no fue encontrado","errors.data.NOT_FOUND":"No se encontr\xF3 lo solicitado","errors.internal_error_changing_password":"Error interno al cambiar la contrase\xF1a. Intenta nuevamente","errors.password_min_length":"La contrase\xF1a debe tener al menos 8 caracteres","errors.password_mismatch":"Las contrase\xF1as no coinciden","errors.password_must_be_different":"La nueva contrase\xF1a debe ser diferente a la actual","errors.system.DATABASE_CONNECTION_ERROR":"Error de conexi\xF3n. Verifica tu conexi\xF3n a internet.","errors.system.INTERNAL_SERVER_ERROR":"Error interno del servidor. Intenta nuevamente.","errors.system.INVALID_CONFIGURATION":"Error de configuraci\xF3n del sistema","errors.system.TOO_MANY_REQUESTS":"Demasiadas solicitudes. Por favor espera un momento e intenta nuevamente","errors.system.UNKNOWN_OPERATION":"Operaci\xF3n no reconocida","errors.users_module_not_configured":"M\xF3dulo de usuarios no configurado","footer.copyright":"Nocios S.R.L. Todos los derechos reservados.","footer.version":"Versi\xF3n","forgotPassword.checkEmailInstructions":"Revisa tu bandeja de entrada para el c\xF3digo de verificaci\xF3n","forgotPassword.codeAlreadyExistsMessage":"Ya se envi\xF3 un c\xF3digo y a\xFAn es v\xE1lido","forgotPassword.emailLabel":"Correo Electr\xF3nico","forgotPassword.emailPlaceholder":"Ingresa tu correo electr\xF3nico","forgotPassword.emailRequired":"El correo electr\xF3nico es obligatorio","forgotPassword.emailSentMessage":"C\xF3digo enviado exitosamente","forgotPassword.enterCodeLink":"Ingresar C\xF3digo","forgotPassword.instructions":"Ingresa tu correo electr\xF3nico y te enviaremos un c\xF3digo para restablecer tu contrase\xF1a.","forgotPassword.invalidEmail":"Ingresa un correo electr\xF3nico v\xE1lido","forgotPassword.sendCodeButton":"Enviar C\xF3digo","forgotPassword.title":"Recuperar Contrase\xF1a","loading.app.configInitial":"Cargando configuraci\xF3n inicial...","loading.app.generic":"Cargando...","loading.app.starting":"Iniciando aplicaci\xF3n...","loading.app.themeSetup":"Generando tema...","loading.app.validatingSession":"Validando sesi\xF3n...","login.alreadyHaveCodeLink":"\xBFYa tienes un c\xF3digo?","login.forgotPasswordLink":"\xBFOlvidaste tu contrase\xF1a?","login.initializationError":"Error de inicializaci\xF3n","login.initializing":"Inicializando...","login.loginButton":"Iniciar Sesi\xF3n","login.logoAlt":"Logotipo","login.noAccountPrompt":"\xBFNo tienes una cuenta?","login.notInitialized":"Sistema no inicializado","login.passwordLabel":"Contrase\xF1a","login.passwordPlaceholder":"Ingresa tu contrase\xF1a","login.passwordRequired":"Contrase\xF1a es obligatoria","login.signUpLink":"Reg\xEDstrate","login.usernameOrEmailLabel":"Correo Electr\xF3nico","login.usernameOrEmailPlaceholder":"Ingresa tu correo electr\xF3nico","login.usernameRequired":"Correo electr\xF3nico es obligatorio","resetPassword.codeExpiredOrInvalid":"El c\xF3digo ha expirado o es inv\xE1lido","resetPassword.confirmPasswordLabel":"Confirmar Contrase\xF1a","resetPassword.confirmPasswordPlaceholder":"Confirma tu nueva contrase\xF1a","resetPassword.confirmPasswordRequired":"Confirma tu contrase\xF1a","resetPassword.goToLoginButton":"Ir al Login","resetPassword.instructions":"Ingresa tu nueva contrase\xF1a.","resetPassword.invalidCode":"El c\xF3digo de verificaci\xF3n es inv\xE1lido. Por favor, verifica el enlace o solicita uno nuevo.","resetPassword.missingParameters":"Faltan par\xE1metros obligatorios","resetPassword.newPasswordLabel":"Nueva Contrase\xF1a","resetPassword.newPasswordPlaceholder":"Ingresa tu nueva contrase\xF1a","resetPassword.newPasswordRequired":"La nueva contrase\xF1a es obligatoria","resetPassword.passwordTooShort":"La contrase\xF1a debe tener al menos 8 caracteres","resetPassword.passwordsDoNotMatch":"Las contrase\xF1as no coinciden","resetPassword.requestNewCodeButton":"Solicitar Nuevo C\xF3digo","resetPassword.resetPasswordButton":"Restablecer Contrase\xF1a","resetPassword.successInstructions":"Ahora puedes iniciar sesi\xF3n con tu nueva contrase\xF1a","resetPassword.successMessage":"Contrase\xF1a restablecida exitosamente","resetPassword.title":"Nueva Contrase\xF1a","resetPassword.validatingCode":"Validando c\xF3digo...","modules.form.publicPolicies.fields.conditions.customEdit":"Edici\xF3n personalizada"},en:{"checkCode.codeLabel":"Verification Code","checkCode.codePlaceholder":"Enter 6-digit code","checkCode.codeRequired":"Code is required","checkCode.emailLabel":"Email Address","checkCode.emailPlaceholder":"Enter your email address","checkCode.emailRequired":"Email address is required","checkCode.instructions":"Enter the 6-digit code we sent to your email address.","checkCode.invalidEmail":"Enter a valid email address","checkCode.resendCodeLink":"Resend code","checkCode.title":"Verify Code","checkCode.verifyButton":"Verify Code","common.back":"Back","common.backToLogin":"Back to Login","error.app.config":"Configuration Error: {{message}}","error.app.initialization":"Error during final application initialization.","error.transaction":"Operation error","error.unknown":"An unknown error occurred.","errors.DUPLICATE":"The field <b>{{field}}</b> must be unique.","errors.FOREIGN_KEY_NOT_FOUND":"The field <b>{{field}}</b> must reference an existing item.","errors.INVALID_EMAIL":"The field <b>{{field}}</b> must be a valid email address.","errors.INVALID_OBJECT_ID":"The field <b>{{field}}</b> must be a valid value.","errors.IN_USE":"The item is currently in use and cannot be deleted.","errors.MAX_LENGTH":"The field <b>{{field}}</b> must not exceed <b>{{maxLength}}</b> characters.","errors.MIN_LENGTH":"The field <b>{{field}}</b> must have at least <b>{{minLength}}</b> characters.","errors.MUST_NOT_BE_EMAIL":"The field <b>{{field}}</b> must not be an email address.","errors.NO_PERMISSION":"You do not have permission to perform this action.","errors.NO_SPACES":"The field <b>{{field}}</b> must not contain spaces.","errors.ONE_OR_MORE_OPERATIONS_FAILED":"Operation error","errors.REQUIRED":"The field <b>{{field}}</b> is required.","errors.TOKEN_HAS_EXPIRED":"Your session has expired, please log in again.","errors.TOO_MANY_REQUESTS":"Request limit reached. Please try again later.","errors.UNAUTHORIZED":"You are not authorized to perform this action.","errors.all_password_fields_required":"All password fields are required","errors.auth.INVALID_API_KEY":"Invalid API key","errors.auth.INVALID_CREDENTIALS":"Incorrect username and/or password","errors.auth.NO_PERMISSION":"Insufficient permissions","errors.auth.SESSION_EXPIRED":"Your session has expired. Please log in again.","errors.auth.TOO_MANY_REQUESTS":"Too many attempts. Please wait 15 minutes and try again","errors.auth.UNAUTHORIZED":"You don't have permission to perform this action","errors.auth.USER_NOT_ACTIVE":"User account is not active","errors.auth.USER_NOT_FOUND":"User not found","errors.data.BAD_REQUEST":"Invalid request","errors.data.FIELD_ERROR":"Error in the provided data","errors.data.IN_USE":"The item is in use and cannot be deleted","errors.data.ITEM_NOT_FOUND":"The requested item was not found","errors.data.NOT_FOUND":"The requested resource was not found","errors.internal_error_changing_password":"Internal error changing password. Please try again","errors.password_min_length":"Password must be at least 8 characters","errors.password_mismatch":"Passwords do not match","errors.password_must_be_different":"New password must be different from current password","errors.system.DATABASE_CONNECTION_ERROR":"Connection error. Please check your internet connection.","errors.system.INTERNAL_SERVER_ERROR":"Internal server error. Please try again.","errors.system.INVALID_CONFIGURATION":"System configuration error","errors.system.TOO_MANY_REQUESTS":"Too many requests. Please wait a moment and try again","errors.system.UNKNOWN_OPERATION":"Unrecognized operation","errors.users_module_not_configured":"Users module not configured","footer.copyright":"Nocios S.R.L. All Rights Reserved.","footer.version":"Version","forgotPassword.checkEmailInstructions":"Check your inbox for the verification code","forgotPassword.codeAlreadyExistsMessage":"A code was already sent and is still valid","forgotPassword.emailLabel":"Email Address","forgotPassword.emailPlaceholder":"Enter your email address","forgotPassword.emailRequired":"Email address is required","forgotPassword.emailSentMessage":"Code sent successfully","forgotPassword.enterCodeLink":"Enter Code","forgotPassword.instructions":"Enter your email address and we'll send you a code to reset your password.","forgotPassword.invalidEmail":"Enter a valid email address","forgotPassword.sendCodeButton":"Send Code","forgotPassword.title":"Reset Password","loading.app.configInitial":"Loading initial configuration...","loading.app.generic":"Loading...","loading.app.starting":"Starting application...","loading.app.themeSetup":"Generating theme...","loading.app.validatingSession":"Validating session...","login.alreadyHaveCodeLink":"Already have a code?","login.forgotPasswordLink":"Forgot Password?","login.initializationError":"Initialization error","login.initializing":"Initializing...","login.loginButton":"Log In","login.logoAlt":"Logo","login.noAccountPrompt":"Don't have an account?","login.notInitialized":"System not initialized","login.passwordLabel":"Password","login.passwordPlaceholder":"Enter your password","login.passwordRequired":"Password is required","login.signUpLink":"Sign up","login.usernameOrEmailLabel":"Username or Email","login.usernameOrEmailPlaceholder":"Enter your username or email","login.usernameRequired":"Username or email is required","resetPassword.codeExpiredOrInvalid":"Code expired or invalid","resetPassword.confirmPasswordLabel":"Confirm Password","resetPassword.confirmPasswordPlaceholder":"Confirm your new password","resetPassword.confirmPasswordRequired":"Confirm your password","resetPassword.goToLoginButton":"Go to Login","resetPassword.instructions":"Enter your new password.","resetPassword.invalidCode":"The verification code is invalid. Please check the link or request a new one.","resetPassword.missingParameters":"Missing required parameters","resetPassword.newPasswordLabel":"New Password","resetPassword.newPasswordPlaceholder":"Enter your new password","resetPassword.newPasswordRequired":"New password is required","resetPassword.passwordTooShort":"Password must be at least 8 characters","resetPassword.passwordsDoNotMatch":"Passwords do not match","resetPassword.requestNewCodeButton":"Request New Code","resetPassword.resetPasswordButton":"Reset Password","resetPassword.successInstructions":"You can now log in with your new password","resetPassword.successMessage":"Password reset successfully","resetPassword.title":"New Password","resetPassword.validatingCode":"Validating code...","modules.form.publicPolicies.fields.conditions.customEdit":"Custom Edit"}},Un=()=>Object.keys(ne),zn=e=>ne[e]||ne.es;import Be from"@nocios/crudify-browser";var vo="crudify_translations_",br=3600*1e3;function To(e){let o=0;for(let r=0;r<e.length;r++){let t=e.charCodeAt(r);o=(o<<5)-o+t,o=o&o}return Math.abs(o).toString(36)}var Ye=class e{constructor(){this.enableDebug=!1;this.initializationPromise=null;this.isInitialized=!1}static getInstance(){return e.instance||(e.instance=new e),e.instance}setDebug(o){this.enableDebug=o}async ensureCrudifyInitialized(o,r){if(!this.isInitialized)return this.initializationPromise?(this.enableDebug&&console.log("[TranslationService] Waiting for crudify initialization..."),this.initializationPromise):(this.enableDebug&&console.log("[TranslationService] Initializing crudify SDK..."),this.initializationPromise=(async()=>{try{let t=Be.getTokenData();if(t&&t.endpoint){this.enableDebug&&console.log("[TranslationService] Crudify already initialized"),this.isInitialized=!0;return}Be.config(r);let a=await Be.init(o,this.enableDebug?"debug":"none");if(a.success===!1)throw new Error(`Failed to initialize crudify: ${JSON.stringify(a.errors||"Unknown error")}`);this.isInitialized=!0,this.enableDebug&&console.log("[TranslationService] Crudify SDK initialized successfully")}catch(t){throw console.error("[TranslationService] Failed to initialize crudify:",t),this.initializationPromise=null,t}})(),this.initializationPromise)}async fetchTranslations(o){let{apiKey:r,featureKeys:t,crudifyEnv:a="stg",urlTranslations:n}=o;this.enableDebug&&console.log("[TranslationService] fetchTranslations called with:",{apiKeyHash:To(r),crudifyEnv:a,featureKeys:t,hasUrlTranslations:!!n});let s=this.getFromCache(r),i=s?this.isCacheExpired(s):!0;if(s&&!i)return this.enableDebug&&console.log("[TranslationService] Using cached translations"),this.mergeWithUrlTranslations(s.data.translations,n);try{await this.ensureCrudifyInitialized(r,a)}catch(d){return console.error("[TranslationService] \u274C Failed to initialize crudify:",d),s?(console.warn("[TranslationService] \u26A0\uFE0F Using expired cache (init failed)"),this.mergeWithUrlTranslations(s.data.translations,n)):(console.warn("[TranslationService] \u26A0\uFE0F Using critical bundle (init failed)"),this.getCriticalTranslationsOnly())}try{this.enableDebug&&console.log("[TranslationService] Fetching from API via crudify SDK");let d=await this.fetchFromAPI(t);this.hasDataChanged(s,d)||!s?this.saveToCache(r,d):this.refreshCacheTimestamp(r);let m=this.mergeWithUrlTranslations(d.translations,n);return this.enableDebug&&console.log("[TranslationService] Translations loaded:",{languages:Object.keys(m),keysCount:m[Object.keys(m)[0]]?Object.keys(m[Object.keys(m)[0]]).length:0}),m}catch(d){return console.error("[TranslationService] \u274C API fetch failed:",d),s?(console.warn("[TranslationService] \u26A0\uFE0F Using expired cache as fallback"),this.mergeWithUrlTranslations(s.data.translations,n)):(console.warn("[TranslationService] \u26A0\uFE0F Using critical bundle translations"),this.getCriticalTranslationsOnly())}}async fetchFromAPI(o){let r=await Be.getTranslation(o);if(!r.success)throw new Error(`Crudify API error: ${r.errors?JSON.stringify(r.errors):"Unknown error"}`);if(!r.data)throw new Error("No translation data in response");return r.data}mergeWithUrlTranslations(o,r){if(!r||Object.keys(r).length===0)return o;let t={};return Object.keys(o).forEach(a=>{t[a]={...o[a],...r}}),t}hasDataChanged(o,r){if(!o||o.data.timestamp!==r.timestamp)return!0;let t=this.hashData(r.translations);return o.dataHash!==t}hashData(o){let r=JSON.stringify(o),t=0;for(let a=0;a<r.length;a++){let n=r.charCodeAt(a);t=(t<<5)-t+n,t=t&t}return t.toString(36)}saveToCache(o,r){try{let t=this.getCacheKey(o),a={data:r,cachedAt:Date.now(),dataHash:this.hashData(r.translations)};localStorage.setItem(t,JSON.stringify(a)),this.enableDebug&&console.log("[TranslationService] Saved to cache:",t)}catch(t){console.error("[TranslationService] Failed to save cache:",t)}}getFromCache(o){try{let r=this.getCacheKey(o),t=localStorage.getItem(r);return t?JSON.parse(t):null}catch(r){return console.error("[TranslationService] Failed to read cache:",r),null}}refreshCacheTimestamp(o){try{let r=this.getFromCache(o);if(r){r.cachedAt=Date.now();let t=this.getCacheKey(o);localStorage.setItem(t,JSON.stringify(r))}}catch(r){console.error("[TranslationService] Failed to refresh cache timestamp:",r)}}isCacheExpired(o){return Date.now()-o.cachedAt>br}hasValidCache(o){let r=this.getFromCache(o);return r?!this.isCacheExpired(r):!1}getCacheKey(o){return`${vo}${To(o)}`}getCriticalTranslationsOnly(){return ne}invalidateCache(o){let r=this.getCacheKey(o);localStorage.removeItem(r),this.enableDebug&&console.log("[TranslationService] Cache invalidated:",r)}async prefetchTranslations(o){try{await this.fetchTranslations(o),this.enableDebug&&console.log("[TranslationService] Prefetch completed")}catch(r){console.error("[TranslationService] Prefetch failed:",r)}}clearAllCaches(){try{let r=Object.keys(localStorage).filter(t=>t.startsWith(vo));r.forEach(t=>localStorage.removeItem(t)),this.enableDebug&&console.log(`[TranslationService] Cleared ${r.length} cache entries`)}catch(o){console.error("[TranslationService] Failed to clear caches:",o)}}},De=Ye.getInstance();import{createContext as wr,useContext as Cr,useEffect as Io,useState as we,useMemo as Eo,useCallback as Pr}from"react";import{Fragment as vr,jsx as ze}from"react/jsx-runtime";var Ue=null,Je=!1,So=wr(null);function Ro(e,o,r){return{...e,...o,...r||{}}}function xr(e,o,r,t,a){Io(()=>{if(!t||!e||!o)return;let n=r||typeof window<"u"&&window.i18next||typeof window<"u"&&window.i18n;if(!n||!n.addResourceBundle){a&&console.log("[TranslationsProvider] i18next not found, skipping auto-sync");return}a&&console.log("[TranslationsProvider] Auto-syncing translations with i18next",{languages:Object.keys(e),currentLanguage:o}),Object.keys(e).forEach(s=>{e[s]&&Object.keys(e[s]).length>0&&(n.addResourceBundle(s,"translation",e[s],!0,!0),a&&console.log(`[TranslationsProvider] Synced ${Object.keys(e[s]).length} keys for language: ${s}`))}),n.language!==o&&(n.changeLanguage(o),a&&console.log(`[TranslationsProvider] Changed i18next language to: ${o}`))},[e,o,r,t,a])}var Yn=({children:e,apiKey:o,crudifyEnv:r="prod",featureKeys:t,language:a="es",devTranslations:n,translationUrl:s,enableDebug:i=!1,skipAutoInit:d=!0,autoSyncI18n:w=!0,i18nInstance:m,loadingFallback:b,waitForInitialLoad:p=!0})=>{let l=Eo(()=>yo({publicApiKey:o,env:r,featureKeys:t,enableDebug:i}),[o,r,t,i]),c=l.publicApiKey||"",h=l.env||r||"prod",u=l.featureKeys||t,[y,f]=we({}),[v,I]=we(!0),[W,C]=we(!0),[g,T]=we(null),[A,F]=we(void 0),[Q,fe]=we(!1),ae=Pr(async()=>{if(!c){i&&console.log("[TranslationsProvider] No apiKey - skipping translation fetch"),I(!1),C(!1);return}if(Q){i&&console.log("[TranslationsProvider] Skipping reload - using fallback translations");return}if(De.hasValidCache(c)&&W&&(i&&console.log("[TranslationsProvider] Valid cache found - not blocking initial render"),C(!1)),Je&&Ue){i&&console.log("[TranslationsProvider] Fetch already in progress, waiting for existing promise");try{let R=await Ue;f(R),I(!1);return}catch{i&&console.warn("[TranslationsProvider] Global fetch failed, retrying")}}Je=!0,I(!0),T(null);let z;if(s)try{i&&console.log(`[TranslationsProvider] Fetching translations from URL: ${s}`);let R=await fetch(s);if(!R.ok)throw new Error(`Failed to fetch translations: ${R.statusText}`);z=await R.json(),F(z),i&&console.log("[TranslationsProvider] URL translations loaded:",{keysCount:z?Object.keys(z).length:0})}catch(R){console.error("[TranslationsProvider] Failed to load URL translations:",R),z=void 0,F(void 0)}let pe=(async()=>{try{De.setDebug(i);let R=await De.fetchTranslations({apiKey:c,crudifyEnv:h,featureKeys:u,urlTranslations:z}),M={};return Object.keys(R).forEach(x=>{let L=ne[x]||{},P=R[x]||{};M[x]=Ro(L,P,n)}),i&&console.log("[TranslationsProvider] Loaded translations:",{languages:Object.keys(M),keysCount:Object.keys(M[a]||{}).length}),M}catch(R){console.error("[TranslationsProvider] Failed to load:",R),T(R.message),fe(!0);let M={};return Object.keys(ne).forEach(x=>{let L=ne[x],P=z||A||{};M[x]=Ro(L,P,n)}),i&&console.log("[TranslationsProvider] Using fallback translations (critical + URL)"),M}})();Ue=pe;try{let R=await pe;f(R)}finally{I(!1),C(!1),Je=!1,setTimeout(()=>{Ue=null},1e3)}},[c,h,u,s,n,i,a,Q]);Io(()=>{ae();let q=setInterval(ae,3600*1e3);return()=>clearInterval(q)},[ae]);let be=Eo(()=>(q,z)=>{let R=(y[a]||{})[q];if(!R){let M=Object.keys(y);for(let x of M)if(y[x][q]){R=y[x][q];break}}return R||(i&&console.warn(`[TranslationsProvider] Missing translation: "${q}"`),R=q),z&&typeof R=="string"&&Object.entries(z).forEach(([M,x])=>{let L=new RegExp(`{{${M}}}`,"g");R=R.replace(L,String(x))}),R},[y,a,i]);xr(y,a,m,w,i);let _={t:be,language:a,availableLanguages:Object.keys(y),translations:y,isLoading:v,error:g,refreshTranslations:ae};return c?p&&W&&v?b||ze("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:ze("div",{children:"Loading translations..."})}):ze(So.Provider,{value:_,children:e}):(i&&console.warn("[TranslationsProvider] No API key available. Skipping translations. Provide apiKey via props or ensure cookies are set by Lambda."),ze(vr,{children:e}))},Lo=()=>{let e=Cr(So);if(!e)throw new Error("useTranslations must be used within TranslationsProvider");return e};import{Box as lt,Typography as ct}from"@mui/material";import{createContext as Er,useContext as Rr,useMemo as Xe}from"react";import{useState as Qe,useEffect as Tr}from"react";var ko=(e,o)=>{let[r,t]=Qe({}),[a,n]=Qe(!1),[s,i]=Qe(null);return Tr(()=>{if(console.log("\u{1F527} [I18nProvider] Hybrid translation loading:",{hasProvidedTranslations:!!o&&Object.keys(o).length>0,hasUrl:!!e,providedKeys:o?Object.keys(o).length:0}),o&&Object.keys(o).length>0){console.log("\u2705 [I18nProvider] Using provided translations (highest priority)"),t(o),n(!1),i(null);return}if(!e){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),t({}),n(!1),i(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",e);let d=!1;return n(!0),i(null),fetch(e).then(w=>{if(!w.ok)throw new Error(`Failed to load translations: ${w.status}`);return w.json()}).then(w=>{d||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:e,keysLoaded:Object.keys(w).length}),t(w),n(!1))}).catch(w=>{d||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",e,w),i(w.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),t({}),n(!1))}),()=>{d=!0}},[e,o]),{translations:r,loading:a,error:s}};import{jsx as Ao}from"react/jsx-runtime";var _o=Er(null),Ir=()=>{try{return Lo()}catch{return null}},Sr=(e,o)=>{if(o.includes(".")){let r=o.split(".").reduce((t,a)=>t&&typeof t=="object"?t[a]:void 0,e);if(r!==void 0)return r}if(e&&e[o])return e[o]},Fo=({children:e,translations:o,translationsUrl:r,language:t="en"})=>{let n=Ir()?.translations?.[t]||{},{translations:s,loading:i}=ko(r,o),d=Xe(()=>({...n,...s,...o||{}}),[n,s,o]),w=Xe(()=>(b,p)=>{let l=Sr(d,b);return l==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${b}" - showing key as-is`),l=b),p&&typeof l=="string"&&Object.entries(p).forEach(([c,h])=>{l=l.replace(new RegExp(`{{${c}}}`,"g"),h)}),typeof l=="string"?l:b},[d]),m=Xe(()=>({t:w,language:t}),[w,t]);return i?Ao("div",{children:"Loading translations..."}):Ao(_o.Provider,{value:m,children:e})},Y=()=>{let e=Rr(_o);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};import{createContext as Lr,useContext as kr,useReducer as Ar,useEffect as Oo}from"react";import{jsx as Fr}from"react/jsx-runtime";var No={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function _r(e,o){switch(o.type){case"SET_SCREEN":let r={...e,currentScreen:o.payload.screen,searchParams:o.payload.params||e.searchParams,errors:{global:[]}},t=new URLSearchParams(r.searchParams),a=t.toString()?`?${t.toString()}`:window.location.pathname;try{window.history.replaceState({},"",a)}catch{}return r;case"SET_SEARCH_PARAMS":return{...e,searchParams:o.payload};case"UPDATE_FORM_DATA":return{...e,formData:{...e.formData,...o.payload},errors:{...e.errors,...Object.keys(o.payload).reduce((n,s)=>({...n,[s]:void 0}),{})}};case"SET_LOADING":return{...e,loading:o.payload};case"SET_ERRORS":return{...e,errors:{...e.errors,...o.payload}};case"CLEAR_ERRORS":return{...e,errors:{global:[]}};case"SET_EMAIL_SENT":return{...e,emailSent:o.payload};case"SET_CODE_ALREADY_EXISTS":return{...e,codeAlreadyExists:o.payload};case"SET_CODE_VALIDATED":return{...e,codeValidated:o.payload};case"SET_FROM_CODE_VERIFICATION":return{...e,fromCodeVerification:o.payload};case"RESET_FORM":return{...e,formData:No.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...e,config:o.payload};default:return e}}var Bo=Lr(void 0),Do=({children:e,initialScreen:o="login",config:r,autoReadFromCookies:t=!0})=>{let[a,n]=Ar(_r,{...No,currentScreen:o});Oo(()=>{n({type:"INIT_CONFIG",payload:(()=>{let l={};if(t)try{let c=po("logo");if(c){let h=decodeURIComponent(c);h.startsWith("http")&&(l.logo=h)}}catch(c){console.error("Error reading configuration from cookies:",c)}return{publicApiKey:r?.publicApiKey,env:r?.env,appName:r?.appName,logo:r?.logo||l.logo,loginActions:r?.loginActions}})()})},[r,t]),Oo(()=>{let p=new URLSearchParams(window.location.search),l={};p.forEach((c,h)=>{l[h]=c}),Object.keys(l).length>0&&n({type:"SET_SEARCH_PARAMS",payload:l}),o==="checkCode"&&l.email&&n({type:"UPDATE_FORM_DATA",payload:{email:l.email,code:l.code||""}}),o==="resetPassword"&&l.link&&n({type:"SET_SEARCH_PARAMS",payload:l})},[o]);let b={state:a,dispatch:n,setScreen:(p,l)=>{n({type:"SET_SCREEN",payload:{screen:p,params:l}})},updateFormData:p=>{n({type:"UPDATE_FORM_DATA",payload:p})},setFieldError:(p,l)=>{n({type:"SET_ERRORS",payload:{[p]:l}})},clearErrors:()=>{n({type:"CLEAR_ERRORS"})},setLoading:p=>{n({type:"SET_LOADING",payload:p})}};return Fr(Bo.Provider,{value:b,children:e})},Me=()=>{let e=kr(Bo);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};import{useEffect as Or,useRef as Nr}from"react";import{Typography as Ze,TextField as Uo,Button as Br,Box as Ie,CircularProgress as Dr,Alert as Ur,Link as zo}from"@mui/material";import{Fragment as Mr,jsx as J,jsxs as Se}from"react/jsx-runtime";var zr=({onScreenChange:e,onExternalNavigate:o,onLoginSuccess:r,onError:t,redirectUrl:a="/"})=>{let{crudify:n}=oe(),{state:s,updateFormData:i,setFieldError:d,clearErrors:w,setLoading:m}=Me(),{login:b}=ie(),p=Y(),{t:l}=p,c=p.i18n,h=Nr(null),u=bo(l,{currentLanguage:c?.language,enableDebug:!1}),y=()=>{if(s.searchParams.redirect)try{let g=decodeURIComponent(s.searchParams.redirect);if(g.startsWith("/")&&!g.startsWith("//"))return g}catch{}return a||"/"};Or(()=>{let g=setTimeout(()=>{h.current&&h.current.focus()},100);return()=>clearTimeout(g)},[]);let f=g=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",g);let T=u.translateError({code:g.code,message:g.message,field:g.field});return console.log("\u{1F50D} [LoginForm] Translation result:",T),T},v=async()=>{if(!s.loading){if(!s.formData.username.trim()){d("username",l("login.usernameRequired"));return}if(!s.formData.password.trim()){d("password",l("login.passwordRequired"));return}w(),m(!0);try{let g=await b(s.formData.username,s.formData.password);if(m(!1),g.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let T=y();r&&r(g.data,T)}else{let T=g.rawResponse||g;I(T)}}catch(g){m(!1);let A=j(g).map(f);d("global",A),t&&t(A.join(", "))}}},I=g=>{let T=j(g),A=[];T.forEach(F=>{F.field?d(F.field,f(F)):A.push(f(F))}),A.length>0&&d("global",A)};return Se(Mr,{children:[Se(Ie,{component:"form",noValidate:!0,onSubmit:g=>{g.preventDefault(),v()},onKeyDown:g=>{g.key==="Enter"&&!s.loading&&(g.preventDefault(),v())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Se(Ie,{sx:{mb:1},children:[J(Ze,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:l("login.usernameOrEmailLabel")}),J(Uo,{fullWidth:!0,id:"email",name:"email",type:"email",value:s.formData.username,disabled:s.loading,onChange:g=>i({username:g.target.value}),error:!!s.errors.username,helperText:s.errors.username,autoComplete:"email",placeholder:l("login.usernameOrEmailPlaceholder"),inputRef:h,required:!0})]}),Se(Ie,{sx:{mb:1},children:[J(Ze,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:l("login.passwordLabel")}),J(Uo,{fullWidth:!0,id:"password",name:"password",type:"password",value:s.formData.password,disabled:s.loading,onChange:g=>i({password:g.target.value}),error:!!s.errors.password,helperText:s.errors.password,autoComplete:"current-password",placeholder:l("login.passwordPlaceholder"),required:!0})]}),s.config.loginActions?.includes("forgotPassword")&&J(Ie,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:J(zo,{sx:{cursor:"pointer"},onClick:()=>{e?.("forgotPassword",s.searchParams)},variant:"body2",color:"secondary",children:l("login.forgotPasswordLink")})}),J(Br,{disabled:s.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:s.loading?J(Dr,{size:20}):l("login.loginButton")})]}),J(Ie,{children:s.errors.global&&s.errors.global.length>0&&s.errors.global.map((g,T)=>J(Ur,{variant:"filled",sx:{mt:2},severity:"error",children:J("div",{children:g})},T))}),s.config.loginActions?.includes("createUser")&&Se(Ze,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[l("login.noAccountPrompt")," ",J(zo,{sx:{cursor:"pointer"},onClick:()=>{let T=`/public/users/create${Object.keys(s.searchParams).length>0?`?${new URLSearchParams(s.searchParams).toString()}`:""}`;o?.(T)},fontWeight:"medium",color:"secondary",children:l("login.signUpLink")})]})]})},Mo=zr;import{useState as Ce,useEffect as Vr,useRef as Wr}from"react";import{Typography as Pe,TextField as Hr,Button as Vo,Box as le,CircularProgress as qr,Alert as Kr,Link as eo}from"@mui/material";import{Fragment as Wo,jsx as V,jsxs as ye}from"react/jsx-runtime";var jr=({onScreenChange:e,onError:o})=>{let{crudify:r}=oe(),[t,a]=Ce(""),[n,s]=Ce(!1),[i,d]=Ce([]),[w,m]=Ce(null),[b,p]=Ce(!1),[l,c]=Ce(!1),h=Wr(null),{t:u}=Y();Vr(()=>{h.current&&!b&&!l&&h.current.focus()},[b,l]);let y=g=>{let T=[`errors.auth.${g.code}`,`errors.data.${g.code}`,`errors.system.${g.code}`,`errors.${g.code}`,`forgotPassword.${g.code.toLowerCase()}`];for(let A of T){let F=u(A);if(F!==A)return F}return g.message||u("error.unknown")},f=g=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(g),v=async()=>{if(!(n||!r)){if(d([]),m(null),!t){m(u("forgotPassword.emailRequired"));return}if(!f(t)){m(u("forgotPassword.invalidEmail"));return}s(!0);try{let g=[{operation:"requestPasswordReset",data:{email:t}}],T=await r.transaction(g);if(T.success)T.data&&T.data.existingCodeValid?c(!0):p(!0);else{let F=j(T).map(y);d(F)}}catch(g){let A=j(g).map(y);d(A),o&&o(A.join(", "))}finally{s(!1)}}},I=()=>{e?.("login")},W=()=>{if(b||l){e?.("checkCode",{email:t});return}if(!t){m(u("forgotPassword.emailRequired"));return}if(!f(t)){m(u("forgotPassword.invalidEmail"));return}e?.("checkCode",{email:t})};return b||l?V(Wo,{children:ye(le,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[ye(le,{sx:{mb:2},children:[V(Pe,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:u(l?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),V(Pe,{variant:"body2",sx:{color:l?"success.main":"grey.600"},children:u("forgotPassword.checkEmailInstructions")})]}),V(Vo,{type:"button",onClick:W,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:u("forgotPassword.enterCodeLink")}),V(le,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:V(eo,{sx:{cursor:"pointer"},onClick:I,variant:"body2",color:"secondary",children:u("common.back")})})]})}):ye(Wo,{children:[ye(le,{component:"form",noValidate:!0,onSubmit:g=>{g.preventDefault(),v()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[ye(le,{sx:{mb:2},children:[V(Pe,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:u("forgotPassword.title")}),V(Pe,{variant:"body2",sx:{color:"grey.600"},children:u("forgotPassword.instructions")})]}),ye(le,{sx:{mb:1},children:[V(Pe,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:u("forgotPassword.emailLabel")}),V(Hr,{fullWidth:!0,id:"email",name:"email",type:"email",value:t,disabled:n,onChange:g=>a(g.target.value),error:!!w,helperText:w,autoComplete:"email",placeholder:u("forgotPassword.emailPlaceholder"),required:!0,autoFocus:!0,inputRef:h})]}),V(Vo,{disabled:n,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?V(qr,{size:20}):u("forgotPassword.sendCodeButton")}),ye(le,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[V(eo,{sx:{cursor:"pointer"},onClick:I,variant:"body2",color:"secondary",children:u("common.back")}),V(Pe,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),V(eo,{sx:{cursor:"pointer"},onClick:W,variant:"body2",color:"secondary",children:u("login.alreadyHaveCodeLink")})]})]}),V(le,{children:i.length>0&&i.map((g,T)=>V(Kr,{variant:"filled",sx:{mt:2},severity:"error",children:g},T))})]})},Ho=jr;import{useState as $,useEffect as qo}from"react";import{Typography as Ve,TextField as Ko,Button as $r,Box as ce,CircularProgress as jo,Alert as $o,Link as Gr}from"@mui/material";import{Fragment as Jr,jsx as H,jsxs as Le}from"react/jsx-runtime";var Yr=({onScreenChange:e,onError:o,searchParams:r,onResetSuccess:t})=>{let{crudify:a}=oe(),[n,s]=$(""),[i,d]=$(""),[w,m]=$(!1),[b,p]=$([]),[l,c]=$(null),[h,u]=$(null),[y,f]=$(""),[v,I]=$(""),[W,C]=$(!1),[g,T]=$(!0),[A,F]=$(!1),[Q,fe]=$(null),[ae,be]=$(!1),{t:_}=Y(),q=x=>{let L=[`errors.auth.${x.code}`,`errors.data.${x.code}`,`errors.system.${x.code}`,`errors.${x.code}`,`resetPassword.${x.code.toLowerCase()}`];for(let P of L){let k=_(P);if(k!==P)return k}return x.message||_("error.unknown")},z=x=>r?r instanceof URLSearchParams?r.get(x):r[x]||null:null;qo(()=>{if(r){if(r){let x=z("fromCodeVerification"),L=z("email"),P=z("code");if(x==="true"&&L&&P){f(L),I(P),C(!0),F(!0),T(!1);return}let k=z("link");if(k)try{let B=decodeURIComponent(k),[X,Re]=B.split("/");if(X&&Re&&X.length===6){I(X),f(Re),C(!1),fe({email:Re,code:X});return}}catch{}if(L&&P){f(L),I(P),C(!1),fe({email:L,code:P});return}}p([_("resetPassword.invalidCode")]),T(!1),setTimeout(()=>e?.("forgotPassword"),3e3)}},[r,a,_,e]),qo(()=>{a&&Q&&!ae&&(be(!0),(async(L,P)=>{try{let k=[{operation:"validatePasswordResetCode",data:{email:L,codePassword:P}}],B=await a.transaction(k);if(B.data&&Array.isArray(B.data)){let X=B.data[0];if(X&&X.response&&X.response.status==="OK"){F(!0);return}}if(B.success)F(!0);else{let Re=j(B).map(q);p(Re),setTimeout(()=>e?.("forgotPassword"),3e3)}}catch(k){let X=j(k).map(q);p(X),setTimeout(()=>e?.("forgotPassword"),3e3)}finally{T(!1),fe(null),be(!1)}})(Q.email,Q.code))},[a,Q,_,e]);let pe=x=>x.length<8?_("resetPassword.passwordTooShort"):null,R=async()=>{if(w||!a)return;p([]),c(null),u(null);let x=!1;if(!n)c(_("resetPassword.newPasswordRequired")),x=!0;else{let L=pe(n);L&&(c(L),x=!0)}if(i?n!==i&&(u(_("resetPassword.passwordsDoNotMatch")),x=!0):(u(_("resetPassword.confirmPasswordRequired")),x=!0),!x){m(!0);try{let L=[{operation:"validateAndResetPassword",data:{email:y,codePassword:v,newPassword:n}}],P=await a.transaction(L);if(P.success)p([]),setTimeout(()=>{t?.()},1e3);else{let B=j(P).map(q);p(B)}}catch(L){let k=j(L).map(q);p(k),o&&o(k.join(", "))}m(!1)}},M=()=>{W?e?.("checkCode",{email:y}):e?.("forgotPassword")};return g?H(ce,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:H(jo,{})}):A?Le(Jr,{children:[Le(ce,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Le(ce,{sx:{mb:2},children:[H(Ve,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:_("resetPassword.title")}),H(Ve,{variant:"body2",sx:{color:"grey.600"},children:_("resetPassword.instructions")})]}),Le(ce,{sx:{mb:1},children:[H(Ve,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:_("resetPassword.newPasswordLabel")}),H(Ko,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:n,disabled:w,onChange:x=>s(x.target.value),error:!!l,helperText:l,autoComplete:"new-password",placeholder:_("resetPassword.newPasswordPlaceholder"),required:!0})]}),Le(ce,{sx:{mb:1},children:[H(Ve,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:_("resetPassword.confirmPasswordLabel")}),H(Ko,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:i,disabled:w,onChange:x=>d(x.target.value),error:!!h,helperText:h,autoComplete:"new-password",placeholder:_("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),H($r,{disabled:w,type:"button",onClick:R,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:w?H(jo,{size:20}):_("resetPassword.resetPasswordButton")}),H(ce,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:H(Gr,{sx:{cursor:"pointer"},onClick:M,variant:"body2",color:"secondary",children:_("common.back")})})]}),H(ce,{children:b.length>0&&b.map((x,L)=>H($o,{variant:"filled",sx:{mt:2},severity:"error",children:x},L))})]}):H(ce,{children:b.length>0&&b.map((x,L)=>H($o,{variant:"filled",sx:{mt:2},severity:"error",children:x},L))})},Go=Yr;import{useState as ke,useEffect as Yo,useRef as Qr}from"react";import{Typography as oo,TextField as Xr,Button as Zr,Box as Ae,CircularProgress as et,Alert as ot,Link as rt}from"@mui/material";import{Fragment as nt,jsx as re,jsxs as We}from"react/jsx-runtime";var tt=({onScreenChange:e,onError:o,searchParams:r})=>{let{crudify:t}=oe(),[a,n]=ke(""),[s,i]=ke(!1),[d,w]=ke([]),[m,b]=ke(null),[p,l]=ke(""),c=Qr(null),{t:h}=Y(),u=C=>r?r instanceof URLSearchParams?r.get(C):r[C]||null:null,y=C=>{let g=[`errors.auth.${C.code}`,`errors.data.${C.code}`,`errors.system.${C.code}`,`errors.${C.code}`,`checkCode.${C.code.toLowerCase()}`];for(let T of g){let A=h(T);if(A!==T)return A}return C.message||h("error.unknown")};Yo(()=>{let C=u("email");C?l(C):e?.("forgotPassword")},[r,e]),Yo(()=>{c.current&&c.current.focus()},[]);let f=async()=>{if(!(s||!t)){if(w([]),b(null),!a){b(h("checkCode.codeRequired"));return}if(a.length!==6){b(h("checkCode.codeRequired"));return}i(!0);try{let C=[{operation:"validatePasswordResetCode",data:{email:p,codePassword:a}}],g=await t.transaction(C);if(g.success)e?.("resetPassword",{email:p,code:a,fromCodeVerification:"true"});else{let A=j(g).map(y);w(A),i(!1)}}catch(C){let T=j(C).map(y);w(T),i(!1),o&&o(T.join(", "))}}},v=()=>{e?.("forgotPassword")},I=C=>{let g=C.target.value.replace(/\D/g,"").slice(0,6);n(g)};return We(nt,{children:[We(Ae,{component:"form",noValidate:!0,onSubmit:C=>{C.preventDefault(),f()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[We(Ae,{sx:{mb:2},children:[re(oo,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:h("checkCode.title")}),re(oo,{variant:"body2",sx:{color:"grey.600"},children:h("checkCode.instructions")})]}),We(Ae,{sx:{mb:1},children:[re(oo,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:h("checkCode.codeLabel")}),re(Xr,{fullWidth:!0,id:"code",name:"code",type:"text",value:a,disabled:s,onChange:I,error:!!m,helperText:m,placeholder:h("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0,autoFocus:!0,inputRef:c})]}),re(Zr,{disabled:s||a.length!==6,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:s?re(et,{size:20}):h("checkCode.verifyButton")}),re(Ae,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:re(rt,{sx:{cursor:"pointer"},onClick:v,variant:"body2",color:"secondary",children:h("common.back")})})]}),re(Ae,{children:d.length>0&&d.map((C,g)=>re(ot,{sx:{mt:2},severity:"error",children:C},g))})]})},Jo=tt;import{Box as st,CircularProgress as at,Alert as Qo,Typography as ro}from"@mui/material";import{Fragment as it,jsx as xe,jsxs as Xo}from"react/jsx-runtime";var Zo=({children:e,fallback:o})=>{let{isLoading:r,error:t,isInitialized:a}=oe(),{t:n}=Y();return r?o||Xo(st,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[xe(at,{}),xe(ro,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):t?xe(Qo,{severity:"error",sx:{mt:2},children:Xo(ro,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",t]})}):a?xe(it,{children:e}):xe(Qo,{severity:"warning",sx:{mt:2},children:xe(ro,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as Z,jsxs as mt}from"react/jsx-runtime";var dt=({onScreenChange:e,onExternalNavigate:o,onLoginSuccess:r,onError:t,redirectUrl:a="/"})=>{let{t:n}=Y(),{state:s,setScreen:i}=Me(),{config:d}=ie(),{showNotification:w}=wo(),m=(p,l)=>{let c=l;p==="login"?c={}:p==="forgotPassword"&&!l&&(c={}),i(p,c),e?.(p,c)},b=()=>{let p={onScreenChange:m,onExternalNavigate:o,onError:t,redirectUrl:a};switch(s.currentScreen){case"forgotPassword":return Z(Ho,{...p});case"checkCode":return Z(Jo,{...p,searchParams:s.searchParams});case"resetPassword":return Z(Go,{...p,searchParams:s.searchParams,onResetSuccess:()=>{let l=n("resetPassword.successMessage");w(l,"success"),m("login")}});default:return Z(Mo,{...p,onLoginSuccess:r})}};return mt(Zo,{children:[Z(lt,{sx:{display:"flex",justifyContent:"center",mb:3},children:Z("img",{src:d.logo||"https://logos.crudia.com/nocios-default.png",alt:n("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:p=>{let l=p.target;l.src="https://logos.crudia.com/nocios-default.png"}})}),!d.logo&&d.appName&&Z(ct,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:d.appName}),b()]})},ut=({translations:e,translationsUrl:o,language:r="en",initialScreen:t="login",autoReadFromCookies:a=!0,...n})=>{let{config:s}=ie();return Z(Fo,{translations:e,translationsUrl:o,language:r,children:Z(ho,{config:s,children:Z(Do,{config:s,initialScreen:t,autoReadFromCookies:a,children:Z(dt,{...n})})})})},na=ut;import{Box as G,Card as er,CardContent as or,Typography as ee,Chip as He,Avatar as gt,Divider as ft,CircularProgress as pt,Alert as rr,List as yt,ListItem as to,ListItemText as no,ListItemIcon as ht,Collapse as bt,IconButton as so}from"@mui/material";import{Person as wt,Email as Ct,Badge as Pt,Security as xt,Schedule as vt,AccountCircle as Tt,ExpandMore as Et,ExpandLess as Rt,Info as It}from"@mui/icons-material";import{useState as St}from"react";import{Fragment as At,jsx as E,jsxs as O}from"react/jsx-runtime";var Lt=({showExtendedData:e=!0,showProfileCard:o=!0,autoRefresh:r=!0})=>{let{userProfile:t,loading:a,error:n,extendedData:s,refreshProfile:i}=Co({autoFetch:r,retryOnError:!0,maxRetries:3}),[d,w]=St(!1);if(a)return O(G,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[E(pt,{}),E(ee,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return O(rr,{severity:"error",action:E(so,{color:"inherit",size:"small",onClick:i,children:E(ee,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!t)return E(rr,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let m=s?.displayData||{},b=s?.totalFields||0,p=f=>{if(!f)return"No disponible";try{return new Date(f).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return f}},l=(f,v)=>v==null?"No disponible":typeof v=="boolean"?v?"S\xED":"No":Array.isArray(v)?v.length>0?v.join(", "):"Ninguno":typeof v=="object"?JSON.stringify(v,null,2):String(v),c=[{key:"id",label:"ID",icon:E(Pt,{})},{key:"email",label:"Email",icon:E(Ct,{})},{key:"username",label:"Usuario",icon:E(wt,{})},{key:"fullName",label:"Nombre completo",icon:E(Tt,{})},{key:"role",label:"Rol",icon:E(xt,{})}],h=[{key:"firstName",label:"Nombre"},{key:"lastName",label:"Apellido"},{key:"isActive",label:"Activo"},{key:"lastLogin",label:"\xDAltimo login"},{key:"createdAt",label:"Creado"},{key:"updatedAt",label:"Actualizado"}],u=[...c.map(f=>f.key),...h.map(f=>f.key),"permissions"],y=Object.keys(m).filter(f=>!u.includes(f)).map(f=>({key:f,label:f}));return O(G,{children:[o&&E(er,{sx:{mb:2},children:O(or,{children:[O(G,{display:"flex",alignItems:"center",mb:2,children:[E(gt,{src:m.avatar,sx:{width:56,height:56,mr:2},children:m.fullName?.[0]||m.username?.[0]||m.email?.[0]}),O(G,{children:[E(ee,{variant:"h6",children:m.fullName||m.username||m.email}),E(ee,{variant:"body2",color:"text.secondary",children:m.role||"Usuario"}),m.isActive!==void 0&&E(He,{label:m.isActive?"Activo":"Inactivo",color:m.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),E(G,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:c.map(({key:f,label:v,icon:I})=>m[f]?O(G,{display:"flex",alignItems:"center",children:[E(G,{sx:{mr:1,color:"text.secondary"},children:I}),O(G,{children:[E(ee,{variant:"caption",color:"text.secondary",children:v}),E(ee,{variant:"body2",children:l(f,m[f])})]})]},f):null)}),m.permissions&&Array.isArray(m.permissions)&&m.permissions.length>0&&O(G,{mt:2,children:[E(ee,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),O(G,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[m.permissions.slice(0,5).map((f,v)=>E(He,{label:f,size:"small",variant:"outlined"},v)),m.permissions.length>5&&E(He,{label:`+${m.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&E(er,{children:O(or,{children:[O(G,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[O(ee,{variant:"h6",display:"flex",alignItems:"center",children:[E(It,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),E(He,{label:`${b} campos totales`,size:"small"})]}),O(yt,{dense:!0,children:[h.map(({key:f,label:v})=>m[f]!==void 0&&O(to,{divider:!0,children:[E(ht,{children:E(vt,{fontSize:"small"})}),E(no,{primary:v,secondary:f.includes("At")||f.includes("Login")?p(m[f]):l(f,m[f])})]},f)),y.length>0&&O(At,{children:[E(ft,{sx:{my:1}}),E(to,{children:E(no,{primary:O(G,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[O(ee,{variant:"subtitle2",children:["Campos Personalizados (",y.length,")"]}),E(so,{size:"small",onClick:()=>w(!d),children:d?E(Rt,{}):E(Et,{})})]})})}),E(bt,{in:d,children:y.map(({key:f,label:v})=>E(to,{sx:{pl:4},children:E(no,{primary:v,secondary:l(f,m[f])})},f))})]})]}),O(G,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[O(ee,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",p(m.updatedAt)]}),E(so,{size:"small",onClick:i,disabled:a,children:E(ee,{variant:"caption",children:"Actualizar"})})]})]})})]})},kt=Lt;var tr=["create","read","update","delete"],nr=["create","read","update","delete"];import{useRef as en}from"react";import{useTranslation as on}from"react-i18next";import{Box as je,Typography as ur,Button as rn,Stack as tn,Alert as mr,Divider as nn}from"@mui/material";import{Add as sn}from"@mui/icons-material";import{forwardRef as Vt}from"react";import{useTranslation as Wt}from"react-i18next";import{Box as he,FormControl as Ht,InputLabel as qt,Select as Kt,MenuItem as jt,IconButton as $t,Typography as ve,FormHelperText as Gt,Stack as Ke,Paper as dr,Divider as Yt,Button as co}from"@mui/material";import{Delete as Jt,SelectAll as Qt,ClearAll as Xt}from"@mui/icons-material";import{useState as sr,useEffect as ar,useRef as ir}from"react";import{useTranslation as _t}from"react-i18next";import{Box as qe,Typography as _e,Button as lr,Stack as ao,FormControlLabel as Ft,FormHelperText as cr,Switch as Ot,ToggleButton as io,ToggleButtonGroup as Nt}from"@mui/material";import{CheckCircle as Bt,Cancel as Dt,SelectAll as Ut,ClearAll as zt}from"@mui/icons-material";import{jsx as D,jsxs as de}from"react/jsx-runtime";var Mt=({value:e,onChange:o,availableFields:r,error:t,disabled:a=!1})=>{let{t:n}=_t(),[s,i]=sr("custom"),[d,w]=sr(!1),m=ir(null);ar(()=>{d&&m.current?.scrollIntoView({behavior:"smooth",block:"start"})},[d]);let b=ir(!1);ar(()=>{let u=e||{allow:[],owner_allow:[],deny:[]},y=new Set(r),f=(u.allow||[]).filter(C=>y.has(C)),v=(u.owner_allow||[]).filter(C=>y.has(C)),I=(u.deny||[]).filter(C=>y.has(C));r.forEach(C=>{!f.includes(C)&&!v.includes(C)&&!I.includes(C)&&I.push(C)});let W={allow:f,owner_allow:v,deny:I};JSON.stringify(W)!==JSON.stringify(u)&&o(W),f.length===r.length?i("all"):I.length===r.length?i("none"):i("custom")},[r,e]);let p=()=>{b.current=!0,o({allow:[...r],owner_allow:[],deny:[]}),i("all"),setTimeout(()=>{b.current=!1},0)},l=()=>{b.current=!0,o({allow:[],owner_allow:[],deny:[...r]}),i("none"),setTimeout(()=>{b.current=!1},0)},c=u=>e?.allow?.includes(u)?"allow":e?.owner_allow?.includes(u)?"owner_allow":"deny",h=(u,y)=>{b.current=!0;let f=new Set(e?.allow||[]),v=new Set(e?.owner_allow||[]),I=new Set(e?.deny||[]);f.delete(u),v.delete(u),I.delete(u),y==="allow"&&f.add(u),y==="owner_allow"&&v.add(u),y==="deny"&&I.add(u),o({allow:Array.from(f),owner_allow:Array.from(v),deny:Array.from(I)}),i("custom"),setTimeout(()=>{b.current=!1},0)};return r.length===0?de(qe,{children:[D(_e,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("modules.form.publicPolicies.fields.conditions.label")}),D(_e,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),t&&D(cr,{error:!0,sx:{mt:1},children:t})]}):de(qe,{children:[D(_e,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.label")}),de(ao,{direction:"row",spacing:1,alignItems:"center",sx:{mb:d?3:1},children:[D(lr,{variant:s==="all"?"contained":"outlined",startIcon:D(Ut,{}),onClick:p,disabled:a,size:"small",sx:{minWidth:120,...s==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("modules.form.publicPolicies.fields.conditions.allFields")}),D(lr,{variant:s==="none"?"contained":"outlined",startIcon:D(zt,{}),onClick:l,disabled:a,size:"small",sx:{minWidth:120,...s==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("modules.form.publicPolicies.fields.conditions.noFields")}),D(qe,{sx:{display:"flex",alignItems:"center",px:1.5,py:.35,borderRadius:"999px",backgroundColor:"#f3f4f6",border:"1px solid #d1d9e0"},children:D(Ft,{control:D(Ot,{size:"small",checked:d,onChange:()=>w(u=>!u),disabled:a,color:"primary",sx:{transform:"scale(1.15)",transformOrigin:"center",m:0}}),label:n("modules.form.publicPolicies.fields.conditions.customEdit"),labelPlacement:"end",sx:{ml:0,".MuiFormControlLabel-label":{fontSize:"0.75rem"}}})})]}),d&&de(qe,{ref:m,sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[D(_e,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.help")}),D(ao,{spacing:1,children:r.map(u=>{let y=c(u);return de(ao,{direction:"row",spacing:1,alignItems:"center",children:[D(_e,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:u}),de(Nt,{value:y,exclusive:!0,size:"small",children:[de(io,{value:"allow",onClick:()=>h(u,"allow"),disabled:a,sx:{px:2,color:y==="allow"?"#ffffff":"#6b7280",backgroundColor:y==="allow"?"#16a34a":"#f3f4f6",borderColor:y==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:y==="allow"?"#15803d":"#e5e7eb",borderColor:y==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[D(Bt,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.allow")]}),D(io,{value:"owner_allow",onClick:()=>h(u,"owner_allow"),disabled:a,sx:{px:2,color:y==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:y==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:y==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:y==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:y==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),de(io,{value:"deny",onClick:()=>h(u,"deny"),disabled:a,sx:{px:2,color:y==="deny"?"#ffffff":"#6b7280",backgroundColor:y==="deny"?"#dc2626":"#f3f4f6",borderColor:y==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:y==="deny"?"#b91c1c":"#e5e7eb",borderColor:y==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[D(Dt,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},u)})})]}),t&&D(cr,{error:!0,sx:{mt:1},children:t})]})},lo=Mt;import{jsx as U,jsxs as K}from"react/jsx-runtime";var Zt=Vt(({policy:e,onChange:o,onRemove:r,availableFields:t,isSubmitting:a=!1,usedActions:n,error:s},i)=>{let{t:d}=Wt(),w=new Set(Array.from(n||[]));w.delete(e.action);let m=tr.map(b=>({value:b,label:d(`modules.form.publicPolicies.fields.action.options.${b}`)}));return K(dr,{ref:i,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[K(he,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[U(ve,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:d("modules.form.publicPolicies.policyTitle")}),U($t,{onClick:r,size:"small",disabled:a,"aria-label":d("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:U(Jt,{})})]}),K(Ke,{spacing:1,children:[U(Ke,{direction:{xs:"column",md:"row"},spacing:2,children:U(he,{sx:{flex:1,minWidth:200},children:K(Ht,{fullWidth:!0,children:[U(qt,{children:d("modules.form.publicPolicies.fields.action.label")}),U(Kt,{value:e.action,label:d("modules.form.publicPolicies.fields.action.label"),disabled:a,onChange:b=>{let p=b.target.value,l={...e,action:p};p==="delete"?(l.permission="deny",delete l.fields):(l.fields={allow:[],owner_allow:[],deny:t},delete l.permission),o(l)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:m.map(b=>{let p=w.has(b.value);return U(jt,{value:b.value,disabled:p,children:b.label},b.value)})}),s&&U(Gt,{error:!0,children:s})]})})}),e.action==="delete"?K(he,{children:[U(ve,{variant:"body2",color:"text.secondary",sx:{mb:2},children:d("modules.form.publicPolicies.fields.conditions.label")}),K(Ke,{direction:"row",spacing:1,sx:{mb:1},children:[U(co,{variant:e.permission==="*"?"contained":"outlined",startIcon:U(Qt,{}),onClick:()=>o({...e,permission:"*"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:d("modules.form.publicPolicies.fields.conditions.allFields")}),U(co,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>o({...e,permission:"owner"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:d("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),U(co,{variant:e.permission==="deny"?"contained":"outlined",startIcon:U(Xt,{}),onClick:()=>o({...e,permission:"deny"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:d("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):U(lo,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:b=>o({...e,fields:b}),availableFields:t,disabled:a}),U(dr,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?K(ve,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[K(he,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[d("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):K(Ke,{spacing:.5,divider:U(Yt,{sx:{borderColor:"#e5e7eb"}}),children:[K(ve,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[K(he,{component:"span",sx:{color:"#16a34a"},children:[d("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(e?.fields?.allow||[]).join(", ")||"-"]}),K(ve,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[K(he,{component:"span",sx:{color:"#0ea5e9"},children:[d("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(e?.fields?.owner_allow||[]).join(", ")||"-"]}),K(ve,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[K(he,{component:"span",sx:{color:"#dc2626"},children:[d("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(e?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),uo=Zt;import{Fragment as cn,jsx as te,jsxs as $e}from"react/jsx-runtime";var an=()=>{let e=globalThis?.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},ln=({policies:e,onChange:o,availableFields:r,errors:t,isSubmitting:a=!1})=>{let{t:n}=on(),s=en({}),i=new Set((e||[]).map(c=>c.action).filter(Boolean)),d=nr.filter(c=>!i.has(c)),w=d.length>0,m=()=>{let c=d[0]||"create",h={id:an(),action:c};c==="delete"?h.permission="deny":h.fields={allow:[],owner_allow:[],deny:r};let u=[...e||[],h];o(u),setTimeout(()=>{let y=u.length-1,f=s.current[y];f&&f.scrollIntoView({behavior:"smooth",block:"center"})},100)},b=c=>{let h=[...e];h.splice(c,1),o(h)},p=(()=>{if(!t)return null;if(typeof t=="string")return t;let c=t._error;return typeof c=="string"?c:null})(),l=new Set((e||[]).map(c=>c.action));return $e(cn,{children:[te(nn,{sx:{borderColor:"#e0e4e7"}}),$e(je,{children:[te(je,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:$e(je,{children:[te(ur,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("modules.form.publicPolicies.title")}),te(ur,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("modules.form.publicPolicies.description")})]})}),p&&te(mr,{severity:"error",sx:{mb:3},children:p}),$e(tn,{spacing:3,children:[(e||[]).length===0?te(mr,{severity:"info",children:n("modules.form.publicPolicies.noPolicies")}):e.map((c,h)=>te(uo,{ref:u=>{s.current[h]=u},policy:c,onChange:u=>{let y=[...e];y[h]=u,o(y)},onRemove:()=>b(h),availableFields:r,isSubmitting:a,usedActions:l,error:typeof t=="object"&&t&&c.id in t?t[c.id]:void 0},c.id)),w&&te(je,{children:te(rn,{type:"button",variant:"outlined",startIcon:te(sn,{}),onClick:m,disabled:a,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("modules.form.publicPolicies.addPolicy")})})]})]})]})},Wa=ln;import{useState as mo}from"react";import{Button as Ge,TextField as gr,Box as Te,Alert as Fe,Typography as ue,CircularProgress as go}from"@mui/material";import{jsx as N,jsxs as se}from"react/jsx-runtime";function Ya(){let[e,o]=mo(""),[r,t]=mo(""),[a,n]=mo(!1),{isAuthenticated:s,isLoading:i,error:d,login:w,logout:m,refreshTokens:b,clearError:p,isExpiringSoon:l,expiresIn:c}=ie(),h=async f=>{if(f.preventDefault(),!e||!r)return;(await w(e,r)).success&&(o(""),t(""),n(!1))},u=async()=>{await m()},y=async()=>{await b()};return s?se(Te,{sx:{maxWidth:600,mx:"auto",p:3},children:[N(ue,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),N(Fe,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),se(Te,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[N(ue,{variant:"h6",gutterBottom:!0,children:"Token Status"}),se(ue,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(c/1e3/60)," minutes"]}),l&&N(Fe,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),se(Te,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[N(Ge,{variant:"contained",onClick:y,disabled:i,startIcon:i?N(go,{size:16}):null,children:"Refresh Tokens"}),N(Ge,{variant:"outlined",color:"error",onClick:u,disabled:i,children:"Logout"})]}),d&&N(Fe,{severity:"error",sx:{mt:2},onClose:p,children:d})]}):se(Te,{sx:{maxWidth:400,mx:"auto",p:3},children:[N(ue,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),N(Fe,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),a?se("form",{onSubmit:h,children:[N(gr,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:f=>o(f.target.value),margin:"normal",required:!0,autoComplete:"email"}),N(gr,{fullWidth:!0,label:"Password",type:"password",value:r,onChange:f=>t(f.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),N(Ge,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:i,startIcon:i?N(go,{size:16}):null,sx:{mt:3,mb:2},children:i?"Logging in...":"Login"})]}):N(Ge,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),d&&N(Fe,{severity:"error",sx:{mt:2},onClose:p,children:d})]})}function Ja(){let{isAuthenticated:e,isLoading:o,isExpiringSoon:r,expiresIn:t}=ie();return o?se(Te,{sx:{display:"flex",alignItems:"center",gap:1},children:[N(go,{size:16}),N(ue,{variant:"caption",children:"Loading session..."})]}):e?se(Te,{children:[N(ue,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),r&&se(ue,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(t/1e3/60)," min"]})]}):N(ue,{variant:"caption",color:"text.secondary",children:"Not logged in"})}import dn from"@mui/material/TextField";import un from"@mui/material/CircularProgress";import fr from"@mui/material/InputAdornment";import mn from"@mui/material/IconButton";import gn from"@mui/icons-material/Refresh";import{jsx as me}from"react/jsx-runtime";var fn=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),pn=({html:e})=>me("span",{dangerouslySetInnerHTML:{__html:fn(e)}}),si=({config:e,value:o,onChange:r,label:t,error:a=!1,helperText:n,readOnly:s=!1,disabled:i=!1})=>{let{value:d,loading:w,error:m,regenerate:b}=Po(e,{autoFetch:!o,onSuccess:y=>{r?.(y)}}),p=o||d,l=a||!!m,c=m||n,h=l&&c&&(c.toLowerCase().includes("duplicate")||c.toLowerCase().includes("duplicado")||c.toLowerCase().includes("duplicada")||c.toLowerCase().includes("unique")||c.toLowerCase().includes("\xFAnico")||c.toLowerCase().includes("unico")||c.toLowerCase().includes("\xFAnica")||c.toLowerCase().includes("unica")||c.toLowerCase().includes("already exists")||c.toLowerCase().includes("ya existe")||c.toLowerCase().includes("e11000"));return me(dn,{label:t,fullWidth:!0,value:p,error:l,helperText:c?me(pn,{html:c}):" ",disabled:i,InputProps:{readOnly:!0,startAdornment:w?me(fr,{position:"start",children:me(un,{size:20})}):void 0,endAdornment:h&&!w?me(fr,{position:"end",children:me(mn,{edge:"end",onClick:async()=>{!i&&!w&&await b()},disabled:i,size:"small",color:"error","aria-label":"regenerar c\xF3digo",title:"Regenerar c\xF3digo",children:me(gn,{})})}):void 0}})};import pr,{useCallback as Oe,useRef as yn,useState as hn}from"react";import Ne from"@mui/material/Box";import Ee from"@mui/material/Typography";import yr from"@mui/material/IconButton";import bn from"@mui/material/LinearProgress";import fo from"@mui/material/CircularProgress";import wn from"@mui/material/Chip";import Cn from"@mui/material/Paper";import Pn from"@mui/material/List";import xn from"@mui/material/ListItem";import vn from"@mui/material/ListItemIcon";import Tn from"@mui/material/ListItemText";import En from"@mui/material/ListItemSecondaryAction";import Rn from"@mui/material/FormHelperText";import In from"@mui/icons-material/CloudUpload";import Sn from"@mui/icons-material/InsertDriveFile";import Ln from"@mui/icons-material/Image";import kn from"@mui/icons-material/PictureAsPdf";import An from"@mui/icons-material/Delete";import _n from"@mui/icons-material/Refresh";import Fn from"@mui/icons-material/CheckCircle";import On from"@mui/icons-material/Error";import{jsx as S,jsxs as ge}from"react/jsx-runtime";var hr=e=>{if(e===0)return"0 B";let o=1024,r=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(o));return`${parseFloat((e/Math.pow(o,t)).toFixed(1))} ${r[t]}`},Nn=e=>e.startsWith("image/")?S(Ln,{color:"primary"}):e==="application/pdf"?S(kn,{color:"error"}):S(Sn,{color:"action"}),Bn=e=>{switch(e){case"completed":return S(Fn,{color:"success",fontSize:"small"});case"error":return S(On,{color:"error",fontSize:"small"});case"uploading":case"pending":return S(fo,{size:16});case"removing":return S(fo,{size:16,color:"error"});default:return null}},Dn=({file:e,disabled:o,onRemove:r,onRetry:t})=>{let a=!o&&e.status!=="uploading"&&e.status!=="removing",n=!o&&e.status==="error"&&e.file;return ge(xn,{sx:{borderRadius:1,mb:.5,bgcolor:e.status==="error"?"error.lighter":"background.paper",border:"1px solid",borderColor:e.status==="error"?"error.light":"divider"},children:[S(vn,{sx:{minWidth:40},children:Nn(e.contentType)}),S(Tn,{primary:ge(Ne,{sx:{display:"flex",alignItems:"center",gap:1},children:[S(Ee,{variant:"body2",noWrap:!0,sx:{maxWidth:200,overflow:"hidden",textOverflow:"ellipsis"},children:e.name}),Bn(e.status)]}),secondary:ge(Ne,{children:[S(Ee,{variant:"caption",color:"text.secondary",children:hr(e.size)}),e.status==="uploading"&&S(bn,{variant:"determinate",value:e.progress,sx:{mt:.5,height:4,borderRadius:2}}),e.status==="error"&&e.errorMessage&&S(Ee,{variant:"caption",color:"error",display:"block",children:e.errorMessage})]})}),ge(En,{children:[n&&S(yr,{edge:"end",size:"small",onClick:()=>t(e.id),color:"primary",title:"Reintentar",children:S(_n,{fontSize:"small"})}),a&&S(yr,{edge:"end",size:"small",onClick:()=>r(e.id),color:"error",title:"Eliminar",children:S(An,{fontSize:"small"})})]})]})},Ai=({label:e,accept:o,maxFileSize:r=10*1024*1024,multiple:t=!1,maxFiles:a,minFiles:n=0,required:s=!1,disabled:i=!1,error:d=!1,helperText:w,onChange:m,onValidation:b,initialFiles:p,placeholder:l,showFileList:c=!0})=>{let h=yn(null),[u,y]=hn(!1),f=t?a:1,v=s?Math.max(n,1):n,I={acceptedTypes:o,maxFileSize:r,maxFiles:f,minFiles:v,onFilesChange:P=>{let k=P.filter(B=>B.status==="completed"&&B.filePath).map(B=>B.filePath);m?.(k)}},{files:W,isUploading:C,addFiles:g,removeFile:T,retryUpload:A,isValid:F,validationError:Q,initializeFiles:fe}=xo(I);pr.useEffect(()=>{p&&p.length>0&&fe(p)},[]),pr.useEffect(()=>{b?.(F,Q)},[F,Q,b]);let ae=Oe(P=>{let k=P.target.files;k&&k.length>0&&g(k),h.current&&(h.current.value="")},[g]),be=Oe(()=>{i||h.current?.click()},[i]),_=Oe(P=>{P.preventDefault(),P.stopPropagation(),i||y(!0)},[i]),q=Oe(P=>{P.preventDefault(),P.stopPropagation(),y(!1)},[]),z=Oe(P=>{if(P.preventDefault(),P.stopPropagation(),y(!1),i)return;let k=P.dataTransfer.files;k&&k.length>0&&g(k)},[i,g]),pe=o?.join(",")||"",R=t||W.length===0,M=d||!F,x=w||Q;return ge(Ne,{sx:{width:"100%"},children:[e&&ge(Ee,{variant:"body2",sx:{mb:1,fontWeight:500,color:M?"error.main":"text.primary"},children:[e,s&&S("span",{style:{color:"red"},children:" *"})]}),S("input",{ref:h,type:"file",accept:pe,multiple:t,onChange:ae,disabled:i,style:{display:"none"}}),R&&ge(Cn,{variant:"outlined",onClick:be,onDragOver:_,onDragLeave:q,onDrop:z,sx:{p:3,textAlign:"center",cursor:i?"not-allowed":"pointer",borderStyle:"dashed",borderWidth:2,borderColor:u?"primary.main":M?"error.main":"divider",bgcolor:u?"primary.lighter":i?"action.disabledBackground":"background.paper",transition:"all 0.2s ease","&:hover":i?{}:{borderColor:"primary.main",bgcolor:"action.hover"}},children:[S(In,{sx:{fontSize:48,color:u?"primary.main":i?"action.disabled":"action.active",mb:1}}),S(Ee,{variant:"body2",color:i?"text.disabled":"text.secondary",children:(()=>{if(l)return l;let P=[];if(u)return"Suelta el archivo aqu\xED";if(P.push("Arrastra archivos aqu\xED o haz clic para seleccionar"),o&&o.length>0){let k=o.map(B=>B.split("/")[1]?.toUpperCase()||B).join(", ");P.push(`Tipos permitidos: ${k}`)}return r&&P.push(`M\xE1ximo ${hr(r)} por archivo`),f!==void 0&&t&&P.push(`M\xE1ximo ${f} archivos`),P[0]})()}),o&&o.length>0&&!u&&S(Ne,{sx:{mt:1,display:"flex",gap:.5,justifyContent:"center",flexWrap:"wrap"},children:o.map(P=>S(wn,{label:P.split("/")[1]?.toUpperCase()||P,size:"small",variant:"outlined",sx:{fontSize:"0.7rem"}},P))})]}),c&&W.length>0&&S(Pn,{dense:!0,sx:{mt:1,p:0},children:W.map(P=>S(Dn,{file:P,disabled:i,onRemove:T,onRetry:A},P.id))}),C&&ge(Ne,{sx:{display:"flex",alignItems:"center",gap:1,mt:1},children:[S(fo,{size:16}),S(Ee,{variant:"caption",color:"text.secondary",children:"Subiendo archivos..."})]}),x&&S(Rn,{error:M,sx:{mt:.5},children:x})]})};export{ne as a,Un as b,zn as c,Ye as d,De as e,Yn as f,Lo as g,na as h,kt as i,tr as j,nr as k,Wa as l,Ya as m,Ja as n,si as o,Ai as p};