@nocios/crudify-ui 4.1.48 → 4.1.52

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{a as Yo,b as G,g as Qo,i as Q,k as Zo}from"./chunk-WLNRGFHL.mjs";import{g as z}from"./chunk-BJ6PIVZR.mjs";import{a as Jo,e as Xo}from"./chunk-5JKS55SE.mjs";import{Box as wr,Typography as Pr}from"@mui/material";import{createContext as Ne,useContext as Ve,useMemo as ee}from"react";import{useState as Bo,useEffect as Ue}from"react";var oe=(o,t)=>{let[a,i]=Bo({}),[f,n]=Bo(!1),[s,g]=Bo(null);return Ue(()=>{if(console.log("\u{1F527} [I18nProvider] Hybrid translation loading:",{hasProvidedTranslations:!!t&&Object.keys(t).length>0,hasUrl:!!o,providedKeys:t?Object.keys(t).length:0}),t&&Object.keys(t).length>0){console.log("\u2705 [I18nProvider] Using provided translations (highest priority)"),i(t),n(!1),g(null);return}if(!o){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),i({}),n(!1),g(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",o);let l=!1;return n(!0),g(null),fetch(o).then(y=>{if(!y.ok)throw new Error(`Failed to load translations: ${y.status}`);return y.json()}).then(y=>{l||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:o,keysLoaded:Object.keys(y).length}),i(y),n(!1))}).catch(y=>{l||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",o,y),g(y.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),i({}),n(!1))}),()=>{l=!0}},[o,t]),{translations:a,loading:f,error:s}};import{jsx as re}from"react/jsx-runtime";var te=Ne(null),Me=(o,t)=>o&&o[t]?o[t]:t.split(".").reduce((a,i)=>a&&typeof a=="object"?a[i]:void 0,o),ne=({children:o,translations:t,translationsUrl:a,language:i="en"})=>{let{translations:f,loading:n}=oe(a,t),s=ee(()=>(l,y)=>{let c=Me(f,l);return c==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${l}" - showing key as-is`),c=l),y&&typeof c=="string"&&Object.entries(y).forEach(([h,d])=>{c=c.replace(new RegExp(`{{${h}}}`,"g"),d)}),typeof c=="string"?c:l},[f]),g=ee(()=>({t:s,language:i}),[s,i]);return n?re("div",{children:"Loading translations..."}):re(te.Provider,{value:g,children:o})},V=()=>{let o=Ve(te);if(!o)throw new Error("useTranslation must be used within I18nProvider");return o};import{createContext as He,useContext as $e,useReducer as je,useEffect as se}from"react";import{jsx as Ge}from"react/jsx-runtime";var ae={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function qe(o,t){switch(t.type){case"SET_SCREEN":let a={...o,currentScreen:t.payload.screen,searchParams:t.payload.params||o.searchParams,errors:{global:[]}},i=new URLSearchParams(a.searchParams),f=i.toString()?`?${i.toString()}`:window.location.pathname;try{window.history.replaceState({},"",f)}catch{}return a;case"SET_SEARCH_PARAMS":return{...o,searchParams:t.payload};case"UPDATE_FORM_DATA":return{...o,formData:{...o.formData,...t.payload},errors:{...o.errors,...Object.keys(t.payload).reduce((n,s)=>({...n,[s]:void 0}),{})}};case"SET_LOADING":return{...o,loading:t.payload};case"SET_ERRORS":return{...o,errors:{...o.errors,...t.payload}};case"CLEAR_ERRORS":return{...o,errors:{global:[]}};case"SET_EMAIL_SENT":return{...o,emailSent:t.payload};case"SET_CODE_ALREADY_EXISTS":return{...o,codeAlreadyExists:t.payload};case"SET_CODE_VALIDATED":return{...o,codeValidated:t.payload};case"SET_FROM_CODE_VERIFICATION":return{...o,fromCodeVerification:t.payload};case"RESET_FORM":return{...o,formData:ae.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...o,config:t.payload};default:return o}}var ie=He(void 0),le=({children:o,initialScreen:t="login",config:a,autoReadFromCookies:i=!0})=>{let[f,n]=je(qe,{...ae,currentScreen:t});se(()=>{n({type:"INIT_CONFIG",payload:(()=>{let e={};if(i)try{let r=Jo("logo");if(r){let m=decodeURIComponent(r);m.startsWith("http")&&(e.logo=m)}}catch(r){console.error("Error reading configuration from cookies:",r)}return{publicApiKey:a?.publicApiKey,env:a?.env,appName:a?.appName,logo:a?.logo||e.logo,loginActions:a?.loginActions}})()})},[a,i]),se(()=>{let d=new URLSearchParams(window.location.search),e={};d.forEach((r,m)=>{e[m]=r}),Object.keys(e).length>0&&n({type:"SET_SEARCH_PARAMS",payload:e}),t==="checkCode"&&e.email&&n({type:"UPDATE_FORM_DATA",payload:{email:e.email,code:e.code||""}}),t==="resetPassword"&&e.link&&n({type:"SET_SEARCH_PARAMS",payload:e})},[t]);let h={state:f,dispatch:n,setScreen:(d,e)=>{n({type:"SET_SCREEN",payload:{screen:d,params:e}})},updateFormData:d=>{n({type:"UPDATE_FORM_DATA",payload:d})},setFieldError:(d,e)=>{n({type:"SET_ERRORS",payload:{[d]:e}})},clearErrors:()=>{n({type:"CLEAR_ERRORS"})},setLoading:d=>{n({type:"SET_LOADING",payload:d})}};return Ge(ie.Provider,{value:h,children:o})},vo=()=>{let o=$e(ie);if(o===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return o};import{useEffect as Ke,useRef as Ye}from"react";import{Typography as Fo,TextField as ce,Button as Je,Box as fo,CircularProgress as Xe,Alert as Qe,Link as de}from"@mui/material";import{Fragment as or,jsx as M,jsxs as po}from"react/jsx-runtime";var Ze=({onScreenChange:o,onExternalNavigate:t,onLoginSuccess:a,onError:i,redirectUrl:f="/"})=>{let{crudify:n}=G(),{state:s,updateFormData:g,setFieldError:l,clearErrors:y,setLoading:c}=vo(),{login:h}=Q(),d=V(),{t:e}=d,r=d.i18n,m=Ye(null),P=Xo(e,{currentLanguage:r?.language,enableDebug:!1}),C=()=>{if(s.searchParams.redirect)try{let p=decodeURIComponent(s.searchParams.redirect);if(p.startsWith("/")&&!p.startsWith("//"))return p}catch{}return f||"/"};Ke(()=>{let p=setTimeout(()=>{m.current&&m.current.focus()},100);return()=>clearTimeout(p)},[]);let u=p=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",p);let S=P.translateError({code:p.code,message:p.message,field:p.field});return console.log("\u{1F50D} [LoginForm] Translation result:",S),S},x=async()=>{if(!s.loading){if(!s.formData.username.trim()){l("username",e("login.usernameRequired"));return}if(!s.formData.password.trim()){l("password",e("login.passwordRequired"));return}y(),c(!0);try{let p=await h(s.formData.username,s.formData.password);if(c(!1),p.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let S=C();a&&a(p.data,S)}else{let S=p.rawResponse||p;w(S)}}catch(p){c(!1);let J=z(p).map(u);l("global",J),i&&i(J.join(", "))}}},w=p=>{z(p).forEach(J=>{if(J.field)l(J.field,u(J));else{let mo=s.errors.global||[];l("global",[...mo,u(J)])}})};return po(or,{children:[po(fo,{component:"form",noValidate:!0,onSubmit:p=>{p.preventDefault(),x()},onKeyDown:p=>{p.key==="Enter"&&!s.loading&&(p.preventDefault(),x())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[po(fo,{sx:{mb:1},children:[M(Fo,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:e("login.usernameOrEmailLabel")}),M(ce,{fullWidth:!0,id:"email",name:"email",type:"email",value:s.formData.username,disabled:s.loading,onChange:p=>g({username:p.target.value}),error:!!s.errors.username,helperText:s.errors.username,autoComplete:"email",placeholder:e("login.usernameOrEmailPlaceholder"),inputRef:m,required:!0})]}),po(fo,{sx:{mb:1},children:[M(Fo,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:e("login.passwordLabel")}),M(ce,{fullWidth:!0,id:"password",name:"password",type:"password",value:s.formData.password,disabled:s.loading,onChange:p=>g({password:p.target.value}),error:!!s.errors.password,helperText:s.errors.password,autoComplete:"current-password",placeholder:e("login.passwordPlaceholder"),required:!0})]}),s.config.loginActions?.includes("forgotPassword")&&M(fo,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:M(de,{sx:{cursor:"pointer"},onClick:()=>{o?.("forgotPassword",s.searchParams)},variant:"body2",color:"secondary",children:e("login.forgotPasswordLink")})}),M(Je,{disabled:s.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:s.loading?M(Xe,{size:20}):e("login.loginButton")})]}),M(fo,{children:s.errors.global&&s.errors.global.length>0&&s.errors.global.map((p,S)=>M(Qe,{variant:"filled",sx:{mt:2},severity:"error",children:M("div",{children:p})},S))}),s.config.loginActions?.includes("createUser")&&po(Fo,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[e("login.noAccountPrompt")," ",M(de,{sx:{cursor:"pointer"},onClick:()=>{let S=`/public/users/create${Object.keys(s.searchParams).length>0?`?${new URLSearchParams(s.searchParams).toString()}`:""}`;t?.(S)},fontWeight:"medium",color:"secondary",children:e("login.signUpLink")})]})]})},me=Ze;import{useState as so}from"react";import{Typography as ao,TextField as er,Button as ue,Box as Z,CircularProgress as rr,Alert as tr,Link as Do}from"@mui/material";import{Fragment as fe,jsx as B,jsxs as to}from"react/jsx-runtime";var nr=({onScreenChange:o,onError:t})=>{let{crudify:a}=G(),[i,f]=so(""),[n,s]=so(!1),[g,l]=so([]),[y,c]=so(null),[h,d]=so(!1),[e,r]=so(!1),{t:m}=V(),P=v=>{let E=[`errors.auth.${v.code}`,`errors.data.${v.code}`,`errors.system.${v.code}`,`errors.${v.code}`,`forgotPassword.${v.code.toLowerCase()}`];for(let p of E){let S=m(p);if(S!==p)return S}return v.message||m("error.unknown")},C=v=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),u=async()=>{if(!(n||!a)){if(l([]),c(null),!i){c(m("forgotPassword.emailRequired"));return}if(!C(i)){c(m("forgotPassword.invalidEmail"));return}s(!0);try{let v=[{operation:"requestPasswordReset",data:{email:i}}],E=await a.transaction(v);if(E.success)E.data&&E.data.existingCodeValid?r(!0):d(!0);else{let S=z(E).map(P);l(S)}}catch(v){let p=z(v).map(P);l(p),t&&t(p.join(", "))}finally{s(!1)}}},x=()=>{o?.("login")},w=()=>{if(h||e){o?.("checkCode",{email:i});return}if(!i){c(m("forgotPassword.emailRequired"));return}if(!C(i)){c(m("forgotPassword.invalidEmail"));return}o?.("checkCode",{email:i})};return h||e?B(fe,{children:to(Z,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[to(Z,{sx:{mb:2},children:[B(ao,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:m(e?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),B(ao,{variant:"body2",sx:{color:e?"success.main":"grey.600"},children:m("forgotPassword.checkEmailInstructions")})]}),B(ue,{type:"button",onClick:w,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:m("forgotPassword.enterCodeLink")}),B(Z,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:B(Do,{sx:{cursor:"pointer"},onClick:x,variant:"body2",color:"secondary",children:m("common.back")})})]})}):to(fe,{children:[to(Z,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[to(Z,{sx:{mb:2},children:[B(ao,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:m("forgotPassword.title")}),B(ao,{variant:"body2",sx:{color:"grey.600"},children:m("forgotPassword.instructions")})]}),to(Z,{sx:{mb:1},children:[B(ao,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:m("forgotPassword.emailLabel")}),B(er,{fullWidth:!0,id:"email",name:"email",type:"email",value:i,disabled:n,onChange:v=>f(v.target.value),error:!!y,helperText:y,autoComplete:"email",placeholder:m("forgotPassword.emailPlaceholder"),required:!0})]}),B(ue,{disabled:n,type:"button",onClick:u,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?B(rr,{size:20}):m("forgotPassword.sendCodeButton")}),to(Z,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[B(Do,{sx:{cursor:"pointer"},onClick:x,variant:"body2",color:"secondary",children:m("common.back")}),B(ao,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),B(Do,{sx:{cursor:"pointer"},onClick:w,variant:"body2",color:"secondary",children:m("login.alreadyHaveCodeLink")})]})]}),B(Z,{children:g.length>0&&g.map((v,E)=>B(tr,{variant:"filled",sx:{mt:2},severity:"error",children:v},E))})]})},pe=nr;import{useState as U,useEffect as ge}from"react";import{Typography as To,TextField as ye,Button as sr,Box as oo,CircularProgress as xe,Alert as he,Link as ar}from"@mui/material";import{Fragment as lr,jsx as F,jsxs as go}from"react/jsx-runtime";var ir=({onScreenChange:o,onError:t,searchParams:a,onResetSuccess:i})=>{let{crudify:f}=G(),[n,s]=U(""),[g,l]=U(""),[y,c]=U(!1),[h,d]=U([]),[e,r]=U(null),[m,P]=U(null),[C,u]=U(""),[x,w]=U(""),[v,E]=U(!1),[p,S]=U(!0),[J,mo]=U(!1),[wo,Io]=U(null),[_e,Ko]=U(!1),{t:I}=V(),Po=T=>{let k=[`errors.auth.${T.code}`,`errors.data.${T.code}`,`errors.system.${T.code}`,`errors.${T.code}`,`resetPassword.${T.code.toLowerCase()}`];for(let O of k){let W=I(O);if(W!==O)return W}return T.message||I("error.unknown")},Co=T=>a?a instanceof URLSearchParams?a.get(T):a[T]||null:null;ge(()=>{if(a){if(a){let T=Co("fromCodeVerification"),k=Co("email"),O=Co("code");if(T==="true"&&k&&O){u(k),w(O),E(!0),mo(!0),S(!1);return}let W=Co("link");if(W)try{let H=decodeURIComponent(W),[$,uo]=H.split("/");if($&&uo&&$.length===6){w($),u(uo),E(!1),Io({email:uo,code:$});return}}catch{}if(k&&O){u(k),w(O),E(!1),Io({email:k,code:O});return}}d([I("resetPassword.invalidCode")]),S(!1),setTimeout(()=>o?.("forgotPassword"),3e3)}},[a,f,I,o]),ge(()=>{f&&wo&&!_e&&(Ko(!0),(async(k,O)=>{try{let W=[{operation:"validatePasswordResetCode",data:{email:k,codePassword:O}}],H=await f.transaction(W);if(H.data&&Array.isArray(H.data)){let $=H.data[0];if($&&$.response&&$.response.status==="OK"){mo(!0);return}}if(H.success)mo(!0);else{let uo=z(H).map(Po);d(uo),setTimeout(()=>o?.("forgotPassword"),3e3)}}catch(W){let $=z(W).map(Po);d($),setTimeout(()=>o?.("forgotPassword"),3e3)}finally{S(!1),Io(null),Ko(!1)}})(wo.email,wo.code))},[f,wo,I,o]);let Oe=T=>T.length<8?I("resetPassword.passwordTooShort"):null,ze=async()=>{if(y||!f)return;d([]),r(null),P(null);let T=!1;if(!n)r(I("resetPassword.newPasswordRequired")),T=!0;else{let k=Oe(n);k&&(r(k),T=!0)}if(g?n!==g&&(P(I("resetPassword.passwordsDoNotMatch")),T=!0):(P(I("resetPassword.confirmPasswordRequired")),T=!0),!T){c(!0);try{let k=[{operation:"validateAndResetPassword",data:{email:C,codePassword:x,newPassword:n}}],O=await f.transaction(k);if(O.success)d([]),setTimeout(()=>{i?.()},1e3);else{let H=z(O).map(Po);d(H)}}catch(k){let W=z(k).map(Po);d(W),t&&t(W.join(", "))}c(!1)}},We=()=>{v?o?.("checkCode",{email:C}):o?.("forgotPassword")};return p?F(oo,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:F(xe,{})}):J?go(lr,{children:[go(oo,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[go(oo,{sx:{mb:2},children:[F(To,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:I("resetPassword.title")}),F(To,{variant:"body2",sx:{color:"grey.600"},children:I("resetPassword.instructions")})]}),go(oo,{sx:{mb:1},children:[F(To,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.newPasswordLabel")}),F(ye,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:n,disabled:y,onChange:T=>s(T.target.value),error:!!e,helperText:e,autoComplete:"new-password",placeholder:I("resetPassword.newPasswordPlaceholder"),required:!0})]}),go(oo,{sx:{mb:1},children:[F(To,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.confirmPasswordLabel")}),F(ye,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:g,disabled:y,onChange:T=>l(T.target.value),error:!!m,helperText:m,autoComplete:"new-password",placeholder:I("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),F(sr,{disabled:y,type:"button",onClick:ze,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:y?F(xe,{size:20}):I("resetPassword.resetPasswordButton")}),F(oo,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:F(ar,{sx:{cursor:"pointer"},onClick:We,variant:"body2",color:"secondary",children:I("common.back")})})]}),F(oo,{children:h.length>0&&h.map((T,k)=>F(he,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})]}):F(oo,{children:h.length>0&&h.map((T,k)=>F(he,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})},be=ir;import{useState as yo,useEffect as cr}from"react";import{Typography as _o,TextField as dr,Button as mr,Box as xo,CircularProgress as ur,Alert as fr,Link as pr}from"@mui/material";import{Fragment as yr,jsx as K,jsxs as Eo}from"react/jsx-runtime";var gr=({onScreenChange:o,onError:t,searchParams:a})=>{let{crudify:i}=G(),[f,n]=yo(""),[s,g]=yo(!1),[l,y]=yo([]),[c,h]=yo(null),[d,e]=yo(""),{t:r}=V(),m=w=>a?a instanceof URLSearchParams?a.get(w):a[w]||null:null,P=w=>{let v=[`errors.auth.${w.code}`,`errors.data.${w.code}`,`errors.system.${w.code}`,`errors.${w.code}`,`checkCode.${w.code.toLowerCase()}`];for(let E of v){let p=r(E);if(p!==E)return p}return w.message||r("error.unknown")};cr(()=>{let w=m("email");w?e(w):o?.("forgotPassword")},[a,o]);let C=async()=>{if(!(s||!i)){if(y([]),h(null),!f){h(r("checkCode.codeRequired"));return}if(f.length!==6){h(r("checkCode.codeRequired"));return}g(!0);try{let w=[{operation:"validatePasswordResetCode",data:{email:d,codePassword:f}}],v=await i.transaction(w);if(v.success)o?.("resetPassword",{email:d,code:f,fromCodeVerification:"true"});else{let p=z(v).map(P);y(p),g(!1)}}catch(w){let E=z(w).map(P);y(E),g(!1),t&&t(E.join(", "))}}},u=()=>{o?.("forgotPassword")},x=w=>{let v=w.target.value.replace(/\D/g,"").slice(0,6);n(v)};return Eo(yr,{children:[Eo(xo,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Eo(xo,{sx:{mb:2},children:[K(_o,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:r("checkCode.title")}),K(_o,{variant:"body2",sx:{color:"grey.600"},children:r("checkCode.instructions")})]}),Eo(xo,{sx:{mb:1},children:[K(_o,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:r("checkCode.codeLabel")}),K(dr,{fullWidth:!0,id:"code",name:"code",type:"text",value:f,disabled:s,onChange:x,error:!!c,helperText:c,placeholder:r("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0})]}),K(mr,{disabled:s||f.length!==6,type:"button",onClick:C,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:s?K(ur,{size:20}):r("checkCode.verifyButton")}),K(xo,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:K(pr,{sx:{cursor:"pointer"},onClick:u,variant:"body2",color:"secondary",children:r("common.back")})})]}),K(xo,{children:l.length>0&&l.map((w,v)=>K(fr,{sx:{mt:2},severity:"error",children:w},v))})]})},we=gr;import{Box as xr,CircularProgress as hr,Alert as Pe,Typography as Oo}from"@mui/material";import{Fragment as br,jsx as io,jsxs as Ce}from"react/jsx-runtime";var ve=({children:o,fallback:t})=>{let{isLoading:a,error:i,isInitialized:f}=G(),{t:n}=V();return a?t||Ce(xr,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[io(hr,{}),io(Oo,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):i?io(Pe,{severity:"error",sx:{mt:2},children:Ce(Oo,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",i]})}):f?io(br,{children:o}):io(Pe,{severity:"warning",sx:{mt:2},children:io(Oo,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as j,jsxs as Tr}from"react/jsx-runtime";var Cr=({onScreenChange:o,onExternalNavigate:t,onLoginSuccess:a,onError:i,redirectUrl:f="/"})=>{let{t:n}=V(),{state:s,setScreen:g}=vo(),{config:l}=Q(),{showNotification:y}=Qo(),c=(d,e)=>{let r=e;d==="login"?r={}:d==="forgotPassword"&&!e&&(r={}),g(d,r),o?.(d,r)},h=()=>{let d={onScreenChange:c,onExternalNavigate:t,onError:i,redirectUrl:f};switch(s.currentScreen){case"forgotPassword":return j(pe,{...d});case"checkCode":return j(we,{...d,searchParams:s.searchParams});case"resetPassword":return j(be,{...d,searchParams:s.searchParams,onResetSuccess:()=>{let e=n("resetPassword.successMessage");y(e,"success"),c("login")}});default:return j(me,{...d,onLoginSuccess:a})}};return Tr(ve,{children:[j(wr,{sx:{display:"flex",justifyContent:"center",mb:3},children:j("img",{src:l.logo||"https://logos.crudia.com/nocios-default.png",alt:n("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:d=>{let e=d.target;e.src="https://logos.crudia.com/nocios-default.png"}})}),!l.logo&&l.appName&&j(Pr,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:l.appName}),h()]})},vr=({translations:o,translationsUrl:t,language:a="en",initialScreen:i="login",autoReadFromCookies:f=!0,...n})=>{let{config:s}=Q();return j(ne,{translations:o,translationsUrl:t,language:a,children:j(Yo,{config:s,children:j(le,{config:s,initialScreen:i,autoReadFromCookies:f,children:j(Cr,{...n})})})})},Ln=vr;import{Box as N,Card as Te,CardContent as Ee,Typography as q,Chip as So,Avatar as Er,Divider as Sr,CircularProgress as kr,Alert as Se,List as Lr,ListItem as zo,ListItemText as Wo,ListItemIcon as Rr,Collapse as Ar,IconButton as Uo}from"@mui/material";import{Person as Ir,Email as Br,Badge as Fr,Security as Dr,Schedule as _r,AccountCircle as Or,ExpandMore as zr,ExpandLess as Wr,Info as Ur}from"@mui/icons-material";import{useState as Nr}from"react";import{Fragment as Hr,jsx as b,jsxs as L}from"react/jsx-runtime";var Vr=({showExtendedData:o=!0,showProfileCard:t=!0,autoRefresh:a=!0})=>{let{userProfile:i,loading:f,error:n,extendedData:s,refreshProfile:g}=Zo({autoFetch:a,retryOnError:!0,maxRetries:3}),[l,y]=Nr(!1);if(f)return L(N,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[b(kr,{}),b(q,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return L(Se,{severity:"error",action:b(Uo,{color:"inherit",size:"small",onClick:g,children:b(q,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!i)return b(Se,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let c=s?.displayData||{},h=s?.totalFields||0,d=u=>{if(!u)return"No disponible";try{return new Date(u).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return u}},e=(u,x)=>x==null?"No disponible":typeof x=="boolean"?x?"S\xED":"No":Array.isArray(x)?x.length>0?x.join(", "):"Ninguno":typeof x=="object"?JSON.stringify(x,null,2):String(x),r=[{key:"id",label:"ID",icon:b(Fr,{})},{key:"email",label:"Email",icon:b(Br,{})},{key:"username",label:"Usuario",icon:b(Ir,{})},{key:"fullName",label:"Nombre completo",icon:b(Or,{})},{key:"role",label:"Rol",icon:b(Dr,{})}],m=[{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"}],P=[...r.map(u=>u.key),...m.map(u=>u.key),"permissions"],C=Object.keys(c).filter(u=>!P.includes(u)).map(u=>({key:u,label:u}));return L(N,{children:[t&&b(Te,{sx:{mb:2},children:L(Ee,{children:[L(N,{display:"flex",alignItems:"center",mb:2,children:[b(Er,{src:c.avatar,sx:{width:56,height:56,mr:2},children:c.fullName?.[0]||c.username?.[0]||c.email?.[0]}),L(N,{children:[b(q,{variant:"h6",children:c.fullName||c.username||c.email}),b(q,{variant:"body2",color:"text.secondary",children:c.role||"Usuario"}),c.isActive!==void 0&&b(So,{label:c.isActive?"Activo":"Inactivo",color:c.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),b(N,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:r.map(({key:u,label:x,icon:w})=>c[u]?L(N,{display:"flex",alignItems:"center",children:[b(N,{sx:{mr:1,color:"text.secondary"},children:w}),L(N,{children:[b(q,{variant:"caption",color:"text.secondary",children:x}),b(q,{variant:"body2",children:e(u,c[u])})]})]},u):null)}),c.permissions&&Array.isArray(c.permissions)&&c.permissions.length>0&&L(N,{mt:2,children:[b(q,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),L(N,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[c.permissions.slice(0,5).map((u,x)=>b(So,{label:u,size:"small",variant:"outlined"},x)),c.permissions.length>5&&b(So,{label:`+${c.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),o&&b(Te,{children:L(Ee,{children:[L(N,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[L(q,{variant:"h6",display:"flex",alignItems:"center",children:[b(Ur,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),b(So,{label:`${h} campos totales`,size:"small"})]}),L(Lr,{dense:!0,children:[m.map(({key:u,label:x})=>c[u]!==void 0&&L(zo,{divider:!0,children:[b(Rr,{children:b(_r,{fontSize:"small"})}),b(Wo,{primary:x,secondary:u.includes("At")||u.includes("Login")?d(c[u]):e(u,c[u])})]},u)),C.length>0&&L(Hr,{children:[b(Sr,{sx:{my:1}}),b(zo,{children:b(Wo,{primary:L(N,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[L(q,{variant:"subtitle2",children:["Campos Personalizados (",C.length,")"]}),b(Uo,{size:"small",onClick:()=>y(!l),children:l?b(Wr,{}):b(zr,{})})]})})}),b(Ar,{in:l,children:C.map(({key:u,label:x})=>b(zo,{sx:{pl:4},children:b(Wo,{primary:x,secondary:e(u,c[u])})},u))})]})]}),L(N,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[L(q,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",d(c.updatedAt)]}),b(Uo,{size:"small",onClick:g,disabled:f,children:b(q,{variant:"caption",children:"Actualizar"})})]})]})})]})},Mr=Vr;var ke=["create","read","update","delete"],Le=["create","read","update","delete"];import{useRef as ft}from"react";import{useTranslation as pt}from"react-i18next";import{Box as Lo,Typography as Be,Button as gt,Stack as yt,Alert as Fe,Divider as xt}from"@mui/material";import{Add as ht}from"@mui/icons-material";import{forwardRef as ot}from"react";import{useTranslation as et}from"react-i18next";import{Box as no,FormControl as rt,InputLabel as tt,Select as nt,MenuItem as st,IconButton as at,Typography as lo,FormHelperText as it,Stack as ko,Paper as Ie,Divider as lt,Button as $o}from"@mui/material";import{Delete as ct,SelectAll as dt,ClearAll as mt}from"@mui/icons-material";import{useState as $r,useEffect as jr,useRef as qr}from"react";import{useTranslation as Gr}from"react-i18next";import{Box as No,Typography as ho,Button as Re,Stack as Vo,FormHelperText as Ae,ToggleButton as Mo,ToggleButtonGroup as Kr}from"@mui/material";import{CheckCircle as Yr,Cancel as Jr,SelectAll as Xr,ClearAll as Qr}from"@mui/icons-material";import{jsx as D,jsxs as eo}from"react/jsx-runtime";var Zr=({value:o,onChange:t,availableFields:a,error:i,disabled:f=!1})=>{let{t:n}=Gr(),[s,g]=$r("custom"),l=qr(!1);jr(()=>{let e=o||{allow:[],owner_allow:[],deny:[]},r=new Set(a),m=(e.allow||[]).filter(x=>r.has(x)),P=(e.owner_allow||[]).filter(x=>r.has(x)),C=(e.deny||[]).filter(x=>r.has(x));a.forEach(x=>{!m.includes(x)&&!P.includes(x)&&!C.includes(x)&&C.push(x)});let u={allow:m,owner_allow:P,deny:C};JSON.stringify(u)!==JSON.stringify(e)&&t(u),m.length===a.length?g("all"):C.length===a.length?g("none"):g("custom")},[a,o]);let y=()=>{l.current=!0,t({allow:[...a],owner_allow:[],deny:[]}),g("all"),setTimeout(()=>{l.current=!1},0)},c=()=>{l.current=!0,t({allow:[],owner_allow:[],deny:[...a]}),g("none"),setTimeout(()=>{l.current=!1},0)},h=e=>o?.allow?.includes(e)?"allow":o?.owner_allow?.includes(e)?"owner_allow":"deny",d=(e,r)=>{l.current=!0;let m=new Set(o?.allow||[]),P=new Set(o?.owner_allow||[]),C=new Set(o?.deny||[]);m.delete(e),P.delete(e),C.delete(e),r==="allow"&&m.add(e),r==="owner_allow"&&P.add(e),r==="deny"&&C.add(e),t({allow:Array.from(m),owner_allow:Array.from(P),deny:Array.from(C)}),g("custom"),setTimeout(()=>{l.current=!1},0)};return a.length===0?eo(No,{children:[D(ho,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("modules.form.publicPolicies.fields.conditions.label")}),D(ho,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),i&&D(Ae,{error:!0,sx:{mt:1},children:i})]}):eo(No,{children:[D(ho,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.label")}),eo(Vo,{direction:"row",spacing:1,sx:{mb:3},children:[D(Re,{variant:s==="all"?"contained":"outlined",startIcon:D(Xr,{}),onClick:y,disabled:f,size:"small",sx:{minWidth:120,...s==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("modules.form.publicPolicies.fields.conditions.allFields")}),D(Re,{variant:s==="none"?"contained":"outlined",startIcon:D(Qr,{}),onClick:c,disabled:f,size:"small",sx:{minWidth:120,...s==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("modules.form.publicPolicies.fields.conditions.noFields")})]}),eo(No,{sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[D(ho,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.help")}),D(Vo,{spacing:1,children:a.map(e=>{let r=h(e);return eo(Vo,{direction:"row",spacing:1,alignItems:"center",children:[D(ho,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:e}),eo(Kr,{value:r,exclusive:!0,size:"small",children:[eo(Mo,{value:"allow",onClick:()=>d(e,"allow"),disabled:f,sx:{px:2,color:r==="allow"?"#ffffff":"#6b7280",backgroundColor:r==="allow"?"#16a34a":"#f3f4f6",borderColor:r==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:r==="allow"?"#15803d":"#e5e7eb",borderColor:r==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[D(Yr,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.allow")]}),D(Mo,{value:"owner_allow",onClick:()=>d(e,"owner_allow"),disabled:f,sx:{px:2,color:r==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:r==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:r==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:r==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:r==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),eo(Mo,{value:"deny",onClick:()=>d(e,"deny"),disabled:f,sx:{px:2,color:r==="deny"?"#ffffff":"#6b7280",backgroundColor:r==="deny"?"#dc2626":"#f3f4f6",borderColor:r==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:r==="deny"?"#b91c1c":"#e5e7eb",borderColor:r==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[D(Jr,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},e)})})]}),i&&D(Ae,{error:!0,sx:{mt:1},children:i})]})},Ho=Zr;import{jsx as A,jsxs as _}from"react/jsx-runtime";var ut=ot(({policy:o,onChange:t,onRemove:a,availableFields:i,isSubmitting:f=!1,usedActions:n,error:s},g)=>{let{t:l}=et(),y=new Set(Array.from(n||[]));y.delete(o.action);let c=ke.map(h=>({value:h,label:l(`modules.form.publicPolicies.fields.action.options.${h}`)}));return _(Ie,{ref:g,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[_(no,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[A(lo,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:l("modules.form.publicPolicies.policyTitle")}),A(at,{onClick:a,size:"small",disabled:f,"aria-label":l("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:A(ct,{})})]}),_(ko,{spacing:3,children:[A(ko,{direction:{xs:"column",md:"row"},spacing:2,children:A(no,{sx:{flex:1,minWidth:200},children:_(rt,{fullWidth:!0,children:[A(tt,{children:l("modules.form.publicPolicies.fields.action.label")}),A(nt,{value:o.action,label:l("modules.form.publicPolicies.fields.action.label"),disabled:f,onChange:h=>{let d=h.target.value,e={...o,action:d};d==="delete"?(e.permission="deny",delete e.fields):(e.fields={allow:[],owner_allow:[],deny:i},delete e.permission),t(e)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:c.map(h=>{let d=y.has(h.value);return A(st,{value:h.value,disabled:d,children:h.label},h.value)})}),s&&A(it,{error:!0,children:s})]})})}),o.action==="delete"?_(no,{children:[A(lo,{variant:"body2",color:"text.secondary",sx:{mb:2},children:l("modules.form.publicPolicies.fields.conditions.label")}),_(ko,{direction:"row",spacing:1,sx:{mb:3},children:[A($o,{variant:o.permission==="*"?"contained":"outlined",startIcon:A(dt,{}),onClick:()=>t({...o,permission:"*"}),disabled:f,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...o.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:l("modules.form.publicPolicies.fields.conditions.allFields")}),A($o,{variant:o.permission==="owner"?"contained":"outlined",onClick:()=>t({...o,permission:"owner"}),disabled:f,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...o.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:l("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),A($o,{variant:o.permission==="deny"?"contained":"outlined",startIcon:A(mt,{}),onClick:()=>t({...o,permission:"deny"}),disabled:f,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...o.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:l("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):A(Ho,{value:o.fields||{allow:[],owner_allow:[],deny:[]},onChange:h=>t({...o,fields:h}),availableFields:i,disabled:f}),A(Ie,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:o.action==="delete"?_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:o.permission==="*"?"#16a34a":o.permission==="owner"?"#0ea5e9":"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",o.permission||"-"]}):_(ko,{spacing:.5,divider:A(lt,{sx:{borderColor:"#e5e7eb"}}),children:[_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:"#16a34a"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(o?.fields?.allow||[]).join(", ")||"-"]}),_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:"#0ea5e9"},children:[l("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(o?.fields?.owner_allow||[]).join(", ")||"-"]}),_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(o?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),jo=ut;import{Fragment as Pt,jsx as Y,jsxs as Ro}from"react/jsx-runtime";var bt=()=>{let o=globalThis?.crypto;return o&&typeof o.randomUUID=="function"?o.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},wt=({policies:o,onChange:t,availableFields:a,errors:i,isSubmitting:f=!1})=>{let{t:n}=pt(),s=ft({}),g=new Set((o||[]).map(r=>r.action).filter(Boolean)),l=Le.filter(r=>!g.has(r)),y=l.length>0,c=()=>{let r=l[0]||"create",m={id:bt(),action:r};r==="delete"?m.permission="deny":m.fields={allow:[],owner_allow:[],deny:a};let P=[...o||[],m];t(P),setTimeout(()=>{let C=P.length-1,u=s.current[C];u&&u.scrollIntoView({behavior:"smooth",block:"center"})},100)},h=r=>{let m=[...o];m.splice(r,1),t(m)},d=(()=>{if(!i)return null;if(typeof i=="string")return i;let r=i._error;return typeof r=="string"?r:null})(),e=new Set((o||[]).map(r=>r.action));return Ro(Pt,{children:[Y(xt,{sx:{borderColor:"#e0e4e7"}}),Ro(Lo,{children:[Y(Lo,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:Ro(Lo,{children:[Y(Be,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("modules.form.publicPolicies.title")}),Y(Be,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("modules.form.publicPolicies.description")})]})}),d&&Y(Fe,{severity:"error",sx:{mb:3},children:d}),Ro(yt,{spacing:3,children:[(o||[]).length===0?Y(Fe,{severity:"info",children:n("modules.form.publicPolicies.noPolicies")}):o.map((r,m)=>Y(jo,{ref:P=>{s.current[m]=P},policy:r,onChange:P=>{let C=[...o];C[m]=P,t(C)},onRemove:()=>h(m),availableFields:a,isSubmitting:f,usedActions:e,error:typeof i=="object"&&i&&r.id in i?i[r.id]:void 0},r.id)),y&&Y(Lo,{children:Y(gt,{type:"button",variant:"outlined",startIcon:Y(ht,{}),onClick:c,disabled:f,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("modules.form.publicPolicies.addPolicy")})})]})]})]})},us=wt;import{useState as qo}from"react";import{Button as Ao,TextField as De,Box as co,Alert as bo,Typography as ro,CircularProgress as Go}from"@mui/material";import{jsx as R,jsxs as X}from"react/jsx-runtime";function bs(){let[o,t]=qo(""),[a,i]=qo(""),[f,n]=qo(!1),{isAuthenticated:s,isLoading:g,error:l,login:y,logout:c,refreshTokens:h,clearError:d,isExpiringSoon:e,expiresIn:r}=Q(),m=async u=>{if(u.preventDefault(),!o||!a)return;(await y(o,a)).success&&(t(""),i(""),n(!1))},P=async()=>{await c()},C=async()=>{await h()};return s?X(co,{sx:{maxWidth:600,mx:"auto",p:3},children:[R(ro,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),R(bo,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),X(co,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[R(ro,{variant:"h6",gutterBottom:!0,children:"Token Status"}),X(ro,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(r/1e3/60)," minutes"]}),e&&R(bo,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),X(co,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[R(Ao,{variant:"contained",onClick:C,disabled:g,startIcon:g?R(Go,{size:16}):null,children:"Refresh Tokens"}),R(Ao,{variant:"outlined",color:"error",onClick:P,disabled:g,children:"Logout"})]}),l&&R(bo,{severity:"error",sx:{mt:2},onClose:d,children:l})]}):X(co,{sx:{maxWidth:400,mx:"auto",p:3},children:[R(ro,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),R(bo,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),f?X("form",{onSubmit:m,children:[R(De,{fullWidth:!0,label:"Email",type:"email",value:o,onChange:u=>t(u.target.value),margin:"normal",required:!0,autoComplete:"email"}),R(De,{fullWidth:!0,label:"Password",type:"password",value:a,onChange:u=>i(u.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),R(Ao,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:g,startIcon:g?R(Go,{size:16}):null,sx:{mt:3,mb:2},children:g?"Logging in...":"Login"})]}):R(Ao,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),l&&R(bo,{severity:"error",sx:{mt:2},onClose:d,children:l})]})}function ws(){let{isAuthenticated:o,isLoading:t,isExpiringSoon:a,expiresIn:i}=Q();return t?X(co,{sx:{display:"flex",alignItems:"center",gap:1},children:[R(Go,{size:16}),R(ro,{variant:"caption",children:"Loading session..."})]}):o?X(co,{children:[R(ro,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),a&&X(ro,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(i/1e3/60)," min"]})]}):R(ro,{variant:"caption",color:"text.secondary",children:"Not logged in"})}export{Ln as a,Mr as b,ke as c,Le as d,us as e,bs as f,ws as g};
1
+ import{b as Yo,c as G,h as Qo,j as Q,l as Zo}from"./chunk-P2PNKHPV.mjs";import{g as z}from"./chunk-BJ6PIVZR.mjs";import{a as Jo,e as Xo}from"./chunk-5JKS55SE.mjs";import{Box as wr,Typography as Pr}from"@mui/material";import{createContext as Ne,useContext as Ve,useMemo as ee}from"react";import{useState as Bo,useEffect as Ue}from"react";var oe=(o,t)=>{let[a,i]=Bo({}),[f,n]=Bo(!1),[s,g]=Bo(null);return Ue(()=>{if(console.log("\u{1F527} [I18nProvider] Hybrid translation loading:",{hasProvidedTranslations:!!t&&Object.keys(t).length>0,hasUrl:!!o,providedKeys:t?Object.keys(t).length:0}),t&&Object.keys(t).length>0){console.log("\u2705 [I18nProvider] Using provided translations (highest priority)"),i(t),n(!1),g(null);return}if(!o){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),i({}),n(!1),g(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",o);let l=!1;return n(!0),g(null),fetch(o).then(y=>{if(!y.ok)throw new Error(`Failed to load translations: ${y.status}`);return y.json()}).then(y=>{l||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:o,keysLoaded:Object.keys(y).length}),i(y),n(!1))}).catch(y=>{l||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",o,y),g(y.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),i({}),n(!1))}),()=>{l=!0}},[o,t]),{translations:a,loading:f,error:s}};import{jsx as re}from"react/jsx-runtime";var te=Ne(null),Me=(o,t)=>o&&o[t]?o[t]:t.split(".").reduce((a,i)=>a&&typeof a=="object"?a[i]:void 0,o),ne=({children:o,translations:t,translationsUrl:a,language:i="en"})=>{let{translations:f,loading:n}=oe(a,t),s=ee(()=>(l,y)=>{let c=Me(f,l);return c==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${l}" - showing key as-is`),c=l),y&&typeof c=="string"&&Object.entries(y).forEach(([h,d])=>{c=c.replace(new RegExp(`{{${h}}}`,"g"),d)}),typeof c=="string"?c:l},[f]),g=ee(()=>({t:s,language:i}),[s,i]);return n?re("div",{children:"Loading translations..."}):re(te.Provider,{value:g,children:o})},V=()=>{let o=Ve(te);if(!o)throw new Error("useTranslation must be used within I18nProvider");return o};import{createContext as He,useContext as $e,useReducer as je,useEffect as se}from"react";import{jsx as Ge}from"react/jsx-runtime";var ae={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function qe(o,t){switch(t.type){case"SET_SCREEN":let a={...o,currentScreen:t.payload.screen,searchParams:t.payload.params||o.searchParams,errors:{global:[]}},i=new URLSearchParams(a.searchParams),f=i.toString()?`?${i.toString()}`:window.location.pathname;try{window.history.replaceState({},"",f)}catch{}return a;case"SET_SEARCH_PARAMS":return{...o,searchParams:t.payload};case"UPDATE_FORM_DATA":return{...o,formData:{...o.formData,...t.payload},errors:{...o.errors,...Object.keys(t.payload).reduce((n,s)=>({...n,[s]:void 0}),{})}};case"SET_LOADING":return{...o,loading:t.payload};case"SET_ERRORS":return{...o,errors:{...o.errors,...t.payload}};case"CLEAR_ERRORS":return{...o,errors:{global:[]}};case"SET_EMAIL_SENT":return{...o,emailSent:t.payload};case"SET_CODE_ALREADY_EXISTS":return{...o,codeAlreadyExists:t.payload};case"SET_CODE_VALIDATED":return{...o,codeValidated:t.payload};case"SET_FROM_CODE_VERIFICATION":return{...o,fromCodeVerification:t.payload};case"RESET_FORM":return{...o,formData:ae.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...o,config:t.payload};default:return o}}var ie=He(void 0),le=({children:o,initialScreen:t="login",config:a,autoReadFromCookies:i=!0})=>{let[f,n]=je(qe,{...ae,currentScreen:t});se(()=>{n({type:"INIT_CONFIG",payload:(()=>{let e={};if(i)try{let r=Jo("logo");if(r){let m=decodeURIComponent(r);m.startsWith("http")&&(e.logo=m)}}catch(r){console.error("Error reading configuration from cookies:",r)}return{publicApiKey:a?.publicApiKey,env:a?.env,appName:a?.appName,logo:a?.logo||e.logo,loginActions:a?.loginActions}})()})},[a,i]),se(()=>{let d=new URLSearchParams(window.location.search),e={};d.forEach((r,m)=>{e[m]=r}),Object.keys(e).length>0&&n({type:"SET_SEARCH_PARAMS",payload:e}),t==="checkCode"&&e.email&&n({type:"UPDATE_FORM_DATA",payload:{email:e.email,code:e.code||""}}),t==="resetPassword"&&e.link&&n({type:"SET_SEARCH_PARAMS",payload:e})},[t]);let h={state:f,dispatch:n,setScreen:(d,e)=>{n({type:"SET_SCREEN",payload:{screen:d,params:e}})},updateFormData:d=>{n({type:"UPDATE_FORM_DATA",payload:d})},setFieldError:(d,e)=>{n({type:"SET_ERRORS",payload:{[d]:e}})},clearErrors:()=>{n({type:"CLEAR_ERRORS"})},setLoading:d=>{n({type:"SET_LOADING",payload:d})}};return Ge(ie.Provider,{value:h,children:o})},vo=()=>{let o=$e(ie);if(o===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return o};import{useEffect as Ke,useRef as Ye}from"react";import{Typography as Fo,TextField as ce,Button as Je,Box as fo,CircularProgress as Xe,Alert as Qe,Link as de}from"@mui/material";import{Fragment as or,jsx as M,jsxs as po}from"react/jsx-runtime";var Ze=({onScreenChange:o,onExternalNavigate:t,onLoginSuccess:a,onError:i,redirectUrl:f="/"})=>{let{crudify:n}=G(),{state:s,updateFormData:g,setFieldError:l,clearErrors:y,setLoading:c}=vo(),{login:h}=Q(),d=V(),{t:e}=d,r=d.i18n,m=Ye(null),P=Xo(e,{currentLanguage:r?.language,enableDebug:!1}),C=()=>{if(s.searchParams.redirect)try{let p=decodeURIComponent(s.searchParams.redirect);if(p.startsWith("/")&&!p.startsWith("//"))return p}catch{}return f||"/"};Ke(()=>{let p=setTimeout(()=>{m.current&&m.current.focus()},100);return()=>clearTimeout(p)},[]);let u=p=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",p);let S=P.translateError({code:p.code,message:p.message,field:p.field});return console.log("\u{1F50D} [LoginForm] Translation result:",S),S},x=async()=>{if(!s.loading){if(!s.formData.username.trim()){l("username",e("login.usernameRequired"));return}if(!s.formData.password.trim()){l("password",e("login.passwordRequired"));return}y(),c(!0);try{let p=await h(s.formData.username,s.formData.password);if(c(!1),p.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let S=C();a&&a(p.data,S)}else{let S=p.rawResponse||p;w(S)}}catch(p){c(!1);let J=z(p).map(u);l("global",J),i&&i(J.join(", "))}}},w=p=>{z(p).forEach(J=>{if(J.field)l(J.field,u(J));else{let mo=s.errors.global||[];l("global",[...mo,u(J)])}})};return po(or,{children:[po(fo,{component:"form",noValidate:!0,onSubmit:p=>{p.preventDefault(),x()},onKeyDown:p=>{p.key==="Enter"&&!s.loading&&(p.preventDefault(),x())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[po(fo,{sx:{mb:1},children:[M(Fo,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:e("login.usernameOrEmailLabel")}),M(ce,{fullWidth:!0,id:"email",name:"email",type:"email",value:s.formData.username,disabled:s.loading,onChange:p=>g({username:p.target.value}),error:!!s.errors.username,helperText:s.errors.username,autoComplete:"email",placeholder:e("login.usernameOrEmailPlaceholder"),inputRef:m,required:!0})]}),po(fo,{sx:{mb:1},children:[M(Fo,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:e("login.passwordLabel")}),M(ce,{fullWidth:!0,id:"password",name:"password",type:"password",value:s.formData.password,disabled:s.loading,onChange:p=>g({password:p.target.value}),error:!!s.errors.password,helperText:s.errors.password,autoComplete:"current-password",placeholder:e("login.passwordPlaceholder"),required:!0})]}),s.config.loginActions?.includes("forgotPassword")&&M(fo,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:M(de,{sx:{cursor:"pointer"},onClick:()=>{o?.("forgotPassword",s.searchParams)},variant:"body2",color:"secondary",children:e("login.forgotPasswordLink")})}),M(Je,{disabled:s.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:s.loading?M(Xe,{size:20}):e("login.loginButton")})]}),M(fo,{children:s.errors.global&&s.errors.global.length>0&&s.errors.global.map((p,S)=>M(Qe,{variant:"filled",sx:{mt:2},severity:"error",children:M("div",{children:p})},S))}),s.config.loginActions?.includes("createUser")&&po(Fo,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[e("login.noAccountPrompt")," ",M(de,{sx:{cursor:"pointer"},onClick:()=>{let S=`/public/users/create${Object.keys(s.searchParams).length>0?`?${new URLSearchParams(s.searchParams).toString()}`:""}`;t?.(S)},fontWeight:"medium",color:"secondary",children:e("login.signUpLink")})]})]})},me=Ze;import{useState as so}from"react";import{Typography as ao,TextField as er,Button as ue,Box as Z,CircularProgress as rr,Alert as tr,Link as Do}from"@mui/material";import{Fragment as fe,jsx as B,jsxs as to}from"react/jsx-runtime";var nr=({onScreenChange:o,onError:t})=>{let{crudify:a}=G(),[i,f]=so(""),[n,s]=so(!1),[g,l]=so([]),[y,c]=so(null),[h,d]=so(!1),[e,r]=so(!1),{t:m}=V(),P=v=>{let E=[`errors.auth.${v.code}`,`errors.data.${v.code}`,`errors.system.${v.code}`,`errors.${v.code}`,`forgotPassword.${v.code.toLowerCase()}`];for(let p of E){let S=m(p);if(S!==p)return S}return v.message||m("error.unknown")},C=v=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),u=async()=>{if(!(n||!a)){if(l([]),c(null),!i){c(m("forgotPassword.emailRequired"));return}if(!C(i)){c(m("forgotPassword.invalidEmail"));return}s(!0);try{let v=[{operation:"requestPasswordReset",data:{email:i}}],E=await a.transaction(v);if(E.success)E.data&&E.data.existingCodeValid?r(!0):d(!0);else{let S=z(E).map(P);l(S)}}catch(v){let p=z(v).map(P);l(p),t&&t(p.join(", "))}finally{s(!1)}}},x=()=>{o?.("login")},w=()=>{if(h||e){o?.("checkCode",{email:i});return}if(!i){c(m("forgotPassword.emailRequired"));return}if(!C(i)){c(m("forgotPassword.invalidEmail"));return}o?.("checkCode",{email:i})};return h||e?B(fe,{children:to(Z,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[to(Z,{sx:{mb:2},children:[B(ao,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:m(e?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),B(ao,{variant:"body2",sx:{color:e?"success.main":"grey.600"},children:m("forgotPassword.checkEmailInstructions")})]}),B(ue,{type:"button",onClick:w,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:m("forgotPassword.enterCodeLink")}),B(Z,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:B(Do,{sx:{cursor:"pointer"},onClick:x,variant:"body2",color:"secondary",children:m("common.back")})})]})}):to(fe,{children:[to(Z,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[to(Z,{sx:{mb:2},children:[B(ao,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:m("forgotPassword.title")}),B(ao,{variant:"body2",sx:{color:"grey.600"},children:m("forgotPassword.instructions")})]}),to(Z,{sx:{mb:1},children:[B(ao,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:m("forgotPassword.emailLabel")}),B(er,{fullWidth:!0,id:"email",name:"email",type:"email",value:i,disabled:n,onChange:v=>f(v.target.value),error:!!y,helperText:y,autoComplete:"email",placeholder:m("forgotPassword.emailPlaceholder"),required:!0})]}),B(ue,{disabled:n,type:"button",onClick:u,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?B(rr,{size:20}):m("forgotPassword.sendCodeButton")}),to(Z,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[B(Do,{sx:{cursor:"pointer"},onClick:x,variant:"body2",color:"secondary",children:m("common.back")}),B(ao,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),B(Do,{sx:{cursor:"pointer"},onClick:w,variant:"body2",color:"secondary",children:m("login.alreadyHaveCodeLink")})]})]}),B(Z,{children:g.length>0&&g.map((v,E)=>B(tr,{variant:"filled",sx:{mt:2},severity:"error",children:v},E))})]})},pe=nr;import{useState as U,useEffect as ge}from"react";import{Typography as To,TextField as ye,Button as sr,Box as oo,CircularProgress as xe,Alert as he,Link as ar}from"@mui/material";import{Fragment as lr,jsx as F,jsxs as go}from"react/jsx-runtime";var ir=({onScreenChange:o,onError:t,searchParams:a,onResetSuccess:i})=>{let{crudify:f}=G(),[n,s]=U(""),[g,l]=U(""),[y,c]=U(!1),[h,d]=U([]),[e,r]=U(null),[m,P]=U(null),[C,u]=U(""),[x,w]=U(""),[v,E]=U(!1),[p,S]=U(!0),[J,mo]=U(!1),[wo,Io]=U(null),[_e,Ko]=U(!1),{t:I}=V(),Po=T=>{let k=[`errors.auth.${T.code}`,`errors.data.${T.code}`,`errors.system.${T.code}`,`errors.${T.code}`,`resetPassword.${T.code.toLowerCase()}`];for(let O of k){let W=I(O);if(W!==O)return W}return T.message||I("error.unknown")},Co=T=>a?a instanceof URLSearchParams?a.get(T):a[T]||null:null;ge(()=>{if(a){if(a){let T=Co("fromCodeVerification"),k=Co("email"),O=Co("code");if(T==="true"&&k&&O){u(k),w(O),E(!0),mo(!0),S(!1);return}let W=Co("link");if(W)try{let H=decodeURIComponent(W),[$,uo]=H.split("/");if($&&uo&&$.length===6){w($),u(uo),E(!1),Io({email:uo,code:$});return}}catch{}if(k&&O){u(k),w(O),E(!1),Io({email:k,code:O});return}}d([I("resetPassword.invalidCode")]),S(!1),setTimeout(()=>o?.("forgotPassword"),3e3)}},[a,f,I,o]),ge(()=>{f&&wo&&!_e&&(Ko(!0),(async(k,O)=>{try{let W=[{operation:"validatePasswordResetCode",data:{email:k,codePassword:O}}],H=await f.transaction(W);if(H.data&&Array.isArray(H.data)){let $=H.data[0];if($&&$.response&&$.response.status==="OK"){mo(!0);return}}if(H.success)mo(!0);else{let uo=z(H).map(Po);d(uo),setTimeout(()=>o?.("forgotPassword"),3e3)}}catch(W){let $=z(W).map(Po);d($),setTimeout(()=>o?.("forgotPassword"),3e3)}finally{S(!1),Io(null),Ko(!1)}})(wo.email,wo.code))},[f,wo,I,o]);let Oe=T=>T.length<8?I("resetPassword.passwordTooShort"):null,ze=async()=>{if(y||!f)return;d([]),r(null),P(null);let T=!1;if(!n)r(I("resetPassword.newPasswordRequired")),T=!0;else{let k=Oe(n);k&&(r(k),T=!0)}if(g?n!==g&&(P(I("resetPassword.passwordsDoNotMatch")),T=!0):(P(I("resetPassword.confirmPasswordRequired")),T=!0),!T){c(!0);try{let k=[{operation:"validateAndResetPassword",data:{email:C,codePassword:x,newPassword:n}}],O=await f.transaction(k);if(O.success)d([]),setTimeout(()=>{i?.()},1e3);else{let H=z(O).map(Po);d(H)}}catch(k){let W=z(k).map(Po);d(W),t&&t(W.join(", "))}c(!1)}},We=()=>{v?o?.("checkCode",{email:C}):o?.("forgotPassword")};return p?F(oo,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:F(xe,{})}):J?go(lr,{children:[go(oo,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[go(oo,{sx:{mb:2},children:[F(To,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:I("resetPassword.title")}),F(To,{variant:"body2",sx:{color:"grey.600"},children:I("resetPassword.instructions")})]}),go(oo,{sx:{mb:1},children:[F(To,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.newPasswordLabel")}),F(ye,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:n,disabled:y,onChange:T=>s(T.target.value),error:!!e,helperText:e,autoComplete:"new-password",placeholder:I("resetPassword.newPasswordPlaceholder"),required:!0})]}),go(oo,{sx:{mb:1},children:[F(To,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:I("resetPassword.confirmPasswordLabel")}),F(ye,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:g,disabled:y,onChange:T=>l(T.target.value),error:!!m,helperText:m,autoComplete:"new-password",placeholder:I("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),F(sr,{disabled:y,type:"button",onClick:ze,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:y?F(xe,{size:20}):I("resetPassword.resetPasswordButton")}),F(oo,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:F(ar,{sx:{cursor:"pointer"},onClick:We,variant:"body2",color:"secondary",children:I("common.back")})})]}),F(oo,{children:h.length>0&&h.map((T,k)=>F(he,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})]}):F(oo,{children:h.length>0&&h.map((T,k)=>F(he,{variant:"filled",sx:{mt:2},severity:"error",children:T},k))})},be=ir;import{useState as yo,useEffect as cr}from"react";import{Typography as _o,TextField as dr,Button as mr,Box as xo,CircularProgress as ur,Alert as fr,Link as pr}from"@mui/material";import{Fragment as yr,jsx as K,jsxs as Eo}from"react/jsx-runtime";var gr=({onScreenChange:o,onError:t,searchParams:a})=>{let{crudify:i}=G(),[f,n]=yo(""),[s,g]=yo(!1),[l,y]=yo([]),[c,h]=yo(null),[d,e]=yo(""),{t:r}=V(),m=w=>a?a instanceof URLSearchParams?a.get(w):a[w]||null:null,P=w=>{let v=[`errors.auth.${w.code}`,`errors.data.${w.code}`,`errors.system.${w.code}`,`errors.${w.code}`,`checkCode.${w.code.toLowerCase()}`];for(let E of v){let p=r(E);if(p!==E)return p}return w.message||r("error.unknown")};cr(()=>{let w=m("email");w?e(w):o?.("forgotPassword")},[a,o]);let C=async()=>{if(!(s||!i)){if(y([]),h(null),!f){h(r("checkCode.codeRequired"));return}if(f.length!==6){h(r("checkCode.codeRequired"));return}g(!0);try{let w=[{operation:"validatePasswordResetCode",data:{email:d,codePassword:f}}],v=await i.transaction(w);if(v.success)o?.("resetPassword",{email:d,code:f,fromCodeVerification:"true"});else{let p=z(v).map(P);y(p),g(!1)}}catch(w){let E=z(w).map(P);y(E),g(!1),t&&t(E.join(", "))}}},u=()=>{o?.("forgotPassword")},x=w=>{let v=w.target.value.replace(/\D/g,"").slice(0,6);n(v)};return Eo(yr,{children:[Eo(xo,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Eo(xo,{sx:{mb:2},children:[K(_o,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:r("checkCode.title")}),K(_o,{variant:"body2",sx:{color:"grey.600"},children:r("checkCode.instructions")})]}),Eo(xo,{sx:{mb:1},children:[K(_o,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:r("checkCode.codeLabel")}),K(dr,{fullWidth:!0,id:"code",name:"code",type:"text",value:f,disabled:s,onChange:x,error:!!c,helperText:c,placeholder:r("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0})]}),K(mr,{disabled:s||f.length!==6,type:"button",onClick:C,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:s?K(ur,{size:20}):r("checkCode.verifyButton")}),K(xo,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:K(pr,{sx:{cursor:"pointer"},onClick:u,variant:"body2",color:"secondary",children:r("common.back")})})]}),K(xo,{children:l.length>0&&l.map((w,v)=>K(fr,{sx:{mt:2},severity:"error",children:w},v))})]})},we=gr;import{Box as xr,CircularProgress as hr,Alert as Pe,Typography as Oo}from"@mui/material";import{Fragment as br,jsx as io,jsxs as Ce}from"react/jsx-runtime";var ve=({children:o,fallback:t})=>{let{isLoading:a,error:i,isInitialized:f}=G(),{t:n}=V();return a?t||Ce(xr,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[io(hr,{}),io(Oo,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):i?io(Pe,{severity:"error",sx:{mt:2},children:Ce(Oo,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",i]})}):f?io(br,{children:o}):io(Pe,{severity:"warning",sx:{mt:2},children:io(Oo,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as j,jsxs as Tr}from"react/jsx-runtime";var Cr=({onScreenChange:o,onExternalNavigate:t,onLoginSuccess:a,onError:i,redirectUrl:f="/"})=>{let{t:n}=V(),{state:s,setScreen:g}=vo(),{config:l}=Q(),{showNotification:y}=Qo(),c=(d,e)=>{let r=e;d==="login"?r={}:d==="forgotPassword"&&!e&&(r={}),g(d,r),o?.(d,r)},h=()=>{let d={onScreenChange:c,onExternalNavigate:t,onError:i,redirectUrl:f};switch(s.currentScreen){case"forgotPassword":return j(pe,{...d});case"checkCode":return j(we,{...d,searchParams:s.searchParams});case"resetPassword":return j(be,{...d,searchParams:s.searchParams,onResetSuccess:()=>{let e=n("resetPassword.successMessage");y(e,"success"),c("login")}});default:return j(me,{...d,onLoginSuccess:a})}};return Tr(ve,{children:[j(wr,{sx:{display:"flex",justifyContent:"center",mb:3},children:j("img",{src:l.logo||"https://logos.crudia.com/nocios-default.png",alt:n("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:d=>{let e=d.target;e.src="https://logos.crudia.com/nocios-default.png"}})}),!l.logo&&l.appName&&j(Pr,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:l.appName}),h()]})},vr=({translations:o,translationsUrl:t,language:a="en",initialScreen:i="login",autoReadFromCookies:f=!0,...n})=>{let{config:s}=Q();return j(ne,{translations:o,translationsUrl:t,language:a,children:j(Yo,{config:s,children:j(le,{config:s,initialScreen:i,autoReadFromCookies:f,children:j(Cr,{...n})})})})},Ln=vr;import{Box as N,Card as Te,CardContent as Ee,Typography as q,Chip as So,Avatar as Er,Divider as Sr,CircularProgress as kr,Alert as Se,List as Lr,ListItem as zo,ListItemText as Wo,ListItemIcon as Rr,Collapse as Ar,IconButton as Uo}from"@mui/material";import{Person as Ir,Email as Br,Badge as Fr,Security as Dr,Schedule as _r,AccountCircle as Or,ExpandMore as zr,ExpandLess as Wr,Info as Ur}from"@mui/icons-material";import{useState as Nr}from"react";import{Fragment as Hr,jsx as b,jsxs as L}from"react/jsx-runtime";var Vr=({showExtendedData:o=!0,showProfileCard:t=!0,autoRefresh:a=!0})=>{let{userProfile:i,loading:f,error:n,extendedData:s,refreshProfile:g}=Zo({autoFetch:a,retryOnError:!0,maxRetries:3}),[l,y]=Nr(!1);if(f)return L(N,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[b(kr,{}),b(q,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return L(Se,{severity:"error",action:b(Uo,{color:"inherit",size:"small",onClick:g,children:b(q,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!i)return b(Se,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let c=s?.displayData||{},h=s?.totalFields||0,d=u=>{if(!u)return"No disponible";try{return new Date(u).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return u}},e=(u,x)=>x==null?"No disponible":typeof x=="boolean"?x?"S\xED":"No":Array.isArray(x)?x.length>0?x.join(", "):"Ninguno":typeof x=="object"?JSON.stringify(x,null,2):String(x),r=[{key:"id",label:"ID",icon:b(Fr,{})},{key:"email",label:"Email",icon:b(Br,{})},{key:"username",label:"Usuario",icon:b(Ir,{})},{key:"fullName",label:"Nombre completo",icon:b(Or,{})},{key:"role",label:"Rol",icon:b(Dr,{})}],m=[{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"}],P=[...r.map(u=>u.key),...m.map(u=>u.key),"permissions"],C=Object.keys(c).filter(u=>!P.includes(u)).map(u=>({key:u,label:u}));return L(N,{children:[t&&b(Te,{sx:{mb:2},children:L(Ee,{children:[L(N,{display:"flex",alignItems:"center",mb:2,children:[b(Er,{src:c.avatar,sx:{width:56,height:56,mr:2},children:c.fullName?.[0]||c.username?.[0]||c.email?.[0]}),L(N,{children:[b(q,{variant:"h6",children:c.fullName||c.username||c.email}),b(q,{variant:"body2",color:"text.secondary",children:c.role||"Usuario"}),c.isActive!==void 0&&b(So,{label:c.isActive?"Activo":"Inactivo",color:c.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),b(N,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:r.map(({key:u,label:x,icon:w})=>c[u]?L(N,{display:"flex",alignItems:"center",children:[b(N,{sx:{mr:1,color:"text.secondary"},children:w}),L(N,{children:[b(q,{variant:"caption",color:"text.secondary",children:x}),b(q,{variant:"body2",children:e(u,c[u])})]})]},u):null)}),c.permissions&&Array.isArray(c.permissions)&&c.permissions.length>0&&L(N,{mt:2,children:[b(q,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),L(N,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[c.permissions.slice(0,5).map((u,x)=>b(So,{label:u,size:"small",variant:"outlined"},x)),c.permissions.length>5&&b(So,{label:`+${c.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),o&&b(Te,{children:L(Ee,{children:[L(N,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[L(q,{variant:"h6",display:"flex",alignItems:"center",children:[b(Ur,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),b(So,{label:`${h} campos totales`,size:"small"})]}),L(Lr,{dense:!0,children:[m.map(({key:u,label:x})=>c[u]!==void 0&&L(zo,{divider:!0,children:[b(Rr,{children:b(_r,{fontSize:"small"})}),b(Wo,{primary:x,secondary:u.includes("At")||u.includes("Login")?d(c[u]):e(u,c[u])})]},u)),C.length>0&&L(Hr,{children:[b(Sr,{sx:{my:1}}),b(zo,{children:b(Wo,{primary:L(N,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[L(q,{variant:"subtitle2",children:["Campos Personalizados (",C.length,")"]}),b(Uo,{size:"small",onClick:()=>y(!l),children:l?b(Wr,{}):b(zr,{})})]})})}),b(Ar,{in:l,children:C.map(({key:u,label:x})=>b(zo,{sx:{pl:4},children:b(Wo,{primary:x,secondary:e(u,c[u])})},u))})]})]}),L(N,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[L(q,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",d(c.updatedAt)]}),b(Uo,{size:"small",onClick:g,disabled:f,children:b(q,{variant:"caption",children:"Actualizar"})})]})]})})]})},Mr=Vr;var ke=["create","read","update","delete"],Le=["create","read","update","delete"];import{useRef as ft}from"react";import{useTranslation as pt}from"react-i18next";import{Box as Lo,Typography as Be,Button as gt,Stack as yt,Alert as Fe,Divider as xt}from"@mui/material";import{Add as ht}from"@mui/icons-material";import{forwardRef as ot}from"react";import{useTranslation as et}from"react-i18next";import{Box as no,FormControl as rt,InputLabel as tt,Select as nt,MenuItem as st,IconButton as at,Typography as lo,FormHelperText as it,Stack as ko,Paper as Ie,Divider as lt,Button as $o}from"@mui/material";import{Delete as ct,SelectAll as dt,ClearAll as mt}from"@mui/icons-material";import{useState as $r,useEffect as jr,useRef as qr}from"react";import{useTranslation as Gr}from"react-i18next";import{Box as No,Typography as ho,Button as Re,Stack as Vo,FormHelperText as Ae,ToggleButton as Mo,ToggleButtonGroup as Kr}from"@mui/material";import{CheckCircle as Yr,Cancel as Jr,SelectAll as Xr,ClearAll as Qr}from"@mui/icons-material";import{jsx as D,jsxs as eo}from"react/jsx-runtime";var Zr=({value:o,onChange:t,availableFields:a,error:i,disabled:f=!1})=>{let{t:n}=Gr(),[s,g]=$r("custom"),l=qr(!1);jr(()=>{let e=o||{allow:[],owner_allow:[],deny:[]},r=new Set(a),m=(e.allow||[]).filter(x=>r.has(x)),P=(e.owner_allow||[]).filter(x=>r.has(x)),C=(e.deny||[]).filter(x=>r.has(x));a.forEach(x=>{!m.includes(x)&&!P.includes(x)&&!C.includes(x)&&C.push(x)});let u={allow:m,owner_allow:P,deny:C};JSON.stringify(u)!==JSON.stringify(e)&&t(u),m.length===a.length?g("all"):C.length===a.length?g("none"):g("custom")},[a,o]);let y=()=>{l.current=!0,t({allow:[...a],owner_allow:[],deny:[]}),g("all"),setTimeout(()=>{l.current=!1},0)},c=()=>{l.current=!0,t({allow:[],owner_allow:[],deny:[...a]}),g("none"),setTimeout(()=>{l.current=!1},0)},h=e=>o?.allow?.includes(e)?"allow":o?.owner_allow?.includes(e)?"owner_allow":"deny",d=(e,r)=>{l.current=!0;let m=new Set(o?.allow||[]),P=new Set(o?.owner_allow||[]),C=new Set(o?.deny||[]);m.delete(e),P.delete(e),C.delete(e),r==="allow"&&m.add(e),r==="owner_allow"&&P.add(e),r==="deny"&&C.add(e),t({allow:Array.from(m),owner_allow:Array.from(P),deny:Array.from(C)}),g("custom"),setTimeout(()=>{l.current=!1},0)};return a.length===0?eo(No,{children:[D(ho,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("modules.form.publicPolicies.fields.conditions.label")}),D(ho,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),i&&D(Ae,{error:!0,sx:{mt:1},children:i})]}):eo(No,{children:[D(ho,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.label")}),eo(Vo,{direction:"row",spacing:1,sx:{mb:3},children:[D(Re,{variant:s==="all"?"contained":"outlined",startIcon:D(Xr,{}),onClick:y,disabled:f,size:"small",sx:{minWidth:120,...s==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("modules.form.publicPolicies.fields.conditions.allFields")}),D(Re,{variant:s==="none"?"contained":"outlined",startIcon:D(Qr,{}),onClick:c,disabled:f,size:"small",sx:{minWidth:120,...s==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("modules.form.publicPolicies.fields.conditions.noFields")})]}),eo(No,{sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[D(ho,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.help")}),D(Vo,{spacing:1,children:a.map(e=>{let r=h(e);return eo(Vo,{direction:"row",spacing:1,alignItems:"center",children:[D(ho,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:e}),eo(Kr,{value:r,exclusive:!0,size:"small",children:[eo(Mo,{value:"allow",onClick:()=>d(e,"allow"),disabled:f,sx:{px:2,color:r==="allow"?"#ffffff":"#6b7280",backgroundColor:r==="allow"?"#16a34a":"#f3f4f6",borderColor:r==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:r==="allow"?"#15803d":"#e5e7eb",borderColor:r==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[D(Yr,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.allow")]}),D(Mo,{value:"owner_allow",onClick:()=>d(e,"owner_allow"),disabled:f,sx:{px:2,color:r==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:r==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:r==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:r==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:r==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),eo(Mo,{value:"deny",onClick:()=>d(e,"deny"),disabled:f,sx:{px:2,color:r==="deny"?"#ffffff":"#6b7280",backgroundColor:r==="deny"?"#dc2626":"#f3f4f6",borderColor:r==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:r==="deny"?"#b91c1c":"#e5e7eb",borderColor:r==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[D(Jr,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},e)})})]}),i&&D(Ae,{error:!0,sx:{mt:1},children:i})]})},Ho=Zr;import{jsx as A,jsxs as _}from"react/jsx-runtime";var ut=ot(({policy:o,onChange:t,onRemove:a,availableFields:i,isSubmitting:f=!1,usedActions:n,error:s},g)=>{let{t:l}=et(),y=new Set(Array.from(n||[]));y.delete(o.action);let c=ke.map(h=>({value:h,label:l(`modules.form.publicPolicies.fields.action.options.${h}`)}));return _(Ie,{ref:g,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[_(no,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[A(lo,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:l("modules.form.publicPolicies.policyTitle")}),A(at,{onClick:a,size:"small",disabled:f,"aria-label":l("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:A(ct,{})})]}),_(ko,{spacing:3,children:[A(ko,{direction:{xs:"column",md:"row"},spacing:2,children:A(no,{sx:{flex:1,minWidth:200},children:_(rt,{fullWidth:!0,children:[A(tt,{children:l("modules.form.publicPolicies.fields.action.label")}),A(nt,{value:o.action,label:l("modules.form.publicPolicies.fields.action.label"),disabled:f,onChange:h=>{let d=h.target.value,e={...o,action:d};d==="delete"?(e.permission="deny",delete e.fields):(e.fields={allow:[],owner_allow:[],deny:i},delete e.permission),t(e)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:c.map(h=>{let d=y.has(h.value);return A(st,{value:h.value,disabled:d,children:h.label},h.value)})}),s&&A(it,{error:!0,children:s})]})})}),o.action==="delete"?_(no,{children:[A(lo,{variant:"body2",color:"text.secondary",sx:{mb:2},children:l("modules.form.publicPolicies.fields.conditions.label")}),_(ko,{direction:"row",spacing:1,sx:{mb:3},children:[A($o,{variant:o.permission==="*"?"contained":"outlined",startIcon:A(dt,{}),onClick:()=>t({...o,permission:"*"}),disabled:f,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...o.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:l("modules.form.publicPolicies.fields.conditions.allFields")}),A($o,{variant:o.permission==="owner"?"contained":"outlined",onClick:()=>t({...o,permission:"owner"}),disabled:f,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...o.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:l("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),A($o,{variant:o.permission==="deny"?"contained":"outlined",startIcon:A(mt,{}),onClick:()=>t({...o,permission:"deny"}),disabled:f,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...o.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:l("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):A(Ho,{value:o.fields||{allow:[],owner_allow:[],deny:[]},onChange:h=>t({...o,fields:h}),availableFields:i,disabled:f}),A(Ie,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:o.action==="delete"?_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:o.permission==="*"?"#16a34a":o.permission==="owner"?"#0ea5e9":"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",o.permission||"-"]}):_(ko,{spacing:.5,divider:A(lt,{sx:{borderColor:"#e5e7eb"}}),children:[_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:"#16a34a"},children:[l("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(o?.fields?.allow||[]).join(", ")||"-"]}),_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:"#0ea5e9"},children:[l("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(o?.fields?.owner_allow||[]).join(", ")||"-"]}),_(lo,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[_(no,{component:"span",sx:{color:"#dc2626"},children:[l("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(o?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),jo=ut;import{Fragment as Pt,jsx as Y,jsxs as Ro}from"react/jsx-runtime";var bt=()=>{let o=globalThis?.crypto;return o&&typeof o.randomUUID=="function"?o.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},wt=({policies:o,onChange:t,availableFields:a,errors:i,isSubmitting:f=!1})=>{let{t:n}=pt(),s=ft({}),g=new Set((o||[]).map(r=>r.action).filter(Boolean)),l=Le.filter(r=>!g.has(r)),y=l.length>0,c=()=>{let r=l[0]||"create",m={id:bt(),action:r};r==="delete"?m.permission="deny":m.fields={allow:[],owner_allow:[],deny:a};let P=[...o||[],m];t(P),setTimeout(()=>{let C=P.length-1,u=s.current[C];u&&u.scrollIntoView({behavior:"smooth",block:"center"})},100)},h=r=>{let m=[...o];m.splice(r,1),t(m)},d=(()=>{if(!i)return null;if(typeof i=="string")return i;let r=i._error;return typeof r=="string"?r:null})(),e=new Set((o||[]).map(r=>r.action));return Ro(Pt,{children:[Y(xt,{sx:{borderColor:"#e0e4e7"}}),Ro(Lo,{children:[Y(Lo,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:Ro(Lo,{children:[Y(Be,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("modules.form.publicPolicies.title")}),Y(Be,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("modules.form.publicPolicies.description")})]})}),d&&Y(Fe,{severity:"error",sx:{mb:3},children:d}),Ro(yt,{spacing:3,children:[(o||[]).length===0?Y(Fe,{severity:"info",children:n("modules.form.publicPolicies.noPolicies")}):o.map((r,m)=>Y(jo,{ref:P=>{s.current[m]=P},policy:r,onChange:P=>{let C=[...o];C[m]=P,t(C)},onRemove:()=>h(m),availableFields:a,isSubmitting:f,usedActions:e,error:typeof i=="object"&&i&&r.id in i?i[r.id]:void 0},r.id)),y&&Y(Lo,{children:Y(gt,{type:"button",variant:"outlined",startIcon:Y(ht,{}),onClick:c,disabled:f,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("modules.form.publicPolicies.addPolicy")})})]})]})]})},us=wt;import{useState as qo}from"react";import{Button as Ao,TextField as De,Box as co,Alert as bo,Typography as ro,CircularProgress as Go}from"@mui/material";import{jsx as R,jsxs as X}from"react/jsx-runtime";function bs(){let[o,t]=qo(""),[a,i]=qo(""),[f,n]=qo(!1),{isAuthenticated:s,isLoading:g,error:l,login:y,logout:c,refreshTokens:h,clearError:d,isExpiringSoon:e,expiresIn:r}=Q(),m=async u=>{if(u.preventDefault(),!o||!a)return;(await y(o,a)).success&&(t(""),i(""),n(!1))},P=async()=>{await c()},C=async()=>{await h()};return s?X(co,{sx:{maxWidth:600,mx:"auto",p:3},children:[R(ro,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),R(bo,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),X(co,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[R(ro,{variant:"h6",gutterBottom:!0,children:"Token Status"}),X(ro,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(r/1e3/60)," minutes"]}),e&&R(bo,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),X(co,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[R(Ao,{variant:"contained",onClick:C,disabled:g,startIcon:g?R(Go,{size:16}):null,children:"Refresh Tokens"}),R(Ao,{variant:"outlined",color:"error",onClick:P,disabled:g,children:"Logout"})]}),l&&R(bo,{severity:"error",sx:{mt:2},onClose:d,children:l})]}):X(co,{sx:{maxWidth:400,mx:"auto",p:3},children:[R(ro,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),R(bo,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),f?X("form",{onSubmit:m,children:[R(De,{fullWidth:!0,label:"Email",type:"email",value:o,onChange:u=>t(u.target.value),margin:"normal",required:!0,autoComplete:"email"}),R(De,{fullWidth:!0,label:"Password",type:"password",value:a,onChange:u=>i(u.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),R(Ao,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:g,startIcon:g?R(Go,{size:16}):null,sx:{mt:3,mb:2},children:g?"Logging in...":"Login"})]}):R(Ao,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),l&&R(bo,{severity:"error",sx:{mt:2},onClose:d,children:l})]})}function ws(){let{isAuthenticated:o,isLoading:t,isExpiringSoon:a,expiresIn:i}=Q();return t?X(co,{sx:{display:"flex",alignItems:"center",gap:1},children:[R(Go,{size:16}),R(ro,{variant:"caption",children:"Loading session..."})]}):o?X(co,{children:[R(ro,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),a&&X(ro,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(i/1e3/60)," min"]})]}):R(ro,{variant:"caption",color:"text.secondary",children:"Not logged in"})}export{Ln as a,Mr as b,ke as c,Le as d,us as e,bs as f,ws as g};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkAT74WV5Wjs = require('./chunk-AT74WV5W.js');var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var V=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}},W= exports.a =V.getInstance();var _jsxruntime = require('react/jsx-runtime');var J=_react.createContext.call(void 0, void 0),Z= exports.b =({config:r,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[o,u]=_react.useState.call(void 0, null),[h,y]=_react.useState.call(void 0, !1),[m,T]=_react.useState.call(void 0, ""),[x,c]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){u("No publicApiKey provided"),t(!1),y(!1);return}let n=`${r.publicApiKey}-${r.env}`;if(n===m&&h){t(!1);return}(async()=>{t(!0),u(null),y(!1);try{_crudifybrowser2.default.config(r.env||"prod");let d=await _crudifybrowser2.default.init(r.publicApiKey,"none");if(c(d),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")y(!0),T(n),d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&W.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(d){let A=d instanceof Error?d.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",d),u(A),y(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,m,h]);let s={crudify:h?_crudifybrowser2.default:null,isLoading:e,error:o,isInitialized:h,adminCredentials:x};return _jsxruntime.jsx.call(void 0, J.Provider,{value:s,children:i})},q= exports.c =()=>{let r=_react.useContext.call(void 0, J);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);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 _cryptojs2.default.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 (e2){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 (e3){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 _cryptojs2.default.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=l.getEncryptionKey();return _cryptojs2.default.AES.decrypt(i,e).toString(_cryptojs2.default.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 f=l;var z=class r{constructor(){this.config={};this.initialized=!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,...i},f.setStorageType(this.config.storageType||"localStorage"),_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=f.getTokens();e?f.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):f.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 _crudifybrowser2.default.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let o=f.getTokens(),u={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:_optionalChain([o, 'optionalAccess', _2 => _2.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([o, 'optionalAccess', _3 => _3.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return f.saveTokens(u),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.onLoginSuccess, 'optionalCall', _6 => _6(u)]),{success:!0,tokens:u,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 _crudifybrowser2.default.logout(),f.clearTokens(),this.log("Logout successful"),_optionalChain([this, 'access', _7 => _7.config, 'access', _8 => _8.onLogout, 'optionalCall', _9 => _9()])}catch(i){this.log("Logout error:",i),f.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=f.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"),f.clearTokens(),!1;if(_crudifybrowser2.default.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),_crudifybrowser2.default.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=f.getTokens();return o&&_optionalChain([this, 'access', _10 => _10.config, 'access', _11 => _11.onSessionRestored, 'optionalCall', _12 => _12(o)]),!0}return f.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _13 => _13.config, 'access', _14 => _14.onSessionRestored, 'optionalCall', _15 => _15(i)]),!0}catch(i){return this.log("Session restore error:",i),f.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||f.hasValidTokens()}getTokenInfo(){let i=_crudifybrowser2.default.getTokenData(),e=f.getExpirationInfo(),t=f.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:f.hasValidTokens(),apiEndpointAdmin:_optionalChain([t, 'optionalAccess', _16 => _16.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([t, 'optionalAccess', _17 => _17.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 _crudifybrowser2.default.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),f.clearTokens(),_optionalChain([this, 'access', _18 => _18.config, 'access', _19 => _19.showNotification, 'optionalCall', _20 => _20(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _21 => _21.config, 'access', _22 => _22.onSessionExpired, 'optionalCall', _23 => _23()]),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return f.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),f.clearTokens(),_optionalChain([this, 'access', _24 => _24.config, 'access', _25 => _25.showNotification, 'optionalCall', _26 => _26(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _27 => _27.config, 'access', _28 => _28.onSessionExpired, 'optionalCall', _29 => _29()]),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){_crudifybrowser2.default.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"),_chunkAT74WV5Wjs.f.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(f.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunkAT74WV5Wjs.f.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}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"||_optionalChain([o, 'access', _30 => _30.message, 'optionalAccess', _31 => _31.includes, 'call', _32 => _32("Unauthorized")])||_optionalChain([o, 'access', _33 => _33.message, 'optionalAccess', _34 => _34.includes, 'call', _35 => _35("Not Authorized")])||_optionalChain([o, 'access', _36 => _36.message, 'optionalAccess', _37 => _37.includes, 'call', _38 => _38("NOT_AUTHORIZED")])||_optionalChain([o, 'access', _39 => _39.message, 'optionalAccess', _40 => _40.includes, 'call', _41 => _41("Token")])||_optionalChain([o, 'access', _42 => _42.message, 'optionalAccess', _43 => _43.includes, 'call', _44 => _44("TOKEN")])||_optionalChain([o, 'access', _45 => _45.message, 'optionalAccess', _46 => _46.includes, 'call', _47 => _47("Authentication")])||_optionalChain([o, 'access', _48 => _48.message, 'optionalAccess', _49 => _49.includes, 'call', _50 => _50("UNAUTHENTICATED")])||_optionalChain([o, 'access', _51 => _51.extensions, 'optionalAccess', _52 => _52.code])==="UNAUTHENTICATED"||_optionalChain([o, 'access', _53 => _53.extensions, 'optionalAccess', _54 => _54.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.",(_optionalChain([t, 'access', _55 => _55.message, 'optionalAccess', _56 => _56.includes, 'call', _57 => _57("TOKEN")])||_optionalChain([t, 'access', _58 => _58.message, 'optionalAccess', _59 => _59.includes, 'call', _60 => _60("Token")]))&&(e.isTokenExpired=!0),_optionalChain([t, 'access', _61 => _61.extensions, 'optionalAccess', _62 => _62.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(u=>typeof u=="string"&&(u.includes("NOT_AUTHORIZED")||u.includes("TOKEN_REFRESH_FAILED")||u.includes("TOKEN_HAS_EXPIRED")||u.includes("PLEASE_LOGIN")||u.includes("Unauthorized")||u.includes("UNAUTHENTICATED")||u.includes("SESSION_EXPIRED")||u.includes("INVALID_TOKEN")));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&&_optionalChain([i, 'access', _63 => _63.data, 'optionalAccess', _64 => _64.response, 'optionalAccess', _65 => _65.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&&_optionalChain([i, 'access', _66 => _66.data, 'optionalAccess', _67 => _67.response, 'optionalAccess', _68 => _68.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 (e4){}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(),e=_crudifybrowser2.default.getTokenData();if(this.lastActivityTime===0)return"none";let t=900*1e3,o=300*1e3,u=300*1e3;return i>t?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):i<o&&e.expiresIn<u&&e.expiresIn>0?(this.log(`User active recently (${Math.floor(i/6e4)}min ago) and token expiring soon, should refresh`),"refresh"):"none"}clearSession(){f.clearTokens(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkAT74WV5Wjs.b.call(void 0, "SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(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"}};function Q(r={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=z.getInstance(),o=_react.useCallback.call(void 0, 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(a=>({...a,isLoading:!0,error:null}));let c={autoRestore:_nullishCoalesce(r.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(r.enableLogging, () => (!1)),showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,onSessionExpired:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([r, 'access', _69 => _69.onSessionExpired, 'optionalCall', _70 => _70()])},onSessionRestored:a=>{e(d=>({...d,isAuthenticated:!0,tokens:a,error:null})),_optionalChain([r, 'access', _71 => _71.onSessionRestored, 'optionalCall', _72 => _72(a)])},onLoginSuccess:a=>{e(d=>({...d,isAuthenticated:!0,tokens:a,error:null}))},onLogout:()=>{e(a=>({...a,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",c),await t.initialize(c),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let s=t.isAuthenticated(),n=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",s),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",n),e(a=>({...a,isAuthenticated:s,isInitialized:!0,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let s=c instanceof Error?c.message:"Initialization failed";e(n=>({...n,isLoading:!1,isInitialized:!0,error:s}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),u=_react.useCallback.call(void 0, async(c,s)=>{e(n=>({...n,isLoading:!0,error:null}));try{let n=await t.login(c,s);return n.success&&n.tokens?e(a=>({...a,isAuthenticated:!0,tokens:n.tokens,isLoading:!1,error:null})):e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),n}catch(n){let a=n instanceof Error?n.message:"Login failed",d=a.includes("INVALID_CREDENTIALS")||a.includes("Invalid email")||a.includes("Invalid password")||a.includes("credentials");return e(A=>({...A,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:a})),{success:!1,error:a}}},[t]),h=_react.useCallback.call(void 0, async()=>{e(c=>({...c,isLoading:!0}));try{await t.logout(),e(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){e(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[t]),y=_react.useCallback.call(void 0, async()=>{try{let c=await t.refreshTokens();if(c){let s=t.getTokenInfo();e(n=>({...n,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 c}catch(c){return e(s=>({...s,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[t]),m=_react.useCallback.call(void 0, ()=>{e(c=>({...c,error:null}))},[]),T=_react.useCallback.call(void 0, ()=>t.getTokenInfo(),[t]);_react.useEffect.call(void 0, ()=>{o()},[o]),_react.useEffect.call(void 0, ()=>{if(!i.isAuthenticated||!i.tokens)return;let c=_chunkAT74WV5Wjs.g.getInstance(),s=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},n=c.subscribe(s);window.addEventListener("popstate",s);let a=setInterval(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping inactivity check");return}let d=t.checkInactivity();if(d==="logout")r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout - logging out user"),await h();else if(d==="refresh")if(r.enableLogging&&console.log("\u{1F504} User active, token expiring soon - refreshing..."),e(p=>({...p,isLoading:!0})),await t.refreshTokens()){let p=t.getTokenInfo();e(I=>({...I,isLoading:!1,tokens:p.crudifyTokens.accessToken?{accessToken:p.crudifyTokens.accessToken,refreshToken:p.crudifyTokens.refreshToken,expiresAt:p.crudifyTokens.expiresAt,refreshExpiresAt:p.crudifyTokens.refreshExpiresAt}:null}))}else e(p=>({...p,isLoading:!1,isAuthenticated:!1,tokens:null}))},120*1e3);return()=>{clearInterval(a),window.removeEventListener("popstate",s),n()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,h]),_react.useEffect.call(void 0, ()=>{let c=_chunkAT74WV5Wjs.f.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(n=>({...n,isLoading:!0}));try{if(await t.refreshTokens()){r.enableLogging&&console.log("\u2705 Token refreshed successfully");let a=t.getTokenInfo();e(d=>({...d,isLoading:!1,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null}))}else r.enableLogging&&console.log("\u274C Token refresh failed, session expired"),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(n){r.enableLogging&&console.error("\u274C Error during token refresh:",n),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:n instanceof Error?n.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(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([s, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message])||"Session expired"})),_optionalChain([r, 'access', _75 => _75.onSessionExpired, 'optionalCall', _76 => _76()]))});return()=>c()},[r.enableLogging,r.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{let c=f.subscribeToChanges(s=>{s?(r.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(n=>({...n,tokens:s,isAuthenticated:!0}))):(r.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(n=>({...n,isAuthenticated:!1,tokens:null})),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[r.enableLogging]);let x=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]);return{...i,login:u,logout:h,refreshTokens:y,clearError:m,getTokenInfo:T,updateActivity:x,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}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var ie=_react.createContext.call(void 0, null),ve=r=>_dompurify2.default.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}),X= exports.g =({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:u=!1})=>{let[h,y]=_react.useState.call(void 0, []),m=_react.useCallback.call(void 0, (s,n="info",a)=>{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=_uuid.v4.call(void 0, ),A={id:d,message:s,severity:n,autoHideDuration:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _77 => _77.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _78 => _78.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _79 => _79.allowHtml]), () => (u))};return y(p=>[...p.length>=i?p.slice(-(i-1)):p,A]),d},[i,e,o,u]),T=_react.useCallback.call(void 0, s=>{y(n=>n.filter(a=>a.id!==s))},[]),x=_react.useCallback.call(void 0, ()=>{y([])},[]),c={showNotification:m,hideNotification:T,clearAllNotifications:x};return _jsxruntime.jsxs.call(void 0, ie.Provider,{value:c,children:[r,o&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{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:h.map(s=>_jsxruntime.jsx.call(void 0, be,{notification:s,onClose:()=>T(s.id)},s.id))})})]})},be=({notification:r,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),o=_react.useCallback.call(void 0, (u,h)=>{h!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let u=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(u)}},[r.autoHideDuration,r.persistent,o]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:e,onClose:o,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:r.severity,onClose:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:ve(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},te= exports.h =()=>{let r=_react.useContext.call(void 0, ie);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var oe=_react.createContext.call(void 0, void 0);function ne({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let u;try{let{showNotification:n}=te();u=n}catch (e5){}let h={};try{let n=q();n.isInitialized&&n.adminCredentials&&(h=n.adminCredentials)}catch (e6){}let y=_react2.default.useMemo(()=>({...i,showNotification:u,apiEndpointAdmin:h.apiEndpointAdmin,apiKeyEndpointAdmin:h.apiKeyEndpointAdmin,onSessionExpired:()=>{_optionalChain([i, 'access', _80 => _80.onSessionExpired, 'optionalCall', _81 => _81()])}}),[i,u,h.apiEndpointAdmin,h.apiKeyEndpointAdmin]),m=Q(y),T=_react.useMemo.call(void 0, ()=>{let n,a,d,A,p,I="unknown";if(_optionalChain([e, 'optionalAccess', _82 => _82.publicApiKey])&&(n=e.publicApiKey,I="props"),_optionalChain([e, 'optionalAccess', _83 => _83.env])&&(a=e.env),_optionalChain([e, 'optionalAccess', _84 => _84.appName])&&(d=e.appName),_optionalChain([e, 'optionalAccess', _85 => _85.loginActions])&&(A=e.loginActions),_optionalChain([e, 'optionalAccess', _86 => _86.logo])&&(p=e.logo),!n){let L=_chunkAT74WV5Wjs.a.call(void 0, "publicApiKey"),N=_chunkAT74WV5Wjs.a.call(void 0, "environment"),S=_chunkAT74WV5Wjs.a.call(void 0, "appName"),g=_chunkAT74WV5Wjs.a.call(void 0, "loginActions"),P=_chunkAT74WV5Wjs.a.call(void 0, "logo");L&&(n=L,I="cookies"),N&&["dev","stg","prod"].includes(N)&&(a=N),S&&(d=decodeURIComponent(S)),g&&(A=decodeURIComponent(g).split(",").map(U=>U.trim()).filter(Boolean)),P&&(p=decodeURIComponent(P))}return{publicApiKey:n,env:a,appName:d,loginActions:A,logo:p}},[e]),x=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([m, 'access', _87 => _87.tokens, 'optionalAccess', _88 => _88.accessToken])||!m.isAuthenticated)return null;try{let n=_chunkAT74WV5Wjs.h.call(void 0, m.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let a={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(d=>{["sub","email","subscriber"].includes(d)||(a[d]=n[d])}),a}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[_optionalChain([m, 'access', _89 => _89.tokens, 'optionalAccess', _90 => _90.accessToken]),m.isAuthenticated]),c={...m,sessionData:x,config:T},s={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, oe.Provider,{value:c,children:r})}function mi(r){let i={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _91 => _91.notificationOptions, 'optionalAccess', _92 => _92.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _93 => _93.notificationOptions, 'optionalAccess', _94 => _94.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _95 => _95.notificationOptions, 'optionalAccess', _96 => _96.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _97 => _97.notificationOptions, 'optionalAccess', _98 => _98.allowHtml])||!1};return _optionalChain([r, 'access', _99 => _99.config, 'optionalAccess', _100 => _100.publicApiKey])?_jsxruntime.jsx.call(void 0, Z,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:_jsxruntime.jsx.call(void 0, X,{...i,children:_jsxruntime.jsx.call(void 0, ne,{...r})})}):_jsxruntime.jsx.call(void 0, X,{...i,children:_jsxruntime.jsx.call(void 0, ne,{...r})})}function Re(){let r=_react.useContext.call(void 0, oe);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Ti(){let r=Re();return r.isInitialized?_jsxruntime.jsxs.call(void 0, "div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[_jsxruntime.jsx.call(void 0, "h4",{children:"Session Debug Info"}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var Si=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,u]=_react.useState.call(void 0, null),[h,y]=_react.useState.call(void 0, !1),[m,T]=_react.useState.call(void 0, null),[x,c]=_react.useState.call(void 0, {}),s=_react.useRef.call(void 0, null),n=_react.useRef.call(void 0, !0),a=_react.useRef.call(void 0, 0),d=_react.useRef.call(void 0, 0),A=_react.useCallback.call(void 0, ()=>{u(null),T(null),y(!1),c({})},[]),p=_react.useCallback.call(void 0, async()=>{let I=_chunkAT74WV5Wjs.i.call(void 0, );if(!I){n.current&&(T("No user email available"),y(!1));return}s.current&&s.current.abort();let L=new AbortController;s.current=L;let N=++a.current;try{n.current&&(y(!0),T(null));let S=await _crudifybrowser2.default.readItems("users",{filter:{email:I},pagination:{limit:1}});if(N===a.current&&n.current&&!L.signal.aborted)if(S.success&&S.data&&S.data.length>0){let g=S.data[0];u(g);let P={fullProfile:g,totalFields:Object.keys(g).length,displayData:{id:g.id,email:g.email,username:g.username,firstName:g.firstName,lastName:g.lastName,fullName:g.fullName||`${g.firstName||""} ${g.lastName||""}`.trim(),role:g.role,permissions:g.permissions||[],isActive:g.isActive,lastLogin:g.lastLogin,createdAt:g.createdAt,updatedAt:g.updatedAt,...Object.keys(g).filter(O=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(O)).reduce((O,U)=>({...O,[U]:g[U]}),{})}};c(P),T(null),d.current=0}else T("User profile not found"),u(null),c({})}catch(S){if(N===a.current&&n.current){let g=S;if(g.name==="AbortError")return;e&&d.current<t&&(_optionalChain([g, 'access', _101 => _101.message, 'optionalAccess', _102 => _102.includes, 'call', _103 => _103("Network Error")])||_optionalChain([g, 'access', _104 => _104.message, 'optionalAccess', _105 => _105.includes, 'call', _106 => _106("Failed to fetch")]))?(d.current++,setTimeout(()=>{n.current&&p()},1e3*d.current)):(T("Failed to load user profile"),u(null),c({}))}}finally{N===a.current&&n.current&&y(!1),s.current===L&&(s.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{i&&p()},[i,p]),_react.useEffect.call(void 0, ()=>(n.current=!0,()=>{n.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:o,loading:h,error:m,extendedData:x,refreshProfile:p,clearProfile:A}};exports.a = W; exports.b = Z; exports.c = q; exports.d = f; exports.e = z; exports.f = Q; exports.g = X; exports.h = te; exports.i = mi; exports.j = Re; exports.k = Ti; exports.l = Si;