@nocios/crudify-ui 4.4.0 → 4.4.2

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.
@@ -1 +1 @@
1
- import{b as io,c as X,h as uo,j as ne,l as go,m as fo}from"./chunk-NEPYABGC.mjs";import{g as V}from"./chunk-BJ6PIVZR.mjs";import{a as lo,e as co}from"./chunk-5JKS55SE.mjs";var oe={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..."},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..."}},on=()=>Object.keys(oe),rn=e=>oe[e]||oe.es;import Ae from"@nocios/crudify-browser";var mo="crudify_translations_",tr=3600*1e3;function po(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 Me=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=Ae.getTokenData();if(t&&t.endpoint){this.enableDebug&&console.log("[TranslationService] Crudify already initialized"),this.isInitialized=!0;return}Ae.config(r);let l=await Ae.init(o,this.enableDebug?"debug":"none");if(l.success===!1)throw new Error(`Failed to initialize crudify: ${JSON.stringify(l.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,sections:t,crudifyEnv:l="stg",urlTranslations:a}=o;this.enableDebug&&console.log("[TranslationService] fetchTranslations called with:",{apiKeyHash:po(r),crudifyEnv:l,sections:t,hasUrlTranslations:!!a});let i=this.getFromCache(r),g=i?this.isCacheExpired(i):!0;if(i&&!g)return this.enableDebug&&console.log("[TranslationService] Using cached translations"),this.mergeWithUrlTranslations(i.data.translations,a);try{await this.ensureCrudifyInitialized(r,l)}catch(c){return console.error("[TranslationService] \u274C Failed to initialize crudify:",c),i?(console.warn("[TranslationService] \u26A0\uFE0F Using expired cache (init failed)"),this.mergeWithUrlTranslations(i.data.translations,a)):(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 c=await this.fetchFromAPI(t);this.hasDataChanged(i,c)||!i?this.saveToCache(r,c):this.refreshCacheTimestamp(r);let d=this.mergeWithUrlTranslations(c.translations,a);return this.enableDebug&&console.log("[TranslationService] Translations loaded:",{languages:Object.keys(d),keysCount:d[Object.keys(d)[0]]?Object.keys(d[Object.keys(d)[0]]).length:0}),d}catch(c){return console.error("[TranslationService] \u274C API fetch failed:",c),i?(console.warn("[TranslationService] \u26A0\uFE0F Using expired cache as fallback"),this.mergeWithUrlTranslations(i.data.translations,a)):(console.warn("[TranslationService] \u26A0\uFE0F Using critical bundle translations"),this.getCriticalTranslationsOnly())}}async fetchFromAPI(o){let r=await Ae.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(l=>{t[l]={...o[l],...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 l=0;l<r.length;l++){let a=r.charCodeAt(l);t=(t<<5)-t+a,t=t&t}return t.toString(36)}saveToCache(o,r){try{let t=this.getCacheKey(o),l={data:r,cachedAt:Date.now(),dataHash:this.hashData(r.translations)};localStorage.setItem(t,JSON.stringify(l)),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>tr}hasValidCache(o){let r=this.getFromCache(o);return r?!this.isCacheExpired(r):!1}getCacheKey(o){return`${mo}${po(o)}`}getCriticalTranslationsOnly(){return oe}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(mo));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)}}},ke=Me.getInstance();import{createContext as nr,useContext as sr,useEffect as ho,useState as pe,useMemo as ar,useCallback as ir}from"react";import{jsx as qe}from"react/jsx-runtime";var _e=null,We=!1,wo=nr(null);function yo(e,o,r){return{...e,...o,...r||{}}}function lr(e,o,r,t,l){ho(()=>{if(!t||!e||!o)return;let a=r||typeof window<"u"&&window.i18next||typeof window<"u"&&window.i18n;if(!a||!a.addResourceBundle){l&&console.log("[TranslationsProvider] i18next not found, skipping auto-sync");return}l&&console.log("[TranslationsProvider] Auto-syncing translations with i18next",{languages:Object.keys(e),currentLanguage:o}),Object.keys(e).forEach(i=>{e[i]&&Object.keys(e[i]).length>0&&(a.addResourceBundle(i,"translation",e[i],!0,!0),l&&console.log(`[TranslationsProvider] Synced ${Object.keys(e[i]).length} keys for language: ${i}`))}),a.language!==o&&(a.changeLanguage(o),l&&console.log(`[TranslationsProvider] Changed i18next language to: ${o}`))},[e,o,r,t,l])}var gn=({children:e,apiKey:o,crudifyEnv:r="stg",sections:t,language:l="es",devTranslations:a,translationUrl:i,enableDebug:g=!1,skipAutoInit:c=!0,autoSyncI18n:h=!0,i18nInstance:d,loadingFallback:w,waitForInitialLoad:f=!0})=>{let[n,s]=pe({}),[p,y]=pe(!0),[T,m]=pe(!0),[P,N]=pe(null),[te,E]=pe(void 0),[u,x]=pe(!1),R=ir(async()=>{if(u){g&&console.log("[TranslationsProvider] Skipping reload - using fallback translations");return}if(ke.hasValidCache(o)&&T&&(g&&console.log("[TranslationsProvider] Valid cache found - not blocking initial render"),m(!1)),We&&_e){g&&console.log("[TranslationsProvider] Fetch already in progress, waiting for existing promise");try{let b=await _e;s(b),y(!1);return}catch{g&&console.warn("[TranslationsProvider] Global fetch failed, retrying")}}We=!0,y(!0),N(null);let j;if(i)try{g&&console.log(`[TranslationsProvider] Fetching translations from URL: ${i}`);let b=await fetch(i);if(!b.ok)throw new Error(`Failed to fetch translations: ${b.statusText}`);j=await b.json(),E(j),g&&console.log("[TranslationsProvider] URL translations loaded:",{keysCount:j?Object.keys(j).length:0})}catch(b){console.error("[TranslationsProvider] Failed to load URL translations:",b),j=void 0,E(void 0)}let me=(async()=>{try{ke.setDebug(g);let b=await ke.fetchTranslations({apiKey:o,crudifyEnv:r,sections:t,urlTranslations:j}),_={};return Object.keys(b).forEach(O=>{let de=oe[O]||{},Ce=b[O]||{};_[O]=yo(de,Ce,a)}),g&&console.log("[TranslationsProvider] Loaded translations:",{languages:Object.keys(_),keysCount:Object.keys(_[l]||{}).length}),_}catch(b){console.error("[TranslationsProvider] Failed to load:",b),N(b.message),x(!0);let _={};return Object.keys(oe).forEach(O=>{let de=oe[O],Ce=j||te||{};_[O]=yo(de,Ce,a)}),g&&console.log("[TranslationsProvider] Using fallback translations (critical + URL)"),_}})();_e=me;try{let b=await me;s(b)}finally{y(!1),m(!1),We=!1,setTimeout(()=>{_e=null},1e3)}},[o,r,t,i,a,g,l,u]);ho(()=>{R();let H=setInterval(R,3600*1e3);return()=>clearInterval(H)},[R]);let D=ar(()=>(H,j)=>{let b=(n[l]||{})[H];if(!b){let _=Object.keys(n);for(let O of _)if(n[O][H]){b=n[O][H];break}}return b||(g&&console.warn(`[TranslationsProvider] Missing translation: "${H}"`),b=H),j&&typeof b=="string"&&Object.entries(j).forEach(([_,O])=>{let de=new RegExp(`{{${_}}}`,"g");b=b.replace(de,String(O))}),b},[n,l,g]);lr(n,l,d,h,g);let fe={t:D,language:l,availableLanguages:Object.keys(n),translations:n,isLoading:p,error:P,refreshTranslations:R};return f&&T&&p?w||qe("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:qe("div",{children:"Loading translations..."})}):qe(wo.Provider,{value:fe,children:e})},bo=()=>{let e=sr(wo);if(!e)throw new Error("useTranslations must be used within TranslationsProvider");return e};import{Box as Kr,Typography as Gr}from"@mui/material";import{createContext as dr,useContext as ur,useMemo as je}from"react";import{useState as He,useEffect as cr}from"react";var Po=(e,o)=>{let[r,t]=He({}),[l,a]=He(!1),[i,g]=He(null);return cr(()=>{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),a(!1),g(null);return}if(!e){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),t({}),a(!1),g(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",e);let c=!1;return a(!0),g(null),fetch(e).then(h=>{if(!h.ok)throw new Error(`Failed to load translations: ${h.status}`);return h.json()}).then(h=>{c||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:e,keysLoaded:Object.keys(h).length}),t(h),a(!1))}).catch(h=>{c||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",e,h),g(h.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),t({}),a(!1))}),()=>{c=!0}},[e,o]),{translations:r,loading:l,error:i}};import{jsx as Co}from"react/jsx-runtime";var xo=dr(null),gr=()=>{try{return bo()}catch{return null}},fr=(e,o)=>{if(o.includes(".")){let r=o.split(".").reduce((t,l)=>t&&typeof t=="object"?t[l]:void 0,e);if(r!==void 0)return r}if(e&&e[o])return e[o]},To=({children:e,translations:o,translationsUrl:r,language:t="en"})=>{let a=gr()?.translations?.[t]||{},{translations:i,loading:g}=Po(r,o),c=je(()=>({...a,...i,...o||{}}),[a,i,o]),h=je(()=>(w,f)=>{let n=fr(c,w);return n==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${w}" - showing key as-is`),n=w),f&&typeof n=="string"&&Object.entries(f).forEach(([s,p])=>{n=n.replace(new RegExp(`{{${s}}}`,"g"),p)}),typeof n=="string"?n:w},[c]),d=je(()=>({t:h,language:t}),[h,t]);return g?Co("div",{children:"Loading translations..."}):Co(xo.Provider,{value:d,children:e})},$=()=>{let e=ur(xo);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};import{createContext as mr,useContext as pr,useReducer as yr,useEffect as Eo}from"react";import{jsx as wr}from"react/jsx-runtime";var vo={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function hr(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),l=t.toString()?`?${t.toString()}`:window.location.pathname;try{window.history.replaceState({},"",l)}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((a,i)=>({...a,[i]: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:vo.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 Ro=mr(void 0),So=({children:e,initialScreen:o="login",config:r,autoReadFromCookies:t=!0})=>{let[l,a]=yr(hr,{...vo,currentScreen:o});Eo(()=>{a({type:"INIT_CONFIG",payload:(()=>{let n={};if(t)try{let s=lo("logo");if(s){let p=decodeURIComponent(s);p.startsWith("http")&&(n.logo=p)}}catch(s){console.error("Error reading configuration from cookies:",s)}return{publicApiKey:r?.publicApiKey,env:r?.env,appName:r?.appName,logo:r?.logo||n.logo,loginActions:r?.loginActions}})()})},[r,t]),Eo(()=>{let f=new URLSearchParams(window.location.search),n={};f.forEach((s,p)=>{n[p]=s}),Object.keys(n).length>0&&a({type:"SET_SEARCH_PARAMS",payload:n}),o==="checkCode"&&n.email&&a({type:"UPDATE_FORM_DATA",payload:{email:n.email,code:n.code||""}}),o==="resetPassword"&&n.link&&a({type:"SET_SEARCH_PARAMS",payload:n})},[o]);let w={state:l,dispatch:a,setScreen:(f,n)=>{a({type:"SET_SCREEN",payload:{screen:f,params:n}})},updateFormData:f=>{a({type:"UPDATE_FORM_DATA",payload:f})},setFieldError:(f,n)=>{a({type:"SET_ERRORS",payload:{[f]:n}})},clearErrors:()=>{a({type:"CLEAR_ERRORS"})},setLoading:f=>{a({type:"SET_LOADING",payload:f})}};return wr(Ro.Provider,{value:w,children:e})},Oe=()=>{let e=pr(Ro);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};import{useEffect as br,useRef as Pr}from"react";import{Typography as $e,TextField as Io,Button as Cr,Box as Te,CircularProgress as xr,Alert as Tr,Link as Lo}from"@mui/material";import{Fragment as vr,jsx as K,jsxs as Ee}from"react/jsx-runtime";var Er=({onScreenChange:e,onExternalNavigate:o,onLoginSuccess:r,onError:t,redirectUrl:l="/"})=>{let{crudify:a}=X(),{state:i,updateFormData:g,setFieldError:c,clearErrors:h,setLoading:d}=Oe(),{login:w}=ne(),f=$(),{t:n}=f,s=f.i18n,p=Pr(null),y=co(n,{currentLanguage:s?.language,enableDebug:!1}),T=()=>{if(i.searchParams.redirect)try{let u=decodeURIComponent(i.searchParams.redirect);if(u.startsWith("/")&&!u.startsWith("//"))return u}catch{}return l||"/"};br(()=>{let u=setTimeout(()=>{p.current&&p.current.focus()},100);return()=>clearTimeout(u)},[]);let m=u=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",u);let x=y.translateError({code:u.code,message:u.message,field:u.field});return console.log("\u{1F50D} [LoginForm] Translation result:",x),x},P=async()=>{if(!i.loading){if(!i.formData.username.trim()){c("username",n("login.usernameRequired"));return}if(!i.formData.password.trim()){c("password",n("login.passwordRequired"));return}h(),d(!0);try{let u=await w(i.formData.username,i.formData.password);if(d(!1),u.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let x=T();r&&r(u.data,x)}else{let x=u.rawResponse||u;N(x)}}catch(u){d(!1);let R=V(u).map(m);c("global",R),t&&t(R.join(", "))}}},N=u=>{let x=V(u),R=[];x.forEach(D=>{D.field?c(D.field,m(D)):R.push(m(D))}),R.length>0&&c("global",R)};return Ee(vr,{children:[Ee(Te,{component:"form",noValidate:!0,onSubmit:u=>{u.preventDefault(),P()},onKeyDown:u=>{u.key==="Enter"&&!i.loading&&(u.preventDefault(),P())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Ee(Te,{sx:{mb:1},children:[K($e,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:n("login.usernameOrEmailLabel")}),K(Io,{fullWidth:!0,id:"email",name:"email",type:"email",value:i.formData.username,disabled:i.loading,onChange:u=>g({username:u.target.value}),error:!!i.errors.username,helperText:i.errors.username,autoComplete:"email",placeholder:n("login.usernameOrEmailPlaceholder"),inputRef:p,required:!0})]}),Ee(Te,{sx:{mb:1},children:[K($e,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:n("login.passwordLabel")}),K(Io,{fullWidth:!0,id:"password",name:"password",type:"password",value:i.formData.password,disabled:i.loading,onChange:u=>g({password:u.target.value}),error:!!i.errors.password,helperText:i.errors.password,autoComplete:"current-password",placeholder:n("login.passwordPlaceholder"),required:!0})]}),i.config.loginActions?.includes("forgotPassword")&&K(Te,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:K(Lo,{sx:{cursor:"pointer"},onClick:()=>{e?.("forgotPassword",i.searchParams)},variant:"body2",color:"secondary",children:n("login.forgotPasswordLink")})}),K(Cr,{disabled:i.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:i.loading?K(xr,{size:20}):n("login.loginButton")})]}),K(Te,{children:i.errors.global&&i.errors.global.length>0&&i.errors.global.map((u,x)=>K(Tr,{variant:"filled",sx:{mt:2},severity:"error",children:K("div",{children:u})},x))}),i.config.loginActions?.includes("createUser")&&Ee($e,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[n("login.noAccountPrompt")," ",K(Lo,{sx:{cursor:"pointer"},onClick:()=>{let x=`/public/users/create${Object.keys(i.searchParams).length>0?`?${new URLSearchParams(i.searchParams).toString()}`:""}`;o?.(x)},fontWeight:"medium",color:"secondary",children:n("login.signUpLink")})]})]})},Ao=Er;import{useState as ye,useEffect as Rr,useRef as Sr}from"react";import{Typography as he,TextField as Ir,Button as ko,Box as se,CircularProgress as Lr,Alert as Ar,Link as Ke}from"@mui/material";import{Fragment as _o,jsx as k,jsxs as ue}from"react/jsx-runtime";var kr=({onScreenChange:e,onError:o})=>{let{crudify:r}=X(),[t,l]=ye(""),[a,i]=ye(!1),[g,c]=ye([]),[h,d]=ye(null),[w,f]=ye(!1),[n,s]=ye(!1),p=Sr(null),{t:y}=$();Rr(()=>{p.current&&!w&&!n&&p.current.focus()},[w,n]);let T=u=>{let x=[`errors.auth.${u.code}`,`errors.data.${u.code}`,`errors.system.${u.code}`,`errors.${u.code}`,`forgotPassword.${u.code.toLowerCase()}`];for(let R of x){let D=y(R);if(D!==R)return D}return u.message||y("error.unknown")},m=u=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u),P=async()=>{if(!(a||!r)){if(c([]),d(null),!t){d(y("forgotPassword.emailRequired"));return}if(!m(t)){d(y("forgotPassword.invalidEmail"));return}i(!0);try{let u=[{operation:"requestPasswordReset",data:{email:t}}],x=await r.transaction(u);if(x.success)x.data&&x.data.existingCodeValid?s(!0):f(!0);else{let D=V(x).map(T);c(D)}}catch(u){let R=V(u).map(T);c(R),o&&o(R.join(", "))}finally{i(!1)}}},N=()=>{e?.("login")},te=()=>{if(w||n){e?.("checkCode",{email:t});return}if(!t){d(y("forgotPassword.emailRequired"));return}if(!m(t)){d(y("forgotPassword.invalidEmail"));return}e?.("checkCode",{email:t})};return w||n?k(_o,{children:ue(se,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[ue(se,{sx:{mb:2},children:[k(he,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:y(n?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),k(he,{variant:"body2",sx:{color:n?"success.main":"grey.600"},children:y("forgotPassword.checkEmailInstructions")})]}),k(ko,{type:"button",onClick:te,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:y("forgotPassword.enterCodeLink")}),k(se,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:k(Ke,{sx:{cursor:"pointer"},onClick:N,variant:"body2",color:"secondary",children:y("common.back")})})]})}):ue(_o,{children:[ue(se,{component:"form",noValidate:!0,onSubmit:u=>{u.preventDefault(),P()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[ue(se,{sx:{mb:2},children:[k(he,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:y("forgotPassword.title")}),k(he,{variant:"body2",sx:{color:"grey.600"},children:y("forgotPassword.instructions")})]}),ue(se,{sx:{mb:1},children:[k(he,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:y("forgotPassword.emailLabel")}),k(Ir,{fullWidth:!0,id:"email",name:"email",type:"email",value:t,disabled:a,onChange:u=>l(u.target.value),error:!!h,helperText:h,autoComplete:"email",placeholder:y("forgotPassword.emailPlaceholder"),required:!0,autoFocus:!0,inputRef:p})]}),k(ko,{disabled:a,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:a?k(Lr,{size:20}):y("forgotPassword.sendCodeButton")}),ue(se,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[k(Ke,{sx:{cursor:"pointer"},onClick:N,variant:"body2",color:"secondary",children:y("common.back")}),k(he,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),k(Ke,{sx:{cursor:"pointer"},onClick:te,variant:"body2",color:"secondary",children:y("login.alreadyHaveCodeLink")})]})]}),k(se,{children:g.length>0&&g.map((u,x)=>k(Ar,{variant:"filled",sx:{mt:2},severity:"error",children:u},x))})]})},Oo=kr;import{useState as W,useEffect as Fo}from"react";import{Typography as Fe,TextField as No,Button as _r,Box as ae,CircularProgress as Do,Alert as Bo,Link as Or}from"@mui/material";import{Fragment as Nr,jsx as F,jsxs as ve}from"react/jsx-runtime";var Fr=({onScreenChange:e,onError:o,searchParams:r,onResetSuccess:t})=>{let{crudify:l}=X(),[a,i]=W(""),[g,c]=W(""),[h,d]=W(!1),[w,f]=W([]),[n,s]=W(null),[p,y]=W(null),[T,m]=W(""),[P,N]=W(""),[te,E]=W(!1),[u,x]=W(!0),[R,D]=W(!1),[fe,H]=W(null),[j,me]=W(!1),{t:b}=$(),_=v=>{let S=[`errors.auth.${v.code}`,`errors.data.${v.code}`,`errors.system.${v.code}`,`errors.${v.code}`,`resetPassword.${v.code.toLowerCase()}`];for(let z of S){let M=b(z);if(M!==z)return M}return v.message||b("error.unknown")},O=v=>r?r instanceof URLSearchParams?r.get(v):r[v]||null:null;Fo(()=>{if(r){if(r){let v=O("fromCodeVerification"),S=O("email"),z=O("code");if(v==="true"&&S&&z){m(S),N(z),E(!0),D(!0),x(!1);return}let M=O("link");if(M)try{let G=decodeURIComponent(M),[Y,xe]=G.split("/");if(Y&&xe&&Y.length===6){N(Y),m(xe),E(!1),H({email:xe,code:Y});return}}catch{}if(S&&z){m(S),N(z),E(!1),H({email:S,code:z});return}}f([b("resetPassword.invalidCode")]),x(!1),setTimeout(()=>e?.("forgotPassword"),3e3)}},[r,l,b,e]),Fo(()=>{l&&fe&&!j&&(me(!0),(async(S,z)=>{try{let M=[{operation:"validatePasswordResetCode",data:{email:S,codePassword:z}}],G=await l.transaction(M);if(G.data&&Array.isArray(G.data)){let Y=G.data[0];if(Y&&Y.response&&Y.response.status==="OK"){D(!0);return}}if(G.success)D(!0);else{let xe=V(G).map(_);f(xe),setTimeout(()=>e?.("forgotPassword"),3e3)}}catch(M){let Y=V(M).map(_);f(Y),setTimeout(()=>e?.("forgotPassword"),3e3)}finally{x(!1),H(null),me(!1)}})(fe.email,fe.code))},[l,fe,b,e]);let de=v=>v.length<8?b("resetPassword.passwordTooShort"):null,Ce=async()=>{if(h||!l)return;f([]),s(null),y(null);let v=!1;if(!a)s(b("resetPassword.newPasswordRequired")),v=!0;else{let S=de(a);S&&(s(S),v=!0)}if(g?a!==g&&(y(b("resetPassword.passwordsDoNotMatch")),v=!0):(y(b("resetPassword.confirmPasswordRequired")),v=!0),!v){d(!0);try{let S=[{operation:"validateAndResetPassword",data:{email:T,codePassword:P,newPassword:a}}],z=await l.transaction(S);if(z.success)f([]),setTimeout(()=>{t?.()},1e3);else{let G=V(z).map(_);f(G)}}catch(S){let M=V(S).map(_);f(M),o&&o(M.join(", "))}d(!1)}},rr=()=>{te?e?.("checkCode",{email:T}):e?.("forgotPassword")};return u?F(ae,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:F(Do,{})}):R?ve(Nr,{children:[ve(ae,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[ve(ae,{sx:{mb:2},children:[F(Fe,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:b("resetPassword.title")}),F(Fe,{variant:"body2",sx:{color:"grey.600"},children:b("resetPassword.instructions")})]}),ve(ae,{sx:{mb:1},children:[F(Fe,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:b("resetPassword.newPasswordLabel")}),F(No,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:a,disabled:h,onChange:v=>i(v.target.value),error:!!n,helperText:n,autoComplete:"new-password",placeholder:b("resetPassword.newPasswordPlaceholder"),required:!0})]}),ve(ae,{sx:{mb:1},children:[F(Fe,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:b("resetPassword.confirmPasswordLabel")}),F(No,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:g,disabled:h,onChange:v=>c(v.target.value),error:!!p,helperText:p,autoComplete:"new-password",placeholder:b("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),F(_r,{disabled:h,type:"button",onClick:Ce,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:h?F(Do,{size:20}):b("resetPassword.resetPasswordButton")}),F(ae,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:F(Or,{sx:{cursor:"pointer"},onClick:rr,variant:"body2",color:"secondary",children:b("common.back")})})]}),F(ae,{children:w.length>0&&w.map((v,S)=>F(Bo,{variant:"filled",sx:{mt:2},severity:"error",children:v},S))})]}):F(ae,{children:w.length>0&&w.map((v,S)=>F(Bo,{variant:"filled",sx:{mt:2},severity:"error",children:v},S))})},Uo=Fr;import{useState as Re,useEffect as zo,useRef as Dr}from"react";import{Typography as Ge,TextField as Br,Button as Ur,Box as Se,CircularProgress as zr,Alert as Vr,Link as Mr}from"@mui/material";import{Fragment as qr,jsx as Z,jsxs as Ne}from"react/jsx-runtime";var Wr=({onScreenChange:e,onError:o,searchParams:r})=>{let{crudify:t}=X(),[l,a]=Re(""),[i,g]=Re(!1),[c,h]=Re([]),[d,w]=Re(null),[f,n]=Re(""),s=Dr(null),{t:p}=$(),y=E=>r?r instanceof URLSearchParams?r.get(E):r[E]||null:null,T=E=>{let u=[`errors.auth.${E.code}`,`errors.data.${E.code}`,`errors.system.${E.code}`,`errors.${E.code}`,`checkCode.${E.code.toLowerCase()}`];for(let x of u){let R=p(x);if(R!==x)return R}return E.message||p("error.unknown")};zo(()=>{let E=y("email");E?n(E):e?.("forgotPassword")},[r,e]),zo(()=>{s.current&&s.current.focus()},[]);let m=async()=>{if(!(i||!t)){if(h([]),w(null),!l){w(p("checkCode.codeRequired"));return}if(l.length!==6){w(p("checkCode.codeRequired"));return}g(!0);try{let E=[{operation:"validatePasswordResetCode",data:{email:f,codePassword:l}}],u=await t.transaction(E);if(u.success)e?.("resetPassword",{email:f,code:l,fromCodeVerification:"true"});else{let R=V(u).map(T);h(R),g(!1)}}catch(E){let x=V(E).map(T);h(x),g(!1),o&&o(x.join(", "))}}},P=()=>{e?.("forgotPassword")},N=E=>{let u=E.target.value.replace(/\D/g,"").slice(0,6);a(u)};return Ne(qr,{children:[Ne(Se,{component:"form",noValidate:!0,onSubmit:E=>{E.preventDefault(),m()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Ne(Se,{sx:{mb:2},children:[Z(Ge,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:p("checkCode.title")}),Z(Ge,{variant:"body2",sx:{color:"grey.600"},children:p("checkCode.instructions")})]}),Ne(Se,{sx:{mb:1},children:[Z(Ge,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:p("checkCode.codeLabel")}),Z(Br,{fullWidth:!0,id:"code",name:"code",type:"text",value:l,disabled:i,onChange:N,error:!!d,helperText:d,placeholder:p("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0,autoFocus:!0,inputRef:s})]}),Z(Ur,{disabled:i||l.length!==6,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:i?Z(zr,{size:20}):p("checkCode.verifyButton")}),Z(Se,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:Z(Mr,{sx:{cursor:"pointer"},onClick:P,variant:"body2",color:"secondary",children:p("common.back")})})]}),Z(Se,{children:c.length>0&&c.map((E,u)=>Z(Vr,{sx:{mt:2},severity:"error",children:E},u))})]})},Vo=Wr;import{Box as Hr,CircularProgress as jr,Alert as Mo,Typography as Ye}from"@mui/material";import{Fragment as $r,jsx as we,jsxs as Wo}from"react/jsx-runtime";var qo=({children:e,fallback:o})=>{let{isLoading:r,error:t,isInitialized:l}=X(),{t:a}=$();return r?o||Wo(Hr,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[we(jr,{}),we(Ye,{variant:"body2",color:"text.secondary",children:a("login.initializing")!=="login.initializing"?a("login.initializing"):"Initializing..."})]}):t?we(Mo,{severity:"error",sx:{mt:2},children:Wo(Ye,{variant:"body2",children:[a("login.initializationError")!=="login.initializationError"?a("login.initializationError"):"Initialization error",":"," ",t]})}):l?we($r,{children:e}):we(Mo,{severity:"warning",sx:{mt:2},children:we(Ye,{variant:"body2",children:a("login.notInitialized")!=="login.notInitialized"?a("login.notInitialized"):"System not initialized"})})};import{jsx as J,jsxs as Qr}from"react/jsx-runtime";var Yr=({onScreenChange:e,onExternalNavigate:o,onLoginSuccess:r,onError:t,redirectUrl:l="/"})=>{let{t:a}=$(),{state:i,setScreen:g}=Oe(),{config:c}=ne(),{showNotification:h}=uo(),d=(f,n)=>{let s=n;f==="login"?s={}:f==="forgotPassword"&&!n&&(s={}),g(f,s),e?.(f,s)},w=()=>{let f={onScreenChange:d,onExternalNavigate:o,onError:t,redirectUrl:l};switch(i.currentScreen){case"forgotPassword":return J(Oo,{...f});case"checkCode":return J(Vo,{...f,searchParams:i.searchParams});case"resetPassword":return J(Uo,{...f,searchParams:i.searchParams,onResetSuccess:()=>{let n=a("resetPassword.successMessage");h(n,"success"),d("login")}});default:return J(Ao,{...f,onLoginSuccess:r})}};return Qr(qo,{children:[J(Kr,{sx:{display:"flex",justifyContent:"center",mb:3},children:J("img",{src:c.logo||"https://logos.crudia.com/nocios-default.png",alt:a("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:f=>{let n=f.target;n.src="https://logos.crudia.com/nocios-default.png"}})}),!c.logo&&c.appName&&J(Gr,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:c.appName}),w()]})},Jr=({translations:e,translationsUrl:o,language:r="en",initialScreen:t="login",autoReadFromCookies:l=!0,...a})=>{let{config:i}=ne();return J(To,{translations:e,translationsUrl:o,language:r,children:J(io,{config:i,children:J(So,{config:i,initialScreen:t,autoReadFromCookies:l,children:J(Yr,{...a})})})})},Cs=Jr;import{Box as q,Card as Ho,CardContent as jo,Typography as Q,Chip as De,Avatar as Xr,Divider as Zr,CircularProgress as et,Alert as $o,List as ot,ListItem as Je,ListItemText as Qe,ListItemIcon as rt,Collapse as tt,IconButton as Xe}from"@mui/material";import{Person as nt,Email as st,Badge as at,Security as it,Schedule as lt,AccountCircle as ct,ExpandMore as dt,ExpandLess as ut,Info as gt}from"@mui/icons-material";import{useState as ft}from"react";import{Fragment as yt,jsx as C,jsxs as I}from"react/jsx-runtime";var mt=({showExtendedData:e=!0,showProfileCard:o=!0,autoRefresh:r=!0})=>{let{userProfile:t,loading:l,error:a,extendedData:i,refreshProfile:g}=go({autoFetch:r,retryOnError:!0,maxRetries:3}),[c,h]=ft(!1);if(l)return I(q,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[C(et,{}),C(Q,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(a)return I($o,{severity:"error",action:C(Xe,{color:"inherit",size:"small",onClick:g,children:C(Q,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",a]});if(!t)return C($o,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let d=i?.displayData||{},w=i?.totalFields||0,f=m=>{if(!m)return"No disponible";try{return new Date(m).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return m}},n=(m,P)=>P==null?"No disponible":typeof P=="boolean"?P?"S\xED":"No":Array.isArray(P)?P.length>0?P.join(", "):"Ninguno":typeof P=="object"?JSON.stringify(P,null,2):String(P),s=[{key:"id",label:"ID",icon:C(at,{})},{key:"email",label:"Email",icon:C(st,{})},{key:"username",label:"Usuario",icon:C(nt,{})},{key:"fullName",label:"Nombre completo",icon:C(ct,{})},{key:"role",label:"Rol",icon:C(it,{})}],p=[{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"}],y=[...s.map(m=>m.key),...p.map(m=>m.key),"permissions"],T=Object.keys(d).filter(m=>!y.includes(m)).map(m=>({key:m,label:m}));return I(q,{children:[o&&C(Ho,{sx:{mb:2},children:I(jo,{children:[I(q,{display:"flex",alignItems:"center",mb:2,children:[C(Xr,{src:d.avatar,sx:{width:56,height:56,mr:2},children:d.fullName?.[0]||d.username?.[0]||d.email?.[0]}),I(q,{children:[C(Q,{variant:"h6",children:d.fullName||d.username||d.email}),C(Q,{variant:"body2",color:"text.secondary",children:d.role||"Usuario"}),d.isActive!==void 0&&C(De,{label:d.isActive?"Activo":"Inactivo",color:d.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),C(q,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:s.map(({key:m,label:P,icon:N})=>d[m]?I(q,{display:"flex",alignItems:"center",children:[C(q,{sx:{mr:1,color:"text.secondary"},children:N}),I(q,{children:[C(Q,{variant:"caption",color:"text.secondary",children:P}),C(Q,{variant:"body2",children:n(m,d[m])})]})]},m):null)}),d.permissions&&Array.isArray(d.permissions)&&d.permissions.length>0&&I(q,{mt:2,children:[C(Q,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),I(q,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[d.permissions.slice(0,5).map((m,P)=>C(De,{label:m,size:"small",variant:"outlined"},P)),d.permissions.length>5&&C(De,{label:`+${d.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&C(Ho,{children:I(jo,{children:[I(q,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[I(Q,{variant:"h6",display:"flex",alignItems:"center",children:[C(gt,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),C(De,{label:`${w} campos totales`,size:"small"})]}),I(ot,{dense:!0,children:[p.map(({key:m,label:P})=>d[m]!==void 0&&I(Je,{divider:!0,children:[C(rt,{children:C(lt,{fontSize:"small"})}),C(Qe,{primary:P,secondary:m.includes("At")||m.includes("Login")?f(d[m]):n(m,d[m])})]},m)),T.length>0&&I(yt,{children:[C(Zr,{sx:{my:1}}),C(Je,{children:C(Qe,{primary:I(q,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[I(Q,{variant:"subtitle2",children:["Campos Personalizados (",T.length,")"]}),C(Xe,{size:"small",onClick:()=>h(!c),children:c?C(ut,{}):C(dt,{})})]})})}),C(tt,{in:c,children:T.map(({key:m,label:P})=>C(Je,{sx:{pl:4},children:C(Qe,{primary:P,secondary:n(m,d[m])})},m))})]})]}),I(q,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[I(Q,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",f(d.updatedAt)]}),C(Xe,{size:"small",onClick:g,disabled:l,children:C(Q,{variant:"caption",children:"Actualizar"})})]})]})})]})},pt=mt;var Ko=["create","read","update","delete"],Go=["create","read","update","delete"];import{useRef as Vt}from"react";import{useTranslation as Mt}from"react-i18next";import{Box as Ue,Typography as Xo,Button as Wt,Stack as qt,Alert as Zo,Divider as Ht}from"@mui/material";import{Add as jt}from"@mui/icons-material";import{forwardRef as St}from"react";import{useTranslation as It}from"react-i18next";import{Box as ge,FormControl as Lt,InputLabel as At,Select as kt,MenuItem as _t,IconButton as Ot,Typography as be,FormHelperText as Ft,Stack as Be,Paper as Qo,Divider as Nt,Button as to}from"@mui/material";import{Delete as Dt,SelectAll as Bt,ClearAll as Ut}from"@mui/icons-material";import{useState as ht,useEffect as wt,useRef as bt}from"react";import{useTranslation as Pt}from"react-i18next";import{Box as Ze,Typography as Ie,Button as Yo,Stack as eo,FormHelperText as Jo,ToggleButton as oo,ToggleButtonGroup as Ct}from"@mui/material";import{CheckCircle as xt,Cancel as Tt,SelectAll as Et,ClearAll as vt}from"@mui/icons-material";import{jsx as B,jsxs as ie}from"react/jsx-runtime";var Rt=({value:e,onChange:o,availableFields:r,error:t,disabled:l=!1})=>{let{t:a}=Pt(),[i,g]=ht("custom"),c=bt(!1);wt(()=>{let n=e||{allow:[],owner_allow:[],deny:[]},s=new Set(r),p=(n.allow||[]).filter(P=>s.has(P)),y=(n.owner_allow||[]).filter(P=>s.has(P)),T=(n.deny||[]).filter(P=>s.has(P));r.forEach(P=>{!p.includes(P)&&!y.includes(P)&&!T.includes(P)&&T.push(P)});let m={allow:p,owner_allow:y,deny:T};JSON.stringify(m)!==JSON.stringify(n)&&o(m),p.length===r.length?g("all"):T.length===r.length?g("none"):g("custom")},[r,e]);let h=()=>{c.current=!0,o({allow:[...r],owner_allow:[],deny:[]}),g("all"),setTimeout(()=>{c.current=!1},0)},d=()=>{c.current=!0,o({allow:[],owner_allow:[],deny:[...r]}),g("none"),setTimeout(()=>{c.current=!1},0)},w=n=>e?.allow?.includes(n)?"allow":e?.owner_allow?.includes(n)?"owner_allow":"deny",f=(n,s)=>{c.current=!0;let p=new Set(e?.allow||[]),y=new Set(e?.owner_allow||[]),T=new Set(e?.deny||[]);p.delete(n),y.delete(n),T.delete(n),s==="allow"&&p.add(n),s==="owner_allow"&&y.add(n),s==="deny"&&T.add(n),o({allow:Array.from(p),owner_allow:Array.from(y),deny:Array.from(T)}),g("custom"),setTimeout(()=>{c.current=!1},0)};return r.length===0?ie(Ze,{children:[B(Ie,{variant:"body2",color:"text.secondary",sx:{mb:1},children:a("modules.form.publicPolicies.fields.conditions.label")}),B(Ie,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:a("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),t&&B(Jo,{error:!0,sx:{mt:1},children:t})]}):ie(Ze,{children:[B(Ie,{variant:"body2",color:"text.secondary",sx:{mb:2},children:a("modules.form.publicPolicies.fields.conditions.label")}),ie(eo,{direction:"row",spacing:1,sx:{mb:3},children:[B(Yo,{variant:i==="all"?"contained":"outlined",startIcon:B(Et,{}),onClick:h,disabled:l,size:"small",sx:{minWidth:120,...i==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:a("modules.form.publicPolicies.fields.conditions.allFields")}),B(Yo,{variant:i==="none"?"contained":"outlined",startIcon:B(vt,{}),onClick:d,disabled:l,size:"small",sx:{minWidth:120,...i==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:a("modules.form.publicPolicies.fields.conditions.noFields")})]}),ie(Ze,{sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[B(Ie,{variant:"body2",color:"text.secondary",sx:{mb:2},children:a("modules.form.publicPolicies.fields.conditions.help")}),B(eo,{spacing:1,children:r.map(n=>{let s=w(n);return ie(eo,{direction:"row",spacing:1,alignItems:"center",children:[B(Ie,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:n}),ie(Ct,{value:s,exclusive:!0,size:"small",children:[ie(oo,{value:"allow",onClick:()=>f(n,"allow"),disabled:l,sx:{px:2,color:s==="allow"?"#ffffff":"#6b7280",backgroundColor:s==="allow"?"#16a34a":"#f3f4f6",borderColor:s==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:s==="allow"?"#15803d":"#e5e7eb",borderColor:s==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[B(xt,{sx:{fontSize:16,mr:.5}}),a("modules.form.publicPolicies.fields.conditions.states.allow")]}),B(oo,{value:"owner_allow",onClick:()=>f(n,"owner_allow"),disabled:l,sx:{px:2,color:s==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:s==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:s==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:s==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:s==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:a("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),ie(oo,{value:"deny",onClick:()=>f(n,"deny"),disabled:l,sx:{px:2,color:s==="deny"?"#ffffff":"#6b7280",backgroundColor:s==="deny"?"#dc2626":"#f3f4f6",borderColor:s==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:s==="deny"?"#b91c1c":"#e5e7eb",borderColor:s==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[B(Tt,{sx:{fontSize:16,mr:.5}}),a("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},n)})})]}),t&&B(Jo,{error:!0,sx:{mt:1},children:t})]})},ro=Rt;import{jsx as A,jsxs as U}from"react/jsx-runtime";var zt=St(({policy:e,onChange:o,onRemove:r,availableFields:t,isSubmitting:l=!1,usedActions:a,error:i},g)=>{let{t:c}=It(),h=new Set(Array.from(a||[]));h.delete(e.action);let d=Ko.map(w=>({value:w,label:c(`modules.form.publicPolicies.fields.action.options.${w}`)}));return U(Qo,{ref:g,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[U(ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[A(be,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:c("modules.form.publicPolicies.policyTitle")}),A(Ot,{onClick:r,size:"small",disabled:l,"aria-label":c("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:A(Dt,{})})]}),U(Be,{spacing:3,children:[A(Be,{direction:{xs:"column",md:"row"},spacing:2,children:A(ge,{sx:{flex:1,minWidth:200},children:U(Lt,{fullWidth:!0,children:[A(At,{children:c("modules.form.publicPolicies.fields.action.label")}),A(kt,{value:e.action,label:c("modules.form.publicPolicies.fields.action.label"),disabled:l,onChange:w=>{let f=w.target.value,n={...e,action:f};f==="delete"?(n.permission="deny",delete n.fields):(n.fields={allow:[],owner_allow:[],deny:t},delete n.permission),o(n)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:d.map(w=>{let f=h.has(w.value);return A(_t,{value:w.value,disabled:f,children:w.label},w.value)})}),i&&A(Ft,{error:!0,children:i})]})})}),e.action==="delete"?U(ge,{children:[A(be,{variant:"body2",color:"text.secondary",sx:{mb:2},children:c("modules.form.publicPolicies.fields.conditions.label")}),U(Be,{direction:"row",spacing:1,sx:{mb:3},children:[A(to,{variant:e.permission==="*"?"contained":"outlined",startIcon:A(Bt,{}),onClick:()=>o({...e,permission:"*"}),disabled:l,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:c("modules.form.publicPolicies.fields.conditions.allFields")}),A(to,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>o({...e,permission:"owner"}),disabled:l,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:c("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),A(to,{variant:e.permission==="deny"?"contained":"outlined",startIcon:A(Ut,{}),onClick:()=>o({...e,permission:"deny"}),disabled:l,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:c("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):A(ro,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:w=>o({...e,fields:w}),availableFields:t,disabled:l}),A(Qo,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?U(be,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[U(ge,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[c("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):U(Be,{spacing:.5,divider:A(Nt,{sx:{borderColor:"#e5e7eb"}}),children:[U(be,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[U(ge,{component:"span",sx:{color:"#16a34a"},children:[c("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(e?.fields?.allow||[]).join(", ")||"-"]}),U(be,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[U(ge,{component:"span",sx:{color:"#0ea5e9"},children:[c("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(e?.fields?.owner_allow||[]).join(", ")||"-"]}),U(be,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[U(ge,{component:"span",sx:{color:"#dc2626"},children:[c("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(e?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),no=zt;import{Fragment as Gt,jsx as ee,jsxs as ze}from"react/jsx-runtime";var $t=()=>{let e=globalThis?.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},Kt=({policies:e,onChange:o,availableFields:r,errors:t,isSubmitting:l=!1})=>{let{t:a}=Mt(),i=Vt({}),g=new Set((e||[]).map(s=>s.action).filter(Boolean)),c=Go.filter(s=>!g.has(s)),h=c.length>0,d=()=>{let s=c[0]||"create",p={id:$t(),action:s};s==="delete"?p.permission="deny":p.fields={allow:[],owner_allow:[],deny:r};let y=[...e||[],p];o(y),setTimeout(()=>{let T=y.length-1,m=i.current[T];m&&m.scrollIntoView({behavior:"smooth",block:"center"})},100)},w=s=>{let p=[...e];p.splice(s,1),o(p)},f=(()=>{if(!t)return null;if(typeof t=="string")return t;let s=t._error;return typeof s=="string"?s:null})(),n=new Set((e||[]).map(s=>s.action));return ze(Gt,{children:[ee(Ht,{sx:{borderColor:"#e0e4e7"}}),ze(Ue,{children:[ee(Ue,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:ze(Ue,{children:[ee(Xo,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:a("modules.form.publicPolicies.title")}),ee(Xo,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:a("modules.form.publicPolicies.description")})]})}),f&&ee(Zo,{severity:"error",sx:{mb:3},children:f}),ze(qt,{spacing:3,children:[(e||[]).length===0?ee(Zo,{severity:"info",children:a("modules.form.publicPolicies.noPolicies")}):e.map((s,p)=>ee(no,{ref:y=>{i.current[p]=y},policy:s,onChange:y=>{let T=[...e];T[p]=y,o(T)},onRemove:()=>w(p),availableFields:r,isSubmitting:l,usedActions:n,error:typeof t=="object"&&t&&s.id in t?t[s.id]:void 0},s.id)),h&&ee(Ue,{children:ee(Wt,{type:"button",variant:"outlined",startIcon:ee(jt,{}),onClick:d,disabled:l,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:a("modules.form.publicPolicies.addPolicy")})})]})]})]})},sa=Kt;import{useState as so}from"react";import{Button as Ve,TextField as er,Box as Pe,Alert as Le,Typography as le,CircularProgress as ao}from"@mui/material";import{jsx as L,jsxs as re}from"react/jsx-runtime";function ga(){let[e,o]=so(""),[r,t]=so(""),[l,a]=so(!1),{isAuthenticated:i,isLoading:g,error:c,login:h,logout:d,refreshTokens:w,clearError:f,isExpiringSoon:n,expiresIn:s}=ne(),p=async m=>{if(m.preventDefault(),!e||!r)return;(await h(e,r)).success&&(o(""),t(""),a(!1))},y=async()=>{await d()},T=async()=>{await w()};return i?re(Pe,{sx:{maxWidth:600,mx:"auto",p:3},children:[L(le,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),L(Le,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),re(Pe,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[L(le,{variant:"h6",gutterBottom:!0,children:"Token Status"}),re(le,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(s/1e3/60)," minutes"]}),n&&L(Le,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),re(Pe,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[L(Ve,{variant:"contained",onClick:T,disabled:g,startIcon:g?L(ao,{size:16}):null,children:"Refresh Tokens"}),L(Ve,{variant:"outlined",color:"error",onClick:y,disabled:g,children:"Logout"})]}),c&&L(Le,{severity:"error",sx:{mt:2},onClose:f,children:c})]}):re(Pe,{sx:{maxWidth:400,mx:"auto",p:3},children:[L(le,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),L(Le,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),l?re("form",{onSubmit:p,children:[L(er,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:m=>o(m.target.value),margin:"normal",required:!0,autoComplete:"email"}),L(er,{fullWidth:!0,label:"Password",type:"password",value:r,onChange:m=>t(m.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),L(Ve,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:g,startIcon:g?L(ao,{size:16}):null,sx:{mt:3,mb:2},children:g?"Logging in...":"Login"})]}):L(Ve,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>a(!0),sx:{mt:2},children:"Show Login Form"}),c&&L(Le,{severity:"error",sx:{mt:2},onClose:f,children:c})]})}function fa(){let{isAuthenticated:e,isLoading:o,isExpiringSoon:r,expiresIn:t}=ne();return o?re(Pe,{sx:{display:"flex",alignItems:"center",gap:1},children:[L(ao,{size:16}),L(le,{variant:"caption",children:"Loading session..."})]}):e?re(Pe,{children:[L(le,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),r&&re(le,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(t/1e3/60)," min"]})]}):L(le,{variant:"caption",color:"text.secondary",children:"Not logged in"})}import Yt from"@mui/material/TextField";import Jt from"@mui/material/CircularProgress";import or from"@mui/material/InputAdornment";import Qt from"@mui/material/IconButton";import Xt from"@mui/icons-material/Refresh";import{jsx as ce}from"react/jsx-runtime";var Zt=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),en=({html:e})=>ce("span",{dangerouslySetInnerHTML:{__html:Zt(e)}}),xa=({config:e,value:o,onChange:r,label:t,error:l=!1,helperText:a,readOnly:i=!1,disabled:g=!1})=>{let{value:c,loading:h,error:d,regenerate:w}=fo(e,{autoFetch:!o,onSuccess:T=>{r?.(T)}}),f=o||c,n=l||!!d,s=d||a,p=n&&s&&(s.toLowerCase().includes("duplicate")||s.toLowerCase().includes("duplicado")||s.toLowerCase().includes("duplicada")||s.toLowerCase().includes("unique")||s.toLowerCase().includes("\xFAnico")||s.toLowerCase().includes("unico")||s.toLowerCase().includes("\xFAnica")||s.toLowerCase().includes("unica")||s.toLowerCase().includes("already exists")||s.toLowerCase().includes("ya existe")||s.toLowerCase().includes("e11000"));return ce(Yt,{label:t,fullWidth:!0,value:f,error:n,helperText:s?ce(en,{html:s}):" ",disabled:g,InputProps:{readOnly:!0,startAdornment:h?ce(or,{position:"start",children:ce(Jt,{size:20})}):void 0,endAdornment:p&&!h?ce(or,{position:"end",children:ce(Qt,{edge:"end",onClick:async()=>{!g&&!h&&await w()},disabled:g,size:"small",color:"error","aria-label":"regenerar c\xF3digo",title:"Regenerar c\xF3digo",children:ce(Xt,{})})}):void 0}})};export{oe as a,on as b,rn as c,Me as d,ke as e,gn as f,bo as g,Cs as h,pt as i,Ko as j,Go as k,sa as l,ga as m,fa as n,xa as o};
1
+ import{b as io,c as X,h as uo,j as ne,l as go,m as fo}from"./chunk-CQM5LDK7.mjs";import{g as V}from"./chunk-BJ6PIVZR.mjs";import{a as lo,e as co}from"./chunk-5JKS55SE.mjs";var oe={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..."},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..."}},on=()=>Object.keys(oe),rn=e=>oe[e]||oe.es;import Ae from"@nocios/crudify-browser";var mo="crudify_translations_",tr=3600*1e3;function po(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 Me=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=Ae.getTokenData();if(t&&t.endpoint){this.enableDebug&&console.log("[TranslationService] Crudify already initialized"),this.isInitialized=!0;return}Ae.config(r);let l=await Ae.init(o,this.enableDebug?"debug":"none");if(l.success===!1)throw new Error(`Failed to initialize crudify: ${JSON.stringify(l.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,sections:t,crudifyEnv:l="stg",urlTranslations:a}=o;this.enableDebug&&console.log("[TranslationService] fetchTranslations called with:",{apiKeyHash:po(r),crudifyEnv:l,sections:t,hasUrlTranslations:!!a});let i=this.getFromCache(r),g=i?this.isCacheExpired(i):!0;if(i&&!g)return this.enableDebug&&console.log("[TranslationService] Using cached translations"),this.mergeWithUrlTranslations(i.data.translations,a);try{await this.ensureCrudifyInitialized(r,l)}catch(c){return console.error("[TranslationService] \u274C Failed to initialize crudify:",c),i?(console.warn("[TranslationService] \u26A0\uFE0F Using expired cache (init failed)"),this.mergeWithUrlTranslations(i.data.translations,a)):(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 c=await this.fetchFromAPI(t);this.hasDataChanged(i,c)||!i?this.saveToCache(r,c):this.refreshCacheTimestamp(r);let d=this.mergeWithUrlTranslations(c.translations,a);return this.enableDebug&&console.log("[TranslationService] Translations loaded:",{languages:Object.keys(d),keysCount:d[Object.keys(d)[0]]?Object.keys(d[Object.keys(d)[0]]).length:0}),d}catch(c){return console.error("[TranslationService] \u274C API fetch failed:",c),i?(console.warn("[TranslationService] \u26A0\uFE0F Using expired cache as fallback"),this.mergeWithUrlTranslations(i.data.translations,a)):(console.warn("[TranslationService] \u26A0\uFE0F Using critical bundle translations"),this.getCriticalTranslationsOnly())}}async fetchFromAPI(o){let r=await Ae.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(l=>{t[l]={...o[l],...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 l=0;l<r.length;l++){let a=r.charCodeAt(l);t=(t<<5)-t+a,t=t&t}return t.toString(36)}saveToCache(o,r){try{let t=this.getCacheKey(o),l={data:r,cachedAt:Date.now(),dataHash:this.hashData(r.translations)};localStorage.setItem(t,JSON.stringify(l)),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>tr}hasValidCache(o){let r=this.getFromCache(o);return r?!this.isCacheExpired(r):!1}getCacheKey(o){return`${mo}${po(o)}`}getCriticalTranslationsOnly(){return oe}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(mo));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)}}},ke=Me.getInstance();import{createContext as nr,useContext as sr,useEffect as ho,useState as pe,useMemo as ar,useCallback as ir}from"react";import{jsx as qe}from"react/jsx-runtime";var _e=null,We=!1,wo=nr(null);function yo(e,o,r){return{...e,...o,...r||{}}}function lr(e,o,r,t,l){ho(()=>{if(!t||!e||!o)return;let a=r||typeof window<"u"&&window.i18next||typeof window<"u"&&window.i18n;if(!a||!a.addResourceBundle){l&&console.log("[TranslationsProvider] i18next not found, skipping auto-sync");return}l&&console.log("[TranslationsProvider] Auto-syncing translations with i18next",{languages:Object.keys(e),currentLanguage:o}),Object.keys(e).forEach(i=>{e[i]&&Object.keys(e[i]).length>0&&(a.addResourceBundle(i,"translation",e[i],!0,!0),l&&console.log(`[TranslationsProvider] Synced ${Object.keys(e[i]).length} keys for language: ${i}`))}),a.language!==o&&(a.changeLanguage(o),l&&console.log(`[TranslationsProvider] Changed i18next language to: ${o}`))},[e,o,r,t,l])}var gn=({children:e,apiKey:o,crudifyEnv:r="stg",sections:t,language:l="es",devTranslations:a,translationUrl:i,enableDebug:g=!1,skipAutoInit:c=!0,autoSyncI18n:h=!0,i18nInstance:d,loadingFallback:w,waitForInitialLoad:f=!0})=>{let[n,s]=pe({}),[p,y]=pe(!0),[T,m]=pe(!0),[P,N]=pe(null),[te,E]=pe(void 0),[u,x]=pe(!1),R=ir(async()=>{if(u){g&&console.log("[TranslationsProvider] Skipping reload - using fallback translations");return}if(ke.hasValidCache(o)&&T&&(g&&console.log("[TranslationsProvider] Valid cache found - not blocking initial render"),m(!1)),We&&_e){g&&console.log("[TranslationsProvider] Fetch already in progress, waiting for existing promise");try{let b=await _e;s(b),y(!1);return}catch{g&&console.warn("[TranslationsProvider] Global fetch failed, retrying")}}We=!0,y(!0),N(null);let j;if(i)try{g&&console.log(`[TranslationsProvider] Fetching translations from URL: ${i}`);let b=await fetch(i);if(!b.ok)throw new Error(`Failed to fetch translations: ${b.statusText}`);j=await b.json(),E(j),g&&console.log("[TranslationsProvider] URL translations loaded:",{keysCount:j?Object.keys(j).length:0})}catch(b){console.error("[TranslationsProvider] Failed to load URL translations:",b),j=void 0,E(void 0)}let me=(async()=>{try{ke.setDebug(g);let b=await ke.fetchTranslations({apiKey:o,crudifyEnv:r,sections:t,urlTranslations:j}),_={};return Object.keys(b).forEach(O=>{let de=oe[O]||{},Ce=b[O]||{};_[O]=yo(de,Ce,a)}),g&&console.log("[TranslationsProvider] Loaded translations:",{languages:Object.keys(_),keysCount:Object.keys(_[l]||{}).length}),_}catch(b){console.error("[TranslationsProvider] Failed to load:",b),N(b.message),x(!0);let _={};return Object.keys(oe).forEach(O=>{let de=oe[O],Ce=j||te||{};_[O]=yo(de,Ce,a)}),g&&console.log("[TranslationsProvider] Using fallback translations (critical + URL)"),_}})();_e=me;try{let b=await me;s(b)}finally{y(!1),m(!1),We=!1,setTimeout(()=>{_e=null},1e3)}},[o,r,t,i,a,g,l,u]);ho(()=>{R();let H=setInterval(R,3600*1e3);return()=>clearInterval(H)},[R]);let D=ar(()=>(H,j)=>{let b=(n[l]||{})[H];if(!b){let _=Object.keys(n);for(let O of _)if(n[O][H]){b=n[O][H];break}}return b||(g&&console.warn(`[TranslationsProvider] Missing translation: "${H}"`),b=H),j&&typeof b=="string"&&Object.entries(j).forEach(([_,O])=>{let de=new RegExp(`{{${_}}}`,"g");b=b.replace(de,String(O))}),b},[n,l,g]);lr(n,l,d,h,g);let fe={t:D,language:l,availableLanguages:Object.keys(n),translations:n,isLoading:p,error:P,refreshTranslations:R};return f&&T&&p?w||qe("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:qe("div",{children:"Loading translations..."})}):qe(wo.Provider,{value:fe,children:e})},bo=()=>{let e=sr(wo);if(!e)throw new Error("useTranslations must be used within TranslationsProvider");return e};import{Box as Kr,Typography as Gr}from"@mui/material";import{createContext as dr,useContext as ur,useMemo as je}from"react";import{useState as He,useEffect as cr}from"react";var Po=(e,o)=>{let[r,t]=He({}),[l,a]=He(!1),[i,g]=He(null);return cr(()=>{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),a(!1),g(null);return}if(!e){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),t({}),a(!1),g(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",e);let c=!1;return a(!0),g(null),fetch(e).then(h=>{if(!h.ok)throw new Error(`Failed to load translations: ${h.status}`);return h.json()}).then(h=>{c||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:e,keysLoaded:Object.keys(h).length}),t(h),a(!1))}).catch(h=>{c||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",e,h),g(h.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),t({}),a(!1))}),()=>{c=!0}},[e,o]),{translations:r,loading:l,error:i}};import{jsx as Co}from"react/jsx-runtime";var xo=dr(null),gr=()=>{try{return bo()}catch{return null}},fr=(e,o)=>{if(o.includes(".")){let r=o.split(".").reduce((t,l)=>t&&typeof t=="object"?t[l]:void 0,e);if(r!==void 0)return r}if(e&&e[o])return e[o]},To=({children:e,translations:o,translationsUrl:r,language:t="en"})=>{let a=gr()?.translations?.[t]||{},{translations:i,loading:g}=Po(r,o),c=je(()=>({...a,...i,...o||{}}),[a,i,o]),h=je(()=>(w,f)=>{let n=fr(c,w);return n==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${w}" - showing key as-is`),n=w),f&&typeof n=="string"&&Object.entries(f).forEach(([s,p])=>{n=n.replace(new RegExp(`{{${s}}}`,"g"),p)}),typeof n=="string"?n:w},[c]),d=je(()=>({t:h,language:t}),[h,t]);return g?Co("div",{children:"Loading translations..."}):Co(xo.Provider,{value:d,children:e})},$=()=>{let e=ur(xo);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};import{createContext as mr,useContext as pr,useReducer as yr,useEffect as Eo}from"react";import{jsx as wr}from"react/jsx-runtime";var vo={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function hr(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),l=t.toString()?`?${t.toString()}`:window.location.pathname;try{window.history.replaceState({},"",l)}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((a,i)=>({...a,[i]: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:vo.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 Ro=mr(void 0),So=({children:e,initialScreen:o="login",config:r,autoReadFromCookies:t=!0})=>{let[l,a]=yr(hr,{...vo,currentScreen:o});Eo(()=>{a({type:"INIT_CONFIG",payload:(()=>{let n={};if(t)try{let s=lo("logo");if(s){let p=decodeURIComponent(s);p.startsWith("http")&&(n.logo=p)}}catch(s){console.error("Error reading configuration from cookies:",s)}return{publicApiKey:r?.publicApiKey,env:r?.env,appName:r?.appName,logo:r?.logo||n.logo,loginActions:r?.loginActions}})()})},[r,t]),Eo(()=>{let f=new URLSearchParams(window.location.search),n={};f.forEach((s,p)=>{n[p]=s}),Object.keys(n).length>0&&a({type:"SET_SEARCH_PARAMS",payload:n}),o==="checkCode"&&n.email&&a({type:"UPDATE_FORM_DATA",payload:{email:n.email,code:n.code||""}}),o==="resetPassword"&&n.link&&a({type:"SET_SEARCH_PARAMS",payload:n})},[o]);let w={state:l,dispatch:a,setScreen:(f,n)=>{a({type:"SET_SCREEN",payload:{screen:f,params:n}})},updateFormData:f=>{a({type:"UPDATE_FORM_DATA",payload:f})},setFieldError:(f,n)=>{a({type:"SET_ERRORS",payload:{[f]:n}})},clearErrors:()=>{a({type:"CLEAR_ERRORS"})},setLoading:f=>{a({type:"SET_LOADING",payload:f})}};return wr(Ro.Provider,{value:w,children:e})},Oe=()=>{let e=pr(Ro);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};import{useEffect as br,useRef as Pr}from"react";import{Typography as $e,TextField as Io,Button as Cr,Box as Te,CircularProgress as xr,Alert as Tr,Link as Lo}from"@mui/material";import{Fragment as vr,jsx as K,jsxs as Ee}from"react/jsx-runtime";var Er=({onScreenChange:e,onExternalNavigate:o,onLoginSuccess:r,onError:t,redirectUrl:l="/"})=>{let{crudify:a}=X(),{state:i,updateFormData:g,setFieldError:c,clearErrors:h,setLoading:d}=Oe(),{login:w}=ne(),f=$(),{t:n}=f,s=f.i18n,p=Pr(null),y=co(n,{currentLanguage:s?.language,enableDebug:!1}),T=()=>{if(i.searchParams.redirect)try{let u=decodeURIComponent(i.searchParams.redirect);if(u.startsWith("/")&&!u.startsWith("//"))return u}catch{}return l||"/"};br(()=>{let u=setTimeout(()=>{p.current&&p.current.focus()},100);return()=>clearTimeout(u)},[]);let m=u=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",u);let x=y.translateError({code:u.code,message:u.message,field:u.field});return console.log("\u{1F50D} [LoginForm] Translation result:",x),x},P=async()=>{if(!i.loading){if(!i.formData.username.trim()){c("username",n("login.usernameRequired"));return}if(!i.formData.password.trim()){c("password",n("login.passwordRequired"));return}h(),d(!0);try{let u=await w(i.formData.username,i.formData.password);if(d(!1),u.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let x=T();r&&r(u.data,x)}else{let x=u.rawResponse||u;N(x)}}catch(u){d(!1);let R=V(u).map(m);c("global",R),t&&t(R.join(", "))}}},N=u=>{let x=V(u),R=[];x.forEach(D=>{D.field?c(D.field,m(D)):R.push(m(D))}),R.length>0&&c("global",R)};return Ee(vr,{children:[Ee(Te,{component:"form",noValidate:!0,onSubmit:u=>{u.preventDefault(),P()},onKeyDown:u=>{u.key==="Enter"&&!i.loading&&(u.preventDefault(),P())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Ee(Te,{sx:{mb:1},children:[K($e,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:n("login.usernameOrEmailLabel")}),K(Io,{fullWidth:!0,id:"email",name:"email",type:"email",value:i.formData.username,disabled:i.loading,onChange:u=>g({username:u.target.value}),error:!!i.errors.username,helperText:i.errors.username,autoComplete:"email",placeholder:n("login.usernameOrEmailPlaceholder"),inputRef:p,required:!0})]}),Ee(Te,{sx:{mb:1},children:[K($e,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:n("login.passwordLabel")}),K(Io,{fullWidth:!0,id:"password",name:"password",type:"password",value:i.formData.password,disabled:i.loading,onChange:u=>g({password:u.target.value}),error:!!i.errors.password,helperText:i.errors.password,autoComplete:"current-password",placeholder:n("login.passwordPlaceholder"),required:!0})]}),i.config.loginActions?.includes("forgotPassword")&&K(Te,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:K(Lo,{sx:{cursor:"pointer"},onClick:()=>{e?.("forgotPassword",i.searchParams)},variant:"body2",color:"secondary",children:n("login.forgotPasswordLink")})}),K(Cr,{disabled:i.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:i.loading?K(xr,{size:20}):n("login.loginButton")})]}),K(Te,{children:i.errors.global&&i.errors.global.length>0&&i.errors.global.map((u,x)=>K(Tr,{variant:"filled",sx:{mt:2},severity:"error",children:K("div",{children:u})},x))}),i.config.loginActions?.includes("createUser")&&Ee($e,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[n("login.noAccountPrompt")," ",K(Lo,{sx:{cursor:"pointer"},onClick:()=>{let x=`/public/users/create${Object.keys(i.searchParams).length>0?`?${new URLSearchParams(i.searchParams).toString()}`:""}`;o?.(x)},fontWeight:"medium",color:"secondary",children:n("login.signUpLink")})]})]})},Ao=Er;import{useState as ye,useEffect as Rr,useRef as Sr}from"react";import{Typography as he,TextField as Ir,Button as ko,Box as se,CircularProgress as Lr,Alert as Ar,Link as Ke}from"@mui/material";import{Fragment as _o,jsx as k,jsxs as ue}from"react/jsx-runtime";var kr=({onScreenChange:e,onError:o})=>{let{crudify:r}=X(),[t,l]=ye(""),[a,i]=ye(!1),[g,c]=ye([]),[h,d]=ye(null),[w,f]=ye(!1),[n,s]=ye(!1),p=Sr(null),{t:y}=$();Rr(()=>{p.current&&!w&&!n&&p.current.focus()},[w,n]);let T=u=>{let x=[`errors.auth.${u.code}`,`errors.data.${u.code}`,`errors.system.${u.code}`,`errors.${u.code}`,`forgotPassword.${u.code.toLowerCase()}`];for(let R of x){let D=y(R);if(D!==R)return D}return u.message||y("error.unknown")},m=u=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u),P=async()=>{if(!(a||!r)){if(c([]),d(null),!t){d(y("forgotPassword.emailRequired"));return}if(!m(t)){d(y("forgotPassword.invalidEmail"));return}i(!0);try{let u=[{operation:"requestPasswordReset",data:{email:t}}],x=await r.transaction(u);if(x.success)x.data&&x.data.existingCodeValid?s(!0):f(!0);else{let D=V(x).map(T);c(D)}}catch(u){let R=V(u).map(T);c(R),o&&o(R.join(", "))}finally{i(!1)}}},N=()=>{e?.("login")},te=()=>{if(w||n){e?.("checkCode",{email:t});return}if(!t){d(y("forgotPassword.emailRequired"));return}if(!m(t)){d(y("forgotPassword.invalidEmail"));return}e?.("checkCode",{email:t})};return w||n?k(_o,{children:ue(se,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[ue(se,{sx:{mb:2},children:[k(he,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:y(n?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),k(he,{variant:"body2",sx:{color:n?"success.main":"grey.600"},children:y("forgotPassword.checkEmailInstructions")})]}),k(ko,{type:"button",onClick:te,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:y("forgotPassword.enterCodeLink")}),k(se,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:k(Ke,{sx:{cursor:"pointer"},onClick:N,variant:"body2",color:"secondary",children:y("common.back")})})]})}):ue(_o,{children:[ue(se,{component:"form",noValidate:!0,onSubmit:u=>{u.preventDefault(),P()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[ue(se,{sx:{mb:2},children:[k(he,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:y("forgotPassword.title")}),k(he,{variant:"body2",sx:{color:"grey.600"},children:y("forgotPassword.instructions")})]}),ue(se,{sx:{mb:1},children:[k(he,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:y("forgotPassword.emailLabel")}),k(Ir,{fullWidth:!0,id:"email",name:"email",type:"email",value:t,disabled:a,onChange:u=>l(u.target.value),error:!!h,helperText:h,autoComplete:"email",placeholder:y("forgotPassword.emailPlaceholder"),required:!0,autoFocus:!0,inputRef:p})]}),k(ko,{disabled:a,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:a?k(Lr,{size:20}):y("forgotPassword.sendCodeButton")}),ue(se,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[k(Ke,{sx:{cursor:"pointer"},onClick:N,variant:"body2",color:"secondary",children:y("common.back")}),k(he,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),k(Ke,{sx:{cursor:"pointer"},onClick:te,variant:"body2",color:"secondary",children:y("login.alreadyHaveCodeLink")})]})]}),k(se,{children:g.length>0&&g.map((u,x)=>k(Ar,{variant:"filled",sx:{mt:2},severity:"error",children:u},x))})]})},Oo=kr;import{useState as W,useEffect as Fo}from"react";import{Typography as Fe,TextField as No,Button as _r,Box as ae,CircularProgress as Do,Alert as Bo,Link as Or}from"@mui/material";import{Fragment as Nr,jsx as F,jsxs as ve}from"react/jsx-runtime";var Fr=({onScreenChange:e,onError:o,searchParams:r,onResetSuccess:t})=>{let{crudify:l}=X(),[a,i]=W(""),[g,c]=W(""),[h,d]=W(!1),[w,f]=W([]),[n,s]=W(null),[p,y]=W(null),[T,m]=W(""),[P,N]=W(""),[te,E]=W(!1),[u,x]=W(!0),[R,D]=W(!1),[fe,H]=W(null),[j,me]=W(!1),{t:b}=$(),_=v=>{let S=[`errors.auth.${v.code}`,`errors.data.${v.code}`,`errors.system.${v.code}`,`errors.${v.code}`,`resetPassword.${v.code.toLowerCase()}`];for(let z of S){let M=b(z);if(M!==z)return M}return v.message||b("error.unknown")},O=v=>r?r instanceof URLSearchParams?r.get(v):r[v]||null:null;Fo(()=>{if(r){if(r){let v=O("fromCodeVerification"),S=O("email"),z=O("code");if(v==="true"&&S&&z){m(S),N(z),E(!0),D(!0),x(!1);return}let M=O("link");if(M)try{let G=decodeURIComponent(M),[Y,xe]=G.split("/");if(Y&&xe&&Y.length===6){N(Y),m(xe),E(!1),H({email:xe,code:Y});return}}catch{}if(S&&z){m(S),N(z),E(!1),H({email:S,code:z});return}}f([b("resetPassword.invalidCode")]),x(!1),setTimeout(()=>e?.("forgotPassword"),3e3)}},[r,l,b,e]),Fo(()=>{l&&fe&&!j&&(me(!0),(async(S,z)=>{try{let M=[{operation:"validatePasswordResetCode",data:{email:S,codePassword:z}}],G=await l.transaction(M);if(G.data&&Array.isArray(G.data)){let Y=G.data[0];if(Y&&Y.response&&Y.response.status==="OK"){D(!0);return}}if(G.success)D(!0);else{let xe=V(G).map(_);f(xe),setTimeout(()=>e?.("forgotPassword"),3e3)}}catch(M){let Y=V(M).map(_);f(Y),setTimeout(()=>e?.("forgotPassword"),3e3)}finally{x(!1),H(null),me(!1)}})(fe.email,fe.code))},[l,fe,b,e]);let de=v=>v.length<8?b("resetPassword.passwordTooShort"):null,Ce=async()=>{if(h||!l)return;f([]),s(null),y(null);let v=!1;if(!a)s(b("resetPassword.newPasswordRequired")),v=!0;else{let S=de(a);S&&(s(S),v=!0)}if(g?a!==g&&(y(b("resetPassword.passwordsDoNotMatch")),v=!0):(y(b("resetPassword.confirmPasswordRequired")),v=!0),!v){d(!0);try{let S=[{operation:"validateAndResetPassword",data:{email:T,codePassword:P,newPassword:a}}],z=await l.transaction(S);if(z.success)f([]),setTimeout(()=>{t?.()},1e3);else{let G=V(z).map(_);f(G)}}catch(S){let M=V(S).map(_);f(M),o&&o(M.join(", "))}d(!1)}},rr=()=>{te?e?.("checkCode",{email:T}):e?.("forgotPassword")};return u?F(ae,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:F(Do,{})}):R?ve(Nr,{children:[ve(ae,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[ve(ae,{sx:{mb:2},children:[F(Fe,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:b("resetPassword.title")}),F(Fe,{variant:"body2",sx:{color:"grey.600"},children:b("resetPassword.instructions")})]}),ve(ae,{sx:{mb:1},children:[F(Fe,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:b("resetPassword.newPasswordLabel")}),F(No,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:a,disabled:h,onChange:v=>i(v.target.value),error:!!n,helperText:n,autoComplete:"new-password",placeholder:b("resetPassword.newPasswordPlaceholder"),required:!0})]}),ve(ae,{sx:{mb:1},children:[F(Fe,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:b("resetPassword.confirmPasswordLabel")}),F(No,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:g,disabled:h,onChange:v=>c(v.target.value),error:!!p,helperText:p,autoComplete:"new-password",placeholder:b("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),F(_r,{disabled:h,type:"button",onClick:Ce,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:h?F(Do,{size:20}):b("resetPassword.resetPasswordButton")}),F(ae,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:F(Or,{sx:{cursor:"pointer"},onClick:rr,variant:"body2",color:"secondary",children:b("common.back")})})]}),F(ae,{children:w.length>0&&w.map((v,S)=>F(Bo,{variant:"filled",sx:{mt:2},severity:"error",children:v},S))})]}):F(ae,{children:w.length>0&&w.map((v,S)=>F(Bo,{variant:"filled",sx:{mt:2},severity:"error",children:v},S))})},Uo=Fr;import{useState as Re,useEffect as zo,useRef as Dr}from"react";import{Typography as Ge,TextField as Br,Button as Ur,Box as Se,CircularProgress as zr,Alert as Vr,Link as Mr}from"@mui/material";import{Fragment as qr,jsx as Z,jsxs as Ne}from"react/jsx-runtime";var Wr=({onScreenChange:e,onError:o,searchParams:r})=>{let{crudify:t}=X(),[l,a]=Re(""),[i,g]=Re(!1),[c,h]=Re([]),[d,w]=Re(null),[f,n]=Re(""),s=Dr(null),{t:p}=$(),y=E=>r?r instanceof URLSearchParams?r.get(E):r[E]||null:null,T=E=>{let u=[`errors.auth.${E.code}`,`errors.data.${E.code}`,`errors.system.${E.code}`,`errors.${E.code}`,`checkCode.${E.code.toLowerCase()}`];for(let x of u){let R=p(x);if(R!==x)return R}return E.message||p("error.unknown")};zo(()=>{let E=y("email");E?n(E):e?.("forgotPassword")},[r,e]),zo(()=>{s.current&&s.current.focus()},[]);let m=async()=>{if(!(i||!t)){if(h([]),w(null),!l){w(p("checkCode.codeRequired"));return}if(l.length!==6){w(p("checkCode.codeRequired"));return}g(!0);try{let E=[{operation:"validatePasswordResetCode",data:{email:f,codePassword:l}}],u=await t.transaction(E);if(u.success)e?.("resetPassword",{email:f,code:l,fromCodeVerification:"true"});else{let R=V(u).map(T);h(R),g(!1)}}catch(E){let x=V(E).map(T);h(x),g(!1),o&&o(x.join(", "))}}},P=()=>{e?.("forgotPassword")},N=E=>{let u=E.target.value.replace(/\D/g,"").slice(0,6);a(u)};return Ne(qr,{children:[Ne(Se,{component:"form",noValidate:!0,onSubmit:E=>{E.preventDefault(),m()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Ne(Se,{sx:{mb:2},children:[Z(Ge,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:p("checkCode.title")}),Z(Ge,{variant:"body2",sx:{color:"grey.600"},children:p("checkCode.instructions")})]}),Ne(Se,{sx:{mb:1},children:[Z(Ge,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:p("checkCode.codeLabel")}),Z(Br,{fullWidth:!0,id:"code",name:"code",type:"text",value:l,disabled:i,onChange:N,error:!!d,helperText:d,placeholder:p("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0,autoFocus:!0,inputRef:s})]}),Z(Ur,{disabled:i||l.length!==6,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:i?Z(zr,{size:20}):p("checkCode.verifyButton")}),Z(Se,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:Z(Mr,{sx:{cursor:"pointer"},onClick:P,variant:"body2",color:"secondary",children:p("common.back")})})]}),Z(Se,{children:c.length>0&&c.map((E,u)=>Z(Vr,{sx:{mt:2},severity:"error",children:E},u))})]})},Vo=Wr;import{Box as Hr,CircularProgress as jr,Alert as Mo,Typography as Ye}from"@mui/material";import{Fragment as $r,jsx as we,jsxs as Wo}from"react/jsx-runtime";var qo=({children:e,fallback:o})=>{let{isLoading:r,error:t,isInitialized:l}=X(),{t:a}=$();return r?o||Wo(Hr,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[we(jr,{}),we(Ye,{variant:"body2",color:"text.secondary",children:a("login.initializing")!=="login.initializing"?a("login.initializing"):"Initializing..."})]}):t?we(Mo,{severity:"error",sx:{mt:2},children:Wo(Ye,{variant:"body2",children:[a("login.initializationError")!=="login.initializationError"?a("login.initializationError"):"Initialization error",":"," ",t]})}):l?we($r,{children:e}):we(Mo,{severity:"warning",sx:{mt:2},children:we(Ye,{variant:"body2",children:a("login.notInitialized")!=="login.notInitialized"?a("login.notInitialized"):"System not initialized"})})};import{jsx as J,jsxs as Qr}from"react/jsx-runtime";var Yr=({onScreenChange:e,onExternalNavigate:o,onLoginSuccess:r,onError:t,redirectUrl:l="/"})=>{let{t:a}=$(),{state:i,setScreen:g}=Oe(),{config:c}=ne(),{showNotification:h}=uo(),d=(f,n)=>{let s=n;f==="login"?s={}:f==="forgotPassword"&&!n&&(s={}),g(f,s),e?.(f,s)},w=()=>{let f={onScreenChange:d,onExternalNavigate:o,onError:t,redirectUrl:l};switch(i.currentScreen){case"forgotPassword":return J(Oo,{...f});case"checkCode":return J(Vo,{...f,searchParams:i.searchParams});case"resetPassword":return J(Uo,{...f,searchParams:i.searchParams,onResetSuccess:()=>{let n=a("resetPassword.successMessage");h(n,"success"),d("login")}});default:return J(Ao,{...f,onLoginSuccess:r})}};return Qr(qo,{children:[J(Kr,{sx:{display:"flex",justifyContent:"center",mb:3},children:J("img",{src:c.logo||"https://logos.crudia.com/nocios-default.png",alt:a("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:f=>{let n=f.target;n.src="https://logos.crudia.com/nocios-default.png"}})}),!c.logo&&c.appName&&J(Gr,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:c.appName}),w()]})},Jr=({translations:e,translationsUrl:o,language:r="en",initialScreen:t="login",autoReadFromCookies:l=!0,...a})=>{let{config:i}=ne();return J(To,{translations:e,translationsUrl:o,language:r,children:J(io,{config:i,children:J(So,{config:i,initialScreen:t,autoReadFromCookies:l,children:J(Yr,{...a})})})})},Cs=Jr;import{Box as q,Card as Ho,CardContent as jo,Typography as Q,Chip as De,Avatar as Xr,Divider as Zr,CircularProgress as et,Alert as $o,List as ot,ListItem as Je,ListItemText as Qe,ListItemIcon as rt,Collapse as tt,IconButton as Xe}from"@mui/material";import{Person as nt,Email as st,Badge as at,Security as it,Schedule as lt,AccountCircle as ct,ExpandMore as dt,ExpandLess as ut,Info as gt}from"@mui/icons-material";import{useState as ft}from"react";import{Fragment as yt,jsx as C,jsxs as I}from"react/jsx-runtime";var mt=({showExtendedData:e=!0,showProfileCard:o=!0,autoRefresh:r=!0})=>{let{userProfile:t,loading:l,error:a,extendedData:i,refreshProfile:g}=go({autoFetch:r,retryOnError:!0,maxRetries:3}),[c,h]=ft(!1);if(l)return I(q,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[C(et,{}),C(Q,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(a)return I($o,{severity:"error",action:C(Xe,{color:"inherit",size:"small",onClick:g,children:C(Q,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",a]});if(!t)return C($o,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let d=i?.displayData||{},w=i?.totalFields||0,f=m=>{if(!m)return"No disponible";try{return new Date(m).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return m}},n=(m,P)=>P==null?"No disponible":typeof P=="boolean"?P?"S\xED":"No":Array.isArray(P)?P.length>0?P.join(", "):"Ninguno":typeof P=="object"?JSON.stringify(P,null,2):String(P),s=[{key:"id",label:"ID",icon:C(at,{})},{key:"email",label:"Email",icon:C(st,{})},{key:"username",label:"Usuario",icon:C(nt,{})},{key:"fullName",label:"Nombre completo",icon:C(ct,{})},{key:"role",label:"Rol",icon:C(it,{})}],p=[{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"}],y=[...s.map(m=>m.key),...p.map(m=>m.key),"permissions"],T=Object.keys(d).filter(m=>!y.includes(m)).map(m=>({key:m,label:m}));return I(q,{children:[o&&C(Ho,{sx:{mb:2},children:I(jo,{children:[I(q,{display:"flex",alignItems:"center",mb:2,children:[C(Xr,{src:d.avatar,sx:{width:56,height:56,mr:2},children:d.fullName?.[0]||d.username?.[0]||d.email?.[0]}),I(q,{children:[C(Q,{variant:"h6",children:d.fullName||d.username||d.email}),C(Q,{variant:"body2",color:"text.secondary",children:d.role||"Usuario"}),d.isActive!==void 0&&C(De,{label:d.isActive?"Activo":"Inactivo",color:d.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),C(q,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:s.map(({key:m,label:P,icon:N})=>d[m]?I(q,{display:"flex",alignItems:"center",children:[C(q,{sx:{mr:1,color:"text.secondary"},children:N}),I(q,{children:[C(Q,{variant:"caption",color:"text.secondary",children:P}),C(Q,{variant:"body2",children:n(m,d[m])})]})]},m):null)}),d.permissions&&Array.isArray(d.permissions)&&d.permissions.length>0&&I(q,{mt:2,children:[C(Q,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),I(q,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[d.permissions.slice(0,5).map((m,P)=>C(De,{label:m,size:"small",variant:"outlined"},P)),d.permissions.length>5&&C(De,{label:`+${d.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&C(Ho,{children:I(jo,{children:[I(q,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[I(Q,{variant:"h6",display:"flex",alignItems:"center",children:[C(gt,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),C(De,{label:`${w} campos totales`,size:"small"})]}),I(ot,{dense:!0,children:[p.map(({key:m,label:P})=>d[m]!==void 0&&I(Je,{divider:!0,children:[C(rt,{children:C(lt,{fontSize:"small"})}),C(Qe,{primary:P,secondary:m.includes("At")||m.includes("Login")?f(d[m]):n(m,d[m])})]},m)),T.length>0&&I(yt,{children:[C(Zr,{sx:{my:1}}),C(Je,{children:C(Qe,{primary:I(q,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[I(Q,{variant:"subtitle2",children:["Campos Personalizados (",T.length,")"]}),C(Xe,{size:"small",onClick:()=>h(!c),children:c?C(ut,{}):C(dt,{})})]})})}),C(tt,{in:c,children:T.map(({key:m,label:P})=>C(Je,{sx:{pl:4},children:C(Qe,{primary:P,secondary:n(m,d[m])})},m))})]})]}),I(q,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[I(Q,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",f(d.updatedAt)]}),C(Xe,{size:"small",onClick:g,disabled:l,children:C(Q,{variant:"caption",children:"Actualizar"})})]})]})})]})},pt=mt;var Ko=["create","read","update","delete"],Go=["create","read","update","delete"];import{useRef as Vt}from"react";import{useTranslation as Mt}from"react-i18next";import{Box as Ue,Typography as Xo,Button as Wt,Stack as qt,Alert as Zo,Divider as Ht}from"@mui/material";import{Add as jt}from"@mui/icons-material";import{forwardRef as St}from"react";import{useTranslation as It}from"react-i18next";import{Box as ge,FormControl as Lt,InputLabel as At,Select as kt,MenuItem as _t,IconButton as Ot,Typography as be,FormHelperText as Ft,Stack as Be,Paper as Qo,Divider as Nt,Button as to}from"@mui/material";import{Delete as Dt,SelectAll as Bt,ClearAll as Ut}from"@mui/icons-material";import{useState as ht,useEffect as wt,useRef as bt}from"react";import{useTranslation as Pt}from"react-i18next";import{Box as Ze,Typography as Ie,Button as Yo,Stack as eo,FormHelperText as Jo,ToggleButton as oo,ToggleButtonGroup as Ct}from"@mui/material";import{CheckCircle as xt,Cancel as Tt,SelectAll as Et,ClearAll as vt}from"@mui/icons-material";import{jsx as B,jsxs as ie}from"react/jsx-runtime";var Rt=({value:e,onChange:o,availableFields:r,error:t,disabled:l=!1})=>{let{t:a}=Pt(),[i,g]=ht("custom"),c=bt(!1);wt(()=>{let n=e||{allow:[],owner_allow:[],deny:[]},s=new Set(r),p=(n.allow||[]).filter(P=>s.has(P)),y=(n.owner_allow||[]).filter(P=>s.has(P)),T=(n.deny||[]).filter(P=>s.has(P));r.forEach(P=>{!p.includes(P)&&!y.includes(P)&&!T.includes(P)&&T.push(P)});let m={allow:p,owner_allow:y,deny:T};JSON.stringify(m)!==JSON.stringify(n)&&o(m),p.length===r.length?g("all"):T.length===r.length?g("none"):g("custom")},[r,e]);let h=()=>{c.current=!0,o({allow:[...r],owner_allow:[],deny:[]}),g("all"),setTimeout(()=>{c.current=!1},0)},d=()=>{c.current=!0,o({allow:[],owner_allow:[],deny:[...r]}),g("none"),setTimeout(()=>{c.current=!1},0)},w=n=>e?.allow?.includes(n)?"allow":e?.owner_allow?.includes(n)?"owner_allow":"deny",f=(n,s)=>{c.current=!0;let p=new Set(e?.allow||[]),y=new Set(e?.owner_allow||[]),T=new Set(e?.deny||[]);p.delete(n),y.delete(n),T.delete(n),s==="allow"&&p.add(n),s==="owner_allow"&&y.add(n),s==="deny"&&T.add(n),o({allow:Array.from(p),owner_allow:Array.from(y),deny:Array.from(T)}),g("custom"),setTimeout(()=>{c.current=!1},0)};return r.length===0?ie(Ze,{children:[B(Ie,{variant:"body2",color:"text.secondary",sx:{mb:1},children:a("modules.form.publicPolicies.fields.conditions.label")}),B(Ie,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:a("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),t&&B(Jo,{error:!0,sx:{mt:1},children:t})]}):ie(Ze,{children:[B(Ie,{variant:"body2",color:"text.secondary",sx:{mb:2},children:a("modules.form.publicPolicies.fields.conditions.label")}),ie(eo,{direction:"row",spacing:1,sx:{mb:3},children:[B(Yo,{variant:i==="all"?"contained":"outlined",startIcon:B(Et,{}),onClick:h,disabled:l,size:"small",sx:{minWidth:120,...i==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:a("modules.form.publicPolicies.fields.conditions.allFields")}),B(Yo,{variant:i==="none"?"contained":"outlined",startIcon:B(vt,{}),onClick:d,disabled:l,size:"small",sx:{minWidth:120,...i==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:a("modules.form.publicPolicies.fields.conditions.noFields")})]}),ie(Ze,{sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[B(Ie,{variant:"body2",color:"text.secondary",sx:{mb:2},children:a("modules.form.publicPolicies.fields.conditions.help")}),B(eo,{spacing:1,children:r.map(n=>{let s=w(n);return ie(eo,{direction:"row",spacing:1,alignItems:"center",children:[B(Ie,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:n}),ie(Ct,{value:s,exclusive:!0,size:"small",children:[ie(oo,{value:"allow",onClick:()=>f(n,"allow"),disabled:l,sx:{px:2,color:s==="allow"?"#ffffff":"#6b7280",backgroundColor:s==="allow"?"#16a34a":"#f3f4f6",borderColor:s==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:s==="allow"?"#15803d":"#e5e7eb",borderColor:s==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[B(xt,{sx:{fontSize:16,mr:.5}}),a("modules.form.publicPolicies.fields.conditions.states.allow")]}),B(oo,{value:"owner_allow",onClick:()=>f(n,"owner_allow"),disabled:l,sx:{px:2,color:s==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:s==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:s==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:s==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:s==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:a("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),ie(oo,{value:"deny",onClick:()=>f(n,"deny"),disabled:l,sx:{px:2,color:s==="deny"?"#ffffff":"#6b7280",backgroundColor:s==="deny"?"#dc2626":"#f3f4f6",borderColor:s==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:s==="deny"?"#b91c1c":"#e5e7eb",borderColor:s==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[B(Tt,{sx:{fontSize:16,mr:.5}}),a("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},n)})})]}),t&&B(Jo,{error:!0,sx:{mt:1},children:t})]})},ro=Rt;import{jsx as A,jsxs as U}from"react/jsx-runtime";var zt=St(({policy:e,onChange:o,onRemove:r,availableFields:t,isSubmitting:l=!1,usedActions:a,error:i},g)=>{let{t:c}=It(),h=new Set(Array.from(a||[]));h.delete(e.action);let d=Ko.map(w=>({value:w,label:c(`modules.form.publicPolicies.fields.action.options.${w}`)}));return U(Qo,{ref:g,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[U(ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[A(be,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:c("modules.form.publicPolicies.policyTitle")}),A(Ot,{onClick:r,size:"small",disabled:l,"aria-label":c("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:A(Dt,{})})]}),U(Be,{spacing:3,children:[A(Be,{direction:{xs:"column",md:"row"},spacing:2,children:A(ge,{sx:{flex:1,minWidth:200},children:U(Lt,{fullWidth:!0,children:[A(At,{children:c("modules.form.publicPolicies.fields.action.label")}),A(kt,{value:e.action,label:c("modules.form.publicPolicies.fields.action.label"),disabled:l,onChange:w=>{let f=w.target.value,n={...e,action:f};f==="delete"?(n.permission="deny",delete n.fields):(n.fields={allow:[],owner_allow:[],deny:t},delete n.permission),o(n)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:d.map(w=>{let f=h.has(w.value);return A(_t,{value:w.value,disabled:f,children:w.label},w.value)})}),i&&A(Ft,{error:!0,children:i})]})})}),e.action==="delete"?U(ge,{children:[A(be,{variant:"body2",color:"text.secondary",sx:{mb:2},children:c("modules.form.publicPolicies.fields.conditions.label")}),U(Be,{direction:"row",spacing:1,sx:{mb:3},children:[A(to,{variant:e.permission==="*"?"contained":"outlined",startIcon:A(Bt,{}),onClick:()=>o({...e,permission:"*"}),disabled:l,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:c("modules.form.publicPolicies.fields.conditions.allFields")}),A(to,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>o({...e,permission:"owner"}),disabled:l,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:c("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),A(to,{variant:e.permission==="deny"?"contained":"outlined",startIcon:A(Ut,{}),onClick:()=>o({...e,permission:"deny"}),disabled:l,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:c("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):A(ro,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:w=>o({...e,fields:w}),availableFields:t,disabled:l}),A(Qo,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?U(be,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[U(ge,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[c("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):U(Be,{spacing:.5,divider:A(Nt,{sx:{borderColor:"#e5e7eb"}}),children:[U(be,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[U(ge,{component:"span",sx:{color:"#16a34a"},children:[c("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(e?.fields?.allow||[]).join(", ")||"-"]}),U(be,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[U(ge,{component:"span",sx:{color:"#0ea5e9"},children:[c("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(e?.fields?.owner_allow||[]).join(", ")||"-"]}),U(be,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[U(ge,{component:"span",sx:{color:"#dc2626"},children:[c("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(e?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),no=zt;import{Fragment as Gt,jsx as ee,jsxs as ze}from"react/jsx-runtime";var $t=()=>{let e=globalThis?.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},Kt=({policies:e,onChange:o,availableFields:r,errors:t,isSubmitting:l=!1})=>{let{t:a}=Mt(),i=Vt({}),g=new Set((e||[]).map(s=>s.action).filter(Boolean)),c=Go.filter(s=>!g.has(s)),h=c.length>0,d=()=>{let s=c[0]||"create",p={id:$t(),action:s};s==="delete"?p.permission="deny":p.fields={allow:[],owner_allow:[],deny:r};let y=[...e||[],p];o(y),setTimeout(()=>{let T=y.length-1,m=i.current[T];m&&m.scrollIntoView({behavior:"smooth",block:"center"})},100)},w=s=>{let p=[...e];p.splice(s,1),o(p)},f=(()=>{if(!t)return null;if(typeof t=="string")return t;let s=t._error;return typeof s=="string"?s:null})(),n=new Set((e||[]).map(s=>s.action));return ze(Gt,{children:[ee(Ht,{sx:{borderColor:"#e0e4e7"}}),ze(Ue,{children:[ee(Ue,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:ze(Ue,{children:[ee(Xo,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:a("modules.form.publicPolicies.title")}),ee(Xo,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:a("modules.form.publicPolicies.description")})]})}),f&&ee(Zo,{severity:"error",sx:{mb:3},children:f}),ze(qt,{spacing:3,children:[(e||[]).length===0?ee(Zo,{severity:"info",children:a("modules.form.publicPolicies.noPolicies")}):e.map((s,p)=>ee(no,{ref:y=>{i.current[p]=y},policy:s,onChange:y=>{let T=[...e];T[p]=y,o(T)},onRemove:()=>w(p),availableFields:r,isSubmitting:l,usedActions:n,error:typeof t=="object"&&t&&s.id in t?t[s.id]:void 0},s.id)),h&&ee(Ue,{children:ee(Wt,{type:"button",variant:"outlined",startIcon:ee(jt,{}),onClick:d,disabled:l,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:a("modules.form.publicPolicies.addPolicy")})})]})]})]})},sa=Kt;import{useState as so}from"react";import{Button as Ve,TextField as er,Box as Pe,Alert as Le,Typography as le,CircularProgress as ao}from"@mui/material";import{jsx as L,jsxs as re}from"react/jsx-runtime";function ga(){let[e,o]=so(""),[r,t]=so(""),[l,a]=so(!1),{isAuthenticated:i,isLoading:g,error:c,login:h,logout:d,refreshTokens:w,clearError:f,isExpiringSoon:n,expiresIn:s}=ne(),p=async m=>{if(m.preventDefault(),!e||!r)return;(await h(e,r)).success&&(o(""),t(""),a(!1))},y=async()=>{await d()},T=async()=>{await w()};return i?re(Pe,{sx:{maxWidth:600,mx:"auto",p:3},children:[L(le,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),L(Le,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),re(Pe,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[L(le,{variant:"h6",gutterBottom:!0,children:"Token Status"}),re(le,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(s/1e3/60)," minutes"]}),n&&L(Le,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),re(Pe,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[L(Ve,{variant:"contained",onClick:T,disabled:g,startIcon:g?L(ao,{size:16}):null,children:"Refresh Tokens"}),L(Ve,{variant:"outlined",color:"error",onClick:y,disabled:g,children:"Logout"})]}),c&&L(Le,{severity:"error",sx:{mt:2},onClose:f,children:c})]}):re(Pe,{sx:{maxWidth:400,mx:"auto",p:3},children:[L(le,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),L(Le,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),l?re("form",{onSubmit:p,children:[L(er,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:m=>o(m.target.value),margin:"normal",required:!0,autoComplete:"email"}),L(er,{fullWidth:!0,label:"Password",type:"password",value:r,onChange:m=>t(m.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),L(Ve,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:g,startIcon:g?L(ao,{size:16}):null,sx:{mt:3,mb:2},children:g?"Logging in...":"Login"})]}):L(Ve,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>a(!0),sx:{mt:2},children:"Show Login Form"}),c&&L(Le,{severity:"error",sx:{mt:2},onClose:f,children:c})]})}function fa(){let{isAuthenticated:e,isLoading:o,isExpiringSoon:r,expiresIn:t}=ne();return o?re(Pe,{sx:{display:"flex",alignItems:"center",gap:1},children:[L(ao,{size:16}),L(le,{variant:"caption",children:"Loading session..."})]}):e?re(Pe,{children:[L(le,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),r&&re(le,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(t/1e3/60)," min"]})]}):L(le,{variant:"caption",color:"text.secondary",children:"Not logged in"})}import Yt from"@mui/material/TextField";import Jt from"@mui/material/CircularProgress";import or from"@mui/material/InputAdornment";import Qt from"@mui/material/IconButton";import Xt from"@mui/icons-material/Refresh";import{jsx as ce}from"react/jsx-runtime";var Zt=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),en=({html:e})=>ce("span",{dangerouslySetInnerHTML:{__html:Zt(e)}}),xa=({config:e,value:o,onChange:r,label:t,error:l=!1,helperText:a,readOnly:i=!1,disabled:g=!1})=>{let{value:c,loading:h,error:d,regenerate:w}=fo(e,{autoFetch:!o,onSuccess:T=>{r?.(T)}}),f=o||c,n=l||!!d,s=d||a,p=n&&s&&(s.toLowerCase().includes("duplicate")||s.toLowerCase().includes("duplicado")||s.toLowerCase().includes("duplicada")||s.toLowerCase().includes("unique")||s.toLowerCase().includes("\xFAnico")||s.toLowerCase().includes("unico")||s.toLowerCase().includes("\xFAnica")||s.toLowerCase().includes("unica")||s.toLowerCase().includes("already exists")||s.toLowerCase().includes("ya existe")||s.toLowerCase().includes("e11000"));return ce(Yt,{label:t,fullWidth:!0,value:f,error:n,helperText:s?ce(en,{html:s}):" ",disabled:g,InputProps:{readOnly:!0,startAdornment:h?ce(or,{position:"start",children:ce(Jt,{size:20})}):void 0,endAdornment:p&&!h?ce(or,{position:"end",children:ce(Qt,{edge:"end",onClick:async()=>{!g&&!h&&await w()},disabled:g,size:"small",color:"error","aria-label":"regenerar c\xF3digo",title:"Regenerar c\xF3digo",children:ce(Xt,{})})}):void 0}})};export{oe as a,on as b,rn as c,Me as d,ke as e,gn as f,bo as g,Cs as h,pt as i,Ko as j,Go as k,sa as l,ga as m,fa as n,xa as o};
@@ -1 +1 @@
1
- import{a as D,b as J,f as N,g as q,h as Z,i as Q}from"./chunk-5JKS55SE.mjs";import{createContext as ge,useContext as pe,useEffect as ye,useState as U}from"react";import z from"@nocios/crudify-browser";var Y=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){console.error("[CredentialsEventBus] Error in listener:",t)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},ee=Y.getInstance();import{jsx as he}from"react/jsx-runtime";var ie=ge(void 0),te=({config:r,children:i})=>{let[e,t]=U(!0),[o,c]=U(null),[y,h]=U(!1),[x,m]=U(""),[I,u]=U();ye(()=>{if(!r.publicApiKey){c("No publicApiKey provided"),t(!1),h(!1);return}let a=`${r.publicApiKey}-${r.env}`;if(a===x&&y){t(!1);return}(async()=>{t(!0),c(null),h(!1);try{z.config(r.env||"prod");let d=await z.init(r.publicApiKey,"none");if(u(d),typeof z.transaction=="function"&&typeof z.login=="function")h(!0),m(a),d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&ee.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(d){let g=d instanceof Error?d.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",d),c(g),h(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,x,y]);let s={crudify:y?z:null,isLoading:e,error:o,isInitialized:y,adminCredentials:I};return he(ie.Provider,{value:s,children:i})},re=()=>{let r=pe(ie);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import F from"crypto-js";var l=class l{static setStorageType(i){l.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return F.SHA256(i).toString()}static getEncryptionKey(){if(l.encryptionKey)return l.encryptionKey;let i=window.localStorage;if(!i)return l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey;try{let e=i.getItem(l.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=l.generateEncryptionKey(),i.setItem(l.ENCRYPTION_KEY_STORAGE,e)),l.encryptionKey=e,e}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch{return!1}}static getStorage(){return l.storageType==="none"?null:l.isStorageAvailable(l.storageType)?window[l.storageType]:(console.warn(`Crudify: ${l.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=l.getEncryptionKey();return F.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=l.getEncryptionKey();return F.AES.decrypt(i,e).toString(F.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",e),i}}static saveTokens(i){let e=l.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},o=l.encrypt(JSON.stringify(t));e.setItem(l.TOKEN_KEY,o),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let i=l.getStorage();if(!i)return null;try{let e=i.getItem(l.TOKEN_KEY);if(!e)return null;let t=l.decrypt(e),o=JSON.parse(t);return!o.accessToken||!o.refreshToken||!o.expiresAt||!o.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),l.clearTokens(),null):Date.now()>=o.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),l.clearTokens(),null):{accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),l.clearTokens(),null}}static clearTokens(){let i=l.getStorage();if(i)try{i.removeItem(l.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{l.clearTokens(),l.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(l.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",i)}}static hasValidTokens(){return l.getTokens()!==null}static getExpirationInfo(){let i=l.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=l.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}l.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===l.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let o=l.getTokens();i(o)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};l.TOKEN_KEY="crudify_tokens",l.ENCRYPTION_KEY_STORAGE="crudify_enc_key",l.encryptionKey=null,l.storageType="localStorage";var p=l;import b from"@nocios/crudify-browser";var M=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(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},p.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),b.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),N.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=p.getTokens();e?p.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):p.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(i,e){try{let t=await b.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let o=p.getTokens(),c={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:o?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:o?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return p.saveTokens(c),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(c),{success:!0,tokens:c,data:t.data}}catch(t){return console.error("[SessionManager] Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await b.logout(),p.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),p.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=p.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),p.clearTokens(),!1;if(b.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),b.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let o=p.getTokens();return o&&this.config.onSessionRestored?.(o),!0}return p.clearTokens(),await b.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(i),!0}catch(i){return this.log("Session restore error:",i),p.clearTokens(),await b.logout(),!1}}isAuthenticated(){return b.isLogin()||p.hasValidTokens()}getTokenInfo(){let i=b.getTokenData(),e=p.getExpirationInfo(),t=p.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:p.hasValidTokens(),apiEndpointAdmin:t?.apiEndpointAdmin,apiKeyEndpointAdmin:t?.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 i=await b.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),p.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return p.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),p.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){b.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);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"),N.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(p.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),N.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"),N.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=b.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";b.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",c=await b.init(t,o);if(c&&c.success===!1&&c.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(c.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw console.error("[SessionManager] Failed to initialize crudify:",i),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(o=>o.errorType==="Unauthorized"||o.message?.includes("Unauthorized")||o.message?.includes("Not Authorized")||o.message?.includes("NOT_AUTHORIZED")||o.message?.includes("Token")||o.message?.includes("TOKEN")||o.message?.includes("Authentication")||o.message?.includes("UNAUTHENTICATED")||o.extensions?.code==="UNAUTHENTICATED"||o.extensions?.code==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(t.message?.includes("TOKEN")||t.message?.includes("Token"))&&(e.isTokenExpired=!0),t.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let o=Object.values(i.errors).flat().find(c=>typeof c=="string"&&(c.includes("NOT_AUTHORIZED")||c.includes("TOKEN_REFRESH_FAILED")||c.includes("TOKEN_HAS_EXPIRED")||c.includes("PLEASE_LOGIN")||c.includes("Unauthorized")||c.includes("UNAUTHENTICATED")||c.includes("SESSION_EXPIRED")||c.includes("INVALID_TOKEN")));o&&typeof o=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,o.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."):o.includes("TOKEN_HAS_EXPIRED")||o.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):o.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&&i.data?.response?.status){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.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&&i.data?.response?.data)try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.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&&i.errorCode){let t=i.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="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 i=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){p.clearTokens(),b.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?J("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as me,useEffect as H,useCallback as P}from"react";function ne(r={}){let[i,e]=me({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=M.getInstance(),o=P(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 u={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(d=>({...d,isAuthenticated:!0,tokens:n,error:null})),r.onSessionRestored?.(n)},onLoginSuccess:n=>{e(d=>({...d,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:",u),await t.initialize(u),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let s=t.isAuthenticated(),a=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",s),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",a),e(n=>({...n,isAuthenticated:s,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(u){let s=u instanceof Error?u.message:"Initialization failed";e(a=>({...a,isLoading:!1,isInitialized:!0,error:s}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),c=P(async(u,s)=>{e(a=>({...a,isLoading:!0,error:null}));try{let a=await t.login(u,s);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",d=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(g=>({...g,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:n})),{success:!1,error:n}}},[t]),y=P(async()=>{e(u=>({...u,isLoading:!0}));try{await t.logout(),e(u=>({...u,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(u){e(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:u instanceof Error?u.message:"Logout error"}))}},[t]),h=P(async()=>{try{let u=await t.refreshTokens();if(u){let s=t.getTokenInfo();e(a=>({...a,tokens:s.crudifyTokens.accessToken?{accessToken:s.crudifyTokens.accessToken,refreshToken:s.crudifyTokens.refreshToken,expiresAt:s.crudifyTokens.expiresAt,refreshExpiresAt:s.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(s=>({...s,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return u}catch(u){return e(s=>({...s,isAuthenticated:!1,tokens:null,error:u instanceof Error?u.message:"Token refresh failed"})),!1}},[t]),x=P(()=>{e(u=>({...u,error:null}))},[]),m=P(()=>t.getTokenInfo(),[t]);H(()=>{o()},[o]),H(()=>{if(!i.isAuthenticated||!i.tokens)return;let u=q.getInstance(),s=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},a=u.subscribe(s);window.addEventListener("popstate",s);let n=()=>{let A=t.getTokenInfo().crudifyTokens.expiresIn||0;return A<300*1e3?30*1e3:A<1800*1e3?60*1e3:120*1e3},d,g=()=>{let T=n();d=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),g();return}let A=t.getTokenInfo(),E=A.crudifyTokens.expiresIn||0,S=(A.crudifyTokens.expiresAt||0)-(Date.now()-E),f=S*.5;if(E>0&&E<=f){let O=Math.round(E/S*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${O}% of TTL (${Math.round(E/6e4)}min remaining), refreshing...`),e(C=>({...C,isLoading:!0})),await t.refreshTokens()){let C=t.getTokenInfo();e(fe=>({...fe,isLoading:!1,tokens:C.crudifyTokens.accessToken?{accessToken:C.crudifyTokens.accessToken,refreshToken:C.crudifyTokens.refreshToken,expiresAt:C.crudifyTokens.expiresAt,refreshExpiresAt:C.crudifyTokens.refreshExpiresAt}:null}))}else e(C=>({...C,isLoading:!1,isAuthenticated:!1,tokens:null}))}let w=t.getTimeSinceLastActivity(),L=1800*1e3;w>L?(r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout (30min) - logging out"),await y()):g()},T)};return g(),()=>{clearTimeout(d),window.removeEventListener("popstate",s),a()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,y]),H(()=>{let u=N.subscribe(async s=>{if(r.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${s.type}`),s.type==="TOKEN_EXPIRED"){if(t.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 t.refreshTokens()){r.enableLogging&&console.log("\u2705 Token refreshed successfully");let n=t.getTokenInfo();e(d=>({...d,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"),N.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),N.emit("SESSION_EXPIRED",{message:a instanceof Error?a.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(s.type==="SESSION_EXPIRED"||s.type==="TOKEN_REFRESH_FAILED")&&(r.enableLogging&&console.log(`\u{1F534} Session expired (${s.type}), logging out...`),e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:s.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>u()},[r.enableLogging,r.onSessionExpired,t]),H(()=>{let u=p.subscribeToChanges(s=>{s?(r.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(a=>({...a,tokens:s,isAuthenticated:!0}))):(r.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(a=>({...a,isAuthenticated:!1,tokens:null})),N.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>u()},[r.enableLogging]);let I=P(()=>{t.updateLastActivity()},[t]);return{...i,login:c,logout:y,refreshTokens:h,clearError:x,getTokenInfo:m,updateActivity:I,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}import{useState as oe,createContext as Ee,useContext as Te,useCallback as G,useEffect as ve}from"react";import{Snackbar as ke,Alert as Ae,Box as be,Portal as xe}from"@mui/material";import{v4 as Se}from"uuid";import Ie from"dompurify";import{jsx as K,jsxs as Ce}from"react/jsx-runtime";var se=Ee(null),Ne=r=>Ie.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}),$=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:c=!1})=>{let[y,h]=oe([]),x=G((s,a="info",n)=>{if(!o)return"";if(!s||typeof s!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";s.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),s=s.substring(0,1e3)+"...");let d=Se(),g={id:d,message:s,severity:a,autoHideDuration:n?.autoHideDuration??e,persistent:n?.persistent??!1,allowHtml:n?.allowHtml??c};return h(T=>[...T.length>=i?T.slice(-(i-1)):T,g]),d},[i,e,o,c]),m=G(s=>{h(a=>a.filter(n=>n.id!==s))},[]),I=G(()=>{h([])},[]),u={showNotification:x,hideNotification:m,clearAllNotifications:I};return Ce(se.Provider,{value:u,children:[r,o&&K(xe,{children:K(be,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:y.map(s=>K(Re,{notification:s,onClose:()=>m(s.id)},s.id))})})]})},Re=({notification:r,onClose:i})=>{let[e,t]=oe(!0),o=G((c,y)=>{y!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return ve(()=>{if(!r.persistent&&r.autoHideDuration){let c=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(c)}},[r.autoHideDuration,r.persistent,o]),K(ke,{open:e,onClose:o,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:K(Ae,{variant:"filled",severity:r.severity,onClose:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?K("span",{dangerouslySetInnerHTML:{__html:Ne(r.message)}}):K("span",{children:r.message})})})},ae=()=>{let r=Te(se);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import Le,{createContext as De,useContext as we,useMemo as B}from"react";import{Fragment as Ke,jsx as k,jsxs as R}from"react/jsx-runtime";var ce=De(void 0);function le({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let c;try{let{showNotification:n}=ae();c=n}catch{}let y={};try{let n=re();n.isInitialized&&n.adminCredentials&&(y=n.adminCredentials)}catch{}let h=B(()=>{let n,d;if(e?.publicApiKey&&(n=e.publicApiKey),e?.env&&(d=e.env),!n){let g=D("publicApiKey"),T=D("environment");g&&(n=g),T&&["dev","stg","prod"].includes(T)&&(d=T)}return{publicApiKey:n,env:d||"stg"}},[e]),x=Le.useMemo(()=>({...i,showNotification:c,apiEndpointAdmin:y.apiEndpointAdmin,apiKeyEndpointAdmin:y.apiKeyEndpointAdmin,publicApiKey:h.publicApiKey,env:h.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,c,y.apiEndpointAdmin,y.apiKeyEndpointAdmin,h]),m=ne(x),I=B(()=>{let n,d,g,T,A,E="unknown";if(e?.publicApiKey&&(n=e.publicApiKey,E="props"),e?.env&&(d=e.env),e?.appName&&(g=e.appName),e?.loginActions&&(T=e.loginActions),e?.logo&&(A=e.logo),!n){let v=D("publicApiKey"),S=D("environment"),f=D("appName"),w=D("loginActions"),L=D("logo");v&&(n=v,E="cookies"),S&&["dev","stg","prod"].includes(S)&&(d=S),f&&(g=decodeURIComponent(f)),w&&(T=decodeURIComponent(w).split(",").map(W=>W.trim()).filter(Boolean)),L&&(A=decodeURIComponent(L))}return{publicApiKey:n,env:d,appName:g,loginActions:T,logo:A}},[e]),u=B(()=>{if(!m.tokens?.accessToken||!m.isAuthenticated)return null;try{let n=Z(m.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let d={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(g=>{["sub","email","subscriber"].includes(g)||(d[g]=n[g])}),d}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[m.tokens?.accessToken,m.isAuthenticated]),s={...m,sessionData:u,config:I},a={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return k(ce.Provider,{value:s,children:r})}function Ii(r){let i={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?k(te,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:k($,{...i,children:k(le,{...r})})}):k($,{...i,children:k(le,{...r})})}function Pe(){let r=we(ce);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Ni(){let r=Pe();return r.isInitialized?R("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[k("h4",{children:"Session Debug Info"}),R("div",{children:[k("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),R("div",{children:[k("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),R("div",{children:[k("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&R(Ke,{children:[R("div",{children:[k("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),R("div",{children:[k("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),R("div",{children:[k("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),R("div",{children:[k("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),R("div",{children:[k("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):k("div",{children:"Session not initialized"})}import{useState as _,useEffect as ue,useCallback as de,useRef as V}from"react";import Oe from"@nocios/crudify-browser";var Pi=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,c]=_(null),[y,h]=_(!1),[x,m]=_(null),[I,u]=_({}),s=V(null),a=V(!0),n=V(0),d=V(0),g=de(()=>{c(null),m(null),h(!1),u({})},[]),T=de(async()=>{let A=Q();if(!A){a.current&&(m("No user email available"),h(!1));return}s.current&&s.current.abort();let E=new AbortController;s.current=E;let v=++n.current;try{a.current&&(h(!0),m(null));let S=await Oe.readItems("users",{filter:{email:A},pagination:{limit:1}});if(v===n.current&&a.current&&!E.signal.aborted)if(S.success&&S.data&&S.data.length>0){let f=S.data[0];c(f);let w={fullProfile:f,totalFields:Object.keys(f).length,displayData:{id:f.id,email:f.email,username:f.username,firstName:f.firstName,lastName:f.lastName,fullName:f.fullName||`${f.firstName||""} ${f.lastName||""}`.trim(),role:f.role,permissions:f.permissions||[],isActive:f.isActive,lastLogin:f.lastLogin,createdAt:f.createdAt,updatedAt:f.updatedAt,...Object.keys(f).filter(L=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(L)).reduce((L,O)=>({...L,[O]:f[O]}),{})}};u(w),m(null),d.current=0}else m("User profile not found"),c(null),u({})}catch(S){if(v===n.current&&a.current){let f=S;if(f.name==="AbortError")return;e&&d.current<t&&(f.message?.includes("Network Error")||f.message?.includes("Failed to fetch"))?(d.current++,setTimeout(()=>{a.current&&T()},1e3*d.current)):(m("Failed to load user profile"),c(null),u({}))}}finally{v===n.current&&a.current&&h(!1),s.current===E&&(s.current=null)}},[e,t]);return ue(()=>{i&&T()},[i,T]),ue(()=>(a.current=!0,()=>{a.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:o,loading:y,error:x,extendedData:I,refreshProfile:T,clearProfile:g}};import{useState as j,useEffect as Ue,useCallback as X,useRef as ze}from"react";import Fe from"@nocios/crudify-browser";var zi=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:c,padding:y=0,separator:h=""}=r,[x,m]=j(""),[I,u]=j(!1),[s,a]=j(null),n=ze(!1),d=X(E=>{let v=String(E).padStart(y,"0");return`${c}${h}${v}`},[c,y,h]),g=X(async()=>{u(!0),a(null);try{let E=await Fe.getNextSequence(c);if(E.success&&E.data?.value){let v=d(E.data.value);m(v),t?.(v)}else{let v=E.errors?._error?.[0]||"Failed to generate code";a(v),o?.(v)}}catch(E){let v=E instanceof Error?E.message:"Unknown error";a(v),o?.(v)}finally{u(!1)}},[c,d,t,o]),T=X(async()=>{await g()},[g]),A=X(()=>{a(null)},[]);return Ue(()=>{e&&!x&&!n.current&&(n.current=!0,g())},[e,x,g]),{value:x,loading:I,error:s,regenerate:T,clearError:A}};export{ee as a,te as b,re as c,p as d,M as e,ne as f,$ as g,ae as h,Ii as i,Pe as j,Ni as k,Pi as l,zi as m};
1
+ import{a as D,b as J,f as N,g as q,h as Z,i as Q}from"./chunk-5JKS55SE.mjs";import{createContext as ge,useContext as pe,useEffect as ye,useState as U}from"react";import z from"@nocios/crudify-browser";var Y=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){console.error("[CredentialsEventBus] Error in listener:",t)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},ee=Y.getInstance();import{jsx as he}from"react/jsx-runtime";var ie=ge(void 0),te=({config:r,children:i})=>{let[e,t]=U(!0),[o,c]=U(null),[y,h]=U(!1),[x,m]=U(""),[I,u]=U();ye(()=>{if(!r.publicApiKey){c("No publicApiKey provided"),t(!1),h(!1);return}let a=`${r.publicApiKey}-${r.env}`;if(a===x&&y){t(!1);return}(async()=>{t(!0),c(null),h(!1);try{z.config(r.env||"prod");let d=await z.init(r.publicApiKey,"none");if(u(d),typeof z.transaction=="function"&&typeof z.login=="function")h(!0),m(a),d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&ee.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(d){let g=d instanceof Error?d.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",d),c(g),h(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,x,y]);let s={crudify:y?z:null,isLoading:e,error:o,isInitialized:y,adminCredentials:I};return he(ie.Provider,{value:s,children:i})},re=()=>{let r=pe(ie);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import F from"crypto-js";var l=class l{static setStorageType(i){l.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return F.SHA256(i).toString()}static getEncryptionKey(){if(l.encryptionKey)return l.encryptionKey;let i=window.localStorage;if(!i)return l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey;try{let e=i.getItem(l.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=l.generateEncryptionKey(),i.setItem(l.ENCRYPTION_KEY_STORAGE,e)),l.encryptionKey=e,e}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch{return!1}}static getStorage(){return l.storageType==="none"?null:l.isStorageAvailable(l.storageType)?window[l.storageType]:(console.warn(`Crudify: ${l.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=l.getEncryptionKey();return F.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=l.getEncryptionKey();return F.AES.decrypt(i,e).toString(F.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",e),i}}static saveTokens(i){let e=l.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},o=l.encrypt(JSON.stringify(t));e.setItem(l.TOKEN_KEY,o),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let i=l.getStorage();if(!i)return null;try{let e=i.getItem(l.TOKEN_KEY);if(!e)return null;let t=l.decrypt(e),o=JSON.parse(t);return!o.accessToken||!o.refreshToken||!o.expiresAt||!o.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),l.clearTokens(),null):Date.now()>=o.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),l.clearTokens(),null):{accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),l.clearTokens(),null}}static clearTokens(){let i=l.getStorage();if(i)try{i.removeItem(l.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{l.clearTokens(),l.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(l.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",i)}}static hasValidTokens(){return l.getTokens()!==null}static getExpirationInfo(){let i=l.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=l.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}l.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===l.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let o=l.getTokens();i(o)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};l.TOKEN_KEY="crudify_tokens",l.ENCRYPTION_KEY_STORAGE="crudify_enc_key",l.encryptionKey=null,l.storageType="localStorage";var p=l;import b from"@nocios/crudify-browser";var M=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(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},p.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),b.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),N.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=p.getTokens();e?p.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):p.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(i,e){try{let t=await b.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let o=p.getTokens(),c={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:o?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:o?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return p.saveTokens(c),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(c),{success:!0,tokens:c,data:t.data}}catch(t){return console.error("[SessionManager] Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await b.logout(),p.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),p.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=p.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),p.clearTokens(),!1;if(b.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),b.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let o=p.getTokens();return o&&this.config.onSessionRestored?.(o),!0}return p.clearTokens(),await b.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(i),!0}catch(i){return this.log("Session restore error:",i),p.clearTokens(),await b.logout(),!1}}isAuthenticated(){return b.isLogin()||p.hasValidTokens()}getTokenInfo(){let i=b.getTokenData(),e=p.getExpirationInfo(),t=p.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:p.hasValidTokens(),apiEndpointAdmin:t?.apiEndpointAdmin,apiKeyEndpointAdmin:t?.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 i=await b.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),p.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return p.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),p.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){b.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);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"),N.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(p.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),N.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"),N.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=b.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";b.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",c=await b.init(t,o);if(c&&c.success===!1&&c.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(c.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw console.error("[SessionManager] Failed to initialize crudify:",i),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(o=>o.errorType==="Unauthorized"||o.message?.includes("Unauthorized")||o.message?.includes("Not Authorized")||o.message?.includes("NOT_AUTHORIZED")||o.message?.includes("Token")||o.message?.includes("TOKEN")||o.message?.includes("Authentication")||o.message?.includes("UNAUTHENTICATED")||o.extensions?.code==="UNAUTHENTICATED"||o.extensions?.code==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(t.message?.includes("TOKEN")||t.message?.includes("Token"))&&(e.isTokenExpired=!0),t.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let o=Object.values(i.errors).flat().find(c=>typeof c=="string"&&(c.includes("NOT_AUTHORIZED")||c.includes("TOKEN_REFRESH_FAILED")||c.includes("TOKEN_HAS_EXPIRED")||c.includes("PLEASE_LOGIN")||c.includes("Unauthorized")||c.includes("UNAUTHENTICATED")||c.includes("SESSION_EXPIRED")||c.includes("INVALID_TOKEN")));o&&typeof o=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,o.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."):o.includes("TOKEN_HAS_EXPIRED")||o.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):o.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&&i.data?.response?.status){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.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&&i.data?.response?.data)try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.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&&i.errorCode){let t=i.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="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 i=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){p.clearTokens(),b.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?J("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as me,useEffect as H,useCallback as P}from"react";function ne(r={}){let[i,e]=me({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=M.getInstance(),o=P(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 u={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(d=>({...d,isAuthenticated:!0,tokens:n,error:null})),r.onSessionRestored?.(n)},onLoginSuccess:n=>{e(d=>({...d,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:",u),await t.initialize(u),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let s=t.isAuthenticated(),a=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",s),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",a),e(n=>({...n,isAuthenticated:s,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(u){let s=u instanceof Error?u.message:"Initialization failed";e(a=>({...a,isLoading:!1,isInitialized:!0,error:s}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),c=P(async(u,s)=>{e(a=>({...a,isLoading:!0,error:null}));try{let a=await t.login(u,s);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",d=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(g=>({...g,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:n})),{success:!1,error:n}}},[t]),y=P(async()=>{e(u=>({...u,isLoading:!0}));try{await t.logout(),e(u=>({...u,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(u){e(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:u instanceof Error?u.message:"Logout error"}))}},[t]),h=P(async()=>{try{let u=await t.refreshTokens();if(u){let s=t.getTokenInfo();e(a=>({...a,tokens:s.crudifyTokens.accessToken?{accessToken:s.crudifyTokens.accessToken,refreshToken:s.crudifyTokens.refreshToken,expiresAt:s.crudifyTokens.expiresAt,refreshExpiresAt:s.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(s=>({...s,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return u}catch(u){return e(s=>({...s,isAuthenticated:!1,tokens:null,error:u instanceof Error?u.message:"Token refresh failed"})),!1}},[t]),x=P(()=>{e(u=>({...u,error:null}))},[]),m=P(()=>t.getTokenInfo(),[t]);H(()=>{o()},[o]),H(()=>{if(!i.isAuthenticated||!i.tokens)return;let u=q.getInstance(),s=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},a=u.subscribe(s);window.addEventListener("popstate",s);let n=()=>{let A=t.getTokenInfo().crudifyTokens.expiresIn||0;return A<300*1e3?30*1e3:A<1800*1e3?60*1e3:120*1e3},d,g=()=>{let T=n();d=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),g();return}let A=t.getTokenInfo(),E=A.crudifyTokens.expiresIn||0,S=(A.crudifyTokens.expiresAt||0)-(Date.now()-E),f=S*.5;if(E>0&&E<=f){let O=Math.round(E/S*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${O}% of TTL (${Math.round(E/6e4)}min remaining), refreshing...`),e(C=>({...C,isLoading:!0})),await t.refreshTokens()){let C=t.getTokenInfo();e(fe=>({...fe,isLoading:!1,tokens:C.crudifyTokens.accessToken?{accessToken:C.crudifyTokens.accessToken,refreshToken:C.crudifyTokens.refreshToken,expiresAt:C.crudifyTokens.expiresAt,refreshExpiresAt:C.crudifyTokens.refreshExpiresAt}:null}))}else e(C=>({...C,isLoading:!1,isAuthenticated:!1,tokens:null}))}let w=t.getTimeSinceLastActivity(),L=1800*1e3;w>L?(r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout (30min) - logging out"),await y()):g()},T)};return g(),()=>{clearTimeout(d),window.removeEventListener("popstate",s),a()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,y]),H(()=>{let u=N.subscribe(async s=>{if(r.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${s.type}`),s.type==="TOKEN_EXPIRED"){if(t.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 t.refreshTokens()){r.enableLogging&&console.log("\u2705 Token refreshed successfully");let n=t.getTokenInfo();e(d=>({...d,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"),N.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),N.emit("SESSION_EXPIRED",{message:a instanceof Error?a.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(s.type==="SESSION_EXPIRED"||s.type==="TOKEN_REFRESH_FAILED")&&(r.enableLogging&&console.log(`\u{1F534} Session expired (${s.type}), logging out...`),e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:s.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>u()},[r.enableLogging,r.onSessionExpired,t]),H(()=>{let u=p.subscribeToChanges(s=>{s?(r.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(a=>({...a,tokens:s,isAuthenticated:!0}))):(r.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(a=>({...a,isAuthenticated:!1,tokens:null})),N.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>u()},[r.enableLogging]);let I=P(()=>{t.updateLastActivity()},[t]);return{...i,login:c,logout:y,refreshTokens:h,clearError:x,getTokenInfo:m,updateActivity:I,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}import{useState as oe,createContext as Ee,useContext as Te,useCallback as G,useEffect as ve}from"react";import{Snackbar as ke,Alert as Ae,Box as be,Portal as xe}from"@mui/material";import{v4 as Se}from"uuid";import Ie from"dompurify";import{jsx as K,jsxs as Ce}from"react/jsx-runtime";var se=Ee(null),Ne=r=>Ie.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}),$=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:c=!1})=>{let[y,h]=oe([]),x=G((s,a="info",n)=>{if(!o)return"";if(!s||typeof s!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";s.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),s=s.substring(0,1e3)+"...");let d=Se(),g={id:d,message:s,severity:a,autoHideDuration:n?.autoHideDuration??e,persistent:n?.persistent??!1,allowHtml:n?.allowHtml??c};return h(T=>[...T.length>=i?T.slice(-(i-1)):T,g]),d},[i,e,o,c]),m=G(s=>{h(a=>a.filter(n=>n.id!==s))},[]),I=G(()=>{h([])},[]),u={showNotification:x,hideNotification:m,clearAllNotifications:I};return Ce(se.Provider,{value:u,children:[r,o&&K(xe,{children:K(be,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:y.map(s=>K(Re,{notification:s,onClose:()=>m(s.id)},s.id))})})]})},Re=({notification:r,onClose:i})=>{let[e,t]=oe(!0),o=G((c,y)=>{y!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return ve(()=>{if(!r.persistent&&r.autoHideDuration){let c=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(c)}},[r.autoHideDuration,r.persistent,o]),K(ke,{open:e,onClose:o,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:K(Ae,{variant:"filled",severity:r.severity,onClose:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?K("span",{dangerouslySetInnerHTML:{__html:Ne(r.message)}}):K("span",{children:r.message})})})},ae=()=>{let r=Te(se);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import Le,{createContext as De,useContext as we,useMemo as B}from"react";import{Fragment as Ke,jsx as k,jsxs as R}from"react/jsx-runtime";var ce=De(void 0);function le({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let c;try{let{showNotification:n}=ae();c=n}catch{}let y={};try{let n=re();n.isInitialized&&n.adminCredentials&&(y=n.adminCredentials)}catch{}let h=B(()=>{let n,d;if(e?.publicApiKey&&(n=e.publicApiKey),e?.env&&(d=e.env),!n){let g=D("publicApiKey"),T=D("environment");g&&(n=g),T&&["dev","stg","prod"].includes(T)&&(d=T)}return{publicApiKey:n,env:d||"prod"}},[e]),x=Le.useMemo(()=>({...i,showNotification:c,apiEndpointAdmin:y.apiEndpointAdmin,apiKeyEndpointAdmin:y.apiKeyEndpointAdmin,publicApiKey:h.publicApiKey,env:h.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,c,y.apiEndpointAdmin,y.apiKeyEndpointAdmin,h]),m=ne(x),I=B(()=>{let n,d,g,T,A,E="unknown";if(e?.publicApiKey&&(n=e.publicApiKey,E="props"),e?.env&&(d=e.env),e?.appName&&(g=e.appName),e?.loginActions&&(T=e.loginActions),e?.logo&&(A=e.logo),!n){let v=D("publicApiKey"),S=D("environment"),f=D("appName"),w=D("loginActions"),L=D("logo");v&&(n=v,E="cookies"),S&&["dev","stg","prod"].includes(S)&&(d=S),f&&(g=decodeURIComponent(f)),w&&(T=decodeURIComponent(w).split(",").map(W=>W.trim()).filter(Boolean)),L&&(A=decodeURIComponent(L))}return{publicApiKey:n,env:d,appName:g,loginActions:T,logo:A}},[e]),u=B(()=>{if(!m.tokens?.accessToken||!m.isAuthenticated)return null;try{let n=Z(m.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let d={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(g=>{["sub","email","subscriber"].includes(g)||(d[g]=n[g])}),d}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[m.tokens?.accessToken,m.isAuthenticated]),s={...m,sessionData:u,config:I},a={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return k(ce.Provider,{value:s,children:r})}function Ii(r){let i={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?k(te,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:k($,{...i,children:k(le,{...r})})}):k($,{...i,children:k(le,{...r})})}function Pe(){let r=we(ce);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Ni(){let r=Pe();return r.isInitialized?R("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[k("h4",{children:"Session Debug Info"}),R("div",{children:[k("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),R("div",{children:[k("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),R("div",{children:[k("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&R(Ke,{children:[R("div",{children:[k("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),R("div",{children:[k("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),R("div",{children:[k("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),R("div",{children:[k("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),R("div",{children:[k("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):k("div",{children:"Session not initialized"})}import{useState as _,useEffect as ue,useCallback as de,useRef as V}from"react";import Oe from"@nocios/crudify-browser";var Pi=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,c]=_(null),[y,h]=_(!1),[x,m]=_(null),[I,u]=_({}),s=V(null),a=V(!0),n=V(0),d=V(0),g=de(()=>{c(null),m(null),h(!1),u({})},[]),T=de(async()=>{let A=Q();if(!A){a.current&&(m("No user email available"),h(!1));return}s.current&&s.current.abort();let E=new AbortController;s.current=E;let v=++n.current;try{a.current&&(h(!0),m(null));let S=await Oe.readItems("users",{filter:{email:A},pagination:{limit:1}});if(v===n.current&&a.current&&!E.signal.aborted)if(S.success&&S.data&&S.data.length>0){let f=S.data[0];c(f);let w={fullProfile:f,totalFields:Object.keys(f).length,displayData:{id:f.id,email:f.email,username:f.username,firstName:f.firstName,lastName:f.lastName,fullName:f.fullName||`${f.firstName||""} ${f.lastName||""}`.trim(),role:f.role,permissions:f.permissions||[],isActive:f.isActive,lastLogin:f.lastLogin,createdAt:f.createdAt,updatedAt:f.updatedAt,...Object.keys(f).filter(L=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(L)).reduce((L,O)=>({...L,[O]:f[O]}),{})}};u(w),m(null),d.current=0}else m("User profile not found"),c(null),u({})}catch(S){if(v===n.current&&a.current){let f=S;if(f.name==="AbortError")return;e&&d.current<t&&(f.message?.includes("Network Error")||f.message?.includes("Failed to fetch"))?(d.current++,setTimeout(()=>{a.current&&T()},1e3*d.current)):(m("Failed to load user profile"),c(null),u({}))}}finally{v===n.current&&a.current&&h(!1),s.current===E&&(s.current=null)}},[e,t]);return ue(()=>{i&&T()},[i,T]),ue(()=>(a.current=!0,()=>{a.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:o,loading:y,error:x,extendedData:I,refreshProfile:T,clearProfile:g}};import{useState as j,useEffect as Ue,useCallback as X,useRef as ze}from"react";import Fe from"@nocios/crudify-browser";var zi=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:c,padding:y=0,separator:h=""}=r,[x,m]=j(""),[I,u]=j(!1),[s,a]=j(null),n=ze(!1),d=X(E=>{let v=String(E).padStart(y,"0");return`${c}${h}${v}`},[c,y,h]),g=X(async()=>{u(!0),a(null);try{let E=await Fe.getNextSequence(c);if(E.success&&E.data?.value){let v=d(E.data.value);m(v),t?.(v)}else{let v=E.errors?._error?.[0]||"Failed to generate code";a(v),o?.(v)}}catch(E){let v=E instanceof Error?E.message:"Unknown error";a(v),o?.(v)}finally{u(!1)}},[c,d,t,o]),T=X(async()=>{await g()},[g]),A=X(()=>{a(null)},[]);return Ue(()=>{e&&!x&&!n.current&&(n.current=!0,g())},[e,x,g]),{value:x,loading:I,error:s,regenerate:T,clearError:A}};export{ee as a,te as b,re as c,p as d,M as e,ne as f,$ as g,ae as h,Ii as i,Pe as j,Ni as k,Pi as l,zi as m};