@nocios/crudify-ui 4.4.4 → 4.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import{a as _,b as K,c as $,d as B,e as Z,f as V,g as W,h as Ie,i as he,j as Ae,k as Pe,l as Re,m as Ce,n as xe,o as ve}from"./chunk-5OTFPH6X.mjs";import{a as Te,b as Se,c as Ee,d as Le}from"./chunk-UDCAHVY3.mjs";import{a as b,b as q,c as Y,d as J,e as d,f as ie,g as ne,h as se,i as ae,j as f,k as le,l as me,m as ze}from"./chunk-CQM5LDK7.mjs";import{a as we,b as be}from"./chunk-T2CPA46I.mjs";import{a as ce,b as ue,c as pe,d as de,e as fe,f as ye,g as ge}from"./chunk-BJ6PIVZR.mjs";import{a as z,b as Q,c as X,d as j,e as ee,h as te,i as re,j as oe}from"./chunk-5JKS55SE.mjs";import{default as Bi}from"@nocios/crudify-browser";export*from"@nocios/crudify-browser";import{useMemo as Me}from"react";import{ThemeProvider as Ne,createTheme as ke,CssBaseline as Oe}from"@mui/material";import{jsx as De,jsxs as Ge}from"react/jsx-runtime";var Ue=(e={})=>{try{let i=z("theme");if(i){let t=JSON.parse(decodeURIComponent(i));return{...e,...t}}}catch(i){console.warn("Error parsing theme from cookie:",i)}return e};function He({children:e,defaultTheme:i={},disableCssBaseline:t=!1}){let r=Me(()=>{let n=Ue(i);return ke(n)},[i]);return Ge(Ne,{theme:r,children:[!t&&De(Oe,{}),e]})}import{Navigate as Ze,useLocation as Ve}from"react-router-dom";import{Fragment as Ke,jsx as h,jsxs as L}from"react/jsx-runtime";var Fe={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},_e=()=>h("style",{children:`
1
+ import{a as $,b as _,c as B,d as Z,e as V,f as W,g as q,h as Ie,i as Ae,j as Pe,k as Re,l as Ce,m as xe,n as ze,o as Te}from"./chunk-W2W2FN5C.mjs";import{a as Se,b as be,c as Ee,d as Me}from"./chunk-6PJ3PR6X.mjs";import{a as w,b as Y,c as J,d as Q,e as f,f as te,g as se,h as ae,i as le,j as y,k as ce,l as he,m as ve}from"./chunk-65TCHVT6.mjs";import{a as we,b as Le}from"./chunk-T2CPA46I.mjs";import{a as ue,b as pe,c as de,d as fe,e as ye,f as ge,g as me}from"./chunk-BJ6PIVZR.mjs";import{a as z,b as X,c as j,d as ee,e as ie,h as re,i as oe,j as ne,k as L}from"./chunk-AWJ3DQQT.mjs";import{default as Vi}from"@nocios/crudify-browser";export*from"@nocios/crudify-browser";import{useMemo as Ne}from"react";import{ThemeProvider as ke,createTheme as Oe,CssBaseline as He}from"@mui/material";import{jsx as Ge,jsxs as Ke}from"react/jsx-runtime";var Ue=(e={})=>{try{let i=z("theme");if(i){let t=JSON.parse(decodeURIComponent(i));return{...e,...t}}}catch(i){console.warn("Error parsing theme from cookie:",i)}return e};function De({children:e,defaultTheme:i={},disableCssBaseline:t=!1}){let r=Ne(()=>{let n=Ue(i);return Oe(n)},[i]);return Ke(ke,{theme:r,children:[!t&&Ge(He,{}),e]})}import{Navigate as Ve,useLocation as We}from"react-router-dom";import{Fragment as _e,jsx as A,jsxs as M}from"react/jsx-runtime";var Fe={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},$e=()=>A("style",{children:`
2
2
  @keyframes spin {
3
3
  0% { transform: rotate(0deg); }
4
4
  100% { transform: rotate(360deg); }
5
5
  }
6
- `});function v({stage:e="loading",message:i}){let r=i||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return L(Ke,{children:[h(_e,{}),L("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[h("div",{style:Fe}),h("p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:r})]})]})}var $e=/^[a-zA-Z0-9\-_./\?=&%#]+$/,Be=[/^https?:\/\//i,/^ftp:\/\//i,/^\/\//,/javascript:/i,/data:/i,/vbscript:/i,/about:/i,/\.\.\//,/\.\.\\/,/%2e%2e%2f/i,/%2e%2e%5c/i,/%2f%2f/i,/%5c%5c/i,/[\x00-\x1f\x7f-\x9f]/,/\\/],A=(e,i="/")=>{if(!e||typeof e!="string")return i;let t=e.trim();if(!t)return i;if(!t.startsWith("/"))return console.warn("\u{1F6A8} Open redirect blocked (relative path):",e),i;if(!$e.test(t))return console.warn("\u{1F6A8} Open redirect blocked (invalid characters):",e),i;let r=t.toLowerCase();for(let o of Be)if(o.test(r))return console.warn("\u{1F6A8} Open redirect blocked (dangerous pattern):",e),i;let n=t.split("?")[0].split("/").filter(Boolean);if(n.length===0)return t;for(let o of n)if(o===".."||o.includes(":")||o.length>100)return console.warn("\u{1F6A8} Open redirect blocked (suspicious path part):",o),i;return t},T=(e,i="/")=>{try{let r=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!r)return i;let n=decodeURIComponent(r);return A(n,i)}catch(t){return console.warn("\u{1F6A8} Error parsing redirect parameter:",t),i}};import{Fragment as M,jsx as P}from"react/jsx-runtime";function N({children:e,loadingComponent:i,loginPath:t="/login"}){let{isAuthenticated:r,isLoading:n,isInitialized:o,tokens:s,error:c}=f(),u=Ve();if(!o||n)return P(M,{children:i||P(v,{stage:"validating-session"})});let p=r&&s?.accessToken&&s.accessToken.length>0;if(c||!r||!p){s&&(!s.accessToken||s.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let g=u.pathname+u.search,I=A(g),m=encodeURIComponent(I);return P(Ze,{to:`${t}?redirect=${m}`,replace:!0})}return P(M,{children:e})}import{Navigate as We,useLocation as qe}from"react-router-dom";import{Fragment as Ye,jsx as k}from"react/jsx-runtime";function O({children:e,redirectTo:i="/"}){let{isAuthenticated:t}=f(),r=qe();if(t){let n=new URLSearchParams(r.search),o=T(n,i);return k(We,{to:o,replace:!0})}return k(Ye,{children:e})}import S from"@nocios/crudify-browser";var R=class e{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return e.instance||(e.instance=new e),e.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:t,publicApiKey:r,env:n,enableLogging:o,requestedBy:s}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==r&&console.warn(`[CrudifyInitialization] ${s} attempted to initialize with different key. Already initialized with key: ${this.state.publicApiKey?.slice(0,10)}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return o&&console.log(`[CrudifyInitialization] ${s} waiting for ongoing initialization...`),this.initializationPromise;if(t==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(o&&console.log(`[CrudifyInitialization] ${s} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(s),await this.waitForHighPriorityOrTimeout(o),this.waitingForHighPriority.delete(s),this.getState().status==="INITIALIZED"){o&&console.log(`[CrudifyInitialization] ${s} found initialization completed by HIGH priority`);return}o&&console.warn(`[CrudifyInitialization] ${s} timeout waiting for HIGH priority, initializing with LOW priority`)}t==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(console.warn(`[CrudifyInitialization] HIGH priority request from ${s} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),o&&console.log(`[CrudifyInitialization] ${s} starting initialization (${t} priority)...`),this.state.status="INITIALIZING",this.state.priority=t,this.state.initializedBy=s,this.initializationPromise=this.performInitialization(r,n,o);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=r,this.state.env=n,this.state.error=null,o&&console.log(`[CrudifyInitialization] \u2705 Successfully initialized by ${s} (${t} priority)`)}catch(c){throw this.state.status="ERROR",this.state.error=c instanceof Error?c:new Error(String(c)),this.initializationPromise=null,console.error(`[CrudifyInitialization] \u274C Initialization failed for ${s}:`,c),c}}async waitForHighPriorityOrTimeout(i){return new Promise(t=>{let n=0,o=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(o),t();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(o),i&&console.log(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),t())},10)})}async performInitialization(i,t,r){window.__CRUDIFY_DEBUG_INIT_MANAGER={publicApiKey:i.substring(0,10)+"...",env:t,enableLogging:r,timestamp:new Date().toISOString()};let n=S.getTokenData();if(n&&n.endpoint){r&&console.log("[CrudifyInitialization] SDK already initialized externally");return}S.config(t);let o=r?"debug":"none",s=await S.init(i,o);if(s.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(s.errors||"Unknown error")}`)}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},C=R.getInstance();import{createContext as Je,useContext as Qe,useEffect as Xe,useRef as U,useState as E}from"react";import{Fragment as ii,jsx as H}from"react/jsx-runtime";var D=Je(void 0),je=({config:e,children:i,fallback:t=null,onInitialized:r,onError:n})=>{let[o,s]=E(!1),[c,u]=E(!1),[p,g]=E(null),I=U(!1),m=U(!1);Xe(()=>{I.current||(C.registerHighPriorityInitializer(),I.current=!0),m.current||(m.current=!0,(async()=>{u(!0),g(null);try{await C.initialize({priority:"HIGH",publicApiKey:e.publicApiKey,env:e.env||"stg",enableLogging:e.enableLogging,requestedBy:"CrudifyInitializer"}),s(!0),u(!1),r&&r()}catch(x){let w=x instanceof Error?x:new Error(String(x));g(w),u(!1),n&&n(w)}})())},[e.publicApiKey,e.env,e.enableLogging,r,n]);let F={isInitialized:o,isInitializing:c,error:p};return c&&t?H(ii,{children:t}):(p&&console.error("[CrudifyInitializer] Initialization failed:",p),H(D.Provider,{value:F,children:i}))},ei=()=>{let e=Qe(D);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};import a from"@nocios/crudify-admin";var G=!1,y=null;async function ti(){let i=d.getInstance().getTokenInfo(),t=i?.apiEndpointAdmin,r=i?.apiKeyEndpointAdmin;return t&&r?{apiUrl:t,apiKey:r}:b.waitForCredentials()}async function ri(){if(!G)return y||(y=(async()=>{try{let e=d.getInstance(),{apiUrl:i,apiKey:t}=await ti();a.init({url:i,apiKey:t,getAdditionalHeaders:()=>{let r=e.getTokenInfo();return r?.crudifyTokens?.accessToken?{Authorization:`Bearer ${r.crudifyTokens.accessToken}`}:{}}}),G=!0}catch(e){throw y=null,console.error("[crudifyAdminWrapper] Initialization failed:",e),e}})(),y)}async function l(e){try{await ri();let i=await e();return!i.success&&i.errors?.includes("401")?await d.getInstance().refreshTokens()?await e():(console.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),i):i}catch(i){return console.error("[crudifyAdmin] Operation error:",i),{success:!1,errors:i instanceof Error?i.message:"Unknown error"}}}var oi={listModules:()=>l(()=>a.listModules()),getModule:e=>l(()=>a.getModule(e)),createModule:e=>l(()=>a.createModule(e)),editModule:(e,i)=>l(()=>a.editModule(e,i)),deleteModule:e=>l(()=>a.deleteModule(e)),activateModule:e=>l(()=>a.activateModule(e)),deactivateModule:e=>l(()=>a.deactivateModule(e)),getModuleVersions:e=>l(()=>a.getModuleVersions(e)),listActions:e=>l(()=>a.listActions(e)),getAction:e=>l(()=>a.getAction(e)),createAction:e=>l(()=>a.createAction(e)),editAction:(e,i)=>l(()=>a.editAction(e,i)),deleteAction:e=>l(()=>a.deleteAction(e)),activateAction:e=>l(()=>a.activateAction(e)),deactivateAction:e=>l(()=>a.deactivateAction(e)),getActionVersions:e=>l(()=>a.getActionVersions(e))};export{O as AuthRoute,_ as CRITICAL_TRANSLATIONS,ve as CrudiaAutoGenerate,R as CrudifyInitializationManager,je as CrudifyInitializer,Ie as CrudifyLogin,q as CrudifyProvider,He as CrudifyThemeProvider,ce as ERROR_CODES,ue as ERROR_SEVERITY_MAP,ne as GlobalNotificationProvider,Ce as LoginComponent,Ae as POLICY_ACTIONS,Pe as PREFERRED_POLICY_ORDER,Re as Policies,N as ProtectedRoute,le as SessionDebugInfo,v as SessionLoadingScreen,d as SessionManager,ae as SessionProvider,xe as SessionStatus,J as TokenStorage,B as TranslationService,V as TranslationsProvider,he as UserProfileDisplay,ee as createErrorTranslator,Bi as crudify,oi as crudifyAdmin,C as crudifyInitManager,te as decodeJwtSafely,T as extractSafeRedirectFromUrl,z as getCookie,K as getCriticalLanguages,$ as getCriticalTranslations,re as getCurrentUserEmail,fe as getErrorMessage,ge as handleCrudifyError,oe as isTokenExpired,pe as parseApiError,ye as parseJavaScriptError,de as parseTransactionError,be as secureLocalStorage,we as secureSessionStorage,j as translateError,Q as translateErrorCode,X as translateErrorCodes,Z as translationService,Se as useAuth,ze as useAutoGenerate,Y as useCrudify,ei as useCrudifyInitializer,Le as useCrudifyWithNotifications,Ee as useData,se as useGlobalNotification,ie as useSession,f as useSessionContext,W as useTranslations,Te as useUserData,me as useUserProfile,A as validateInternalRedirect};
6
+ `});function v({stage:e="loading",message:i}){let r=i||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return M(_e,{children:[A($e,{}),M("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[A("div",{style:Fe}),A("p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:r})]})]})}var Be=/^[a-zA-Z0-9\-_./\?=&%#]+$/,Ze=[/^https?:\/\//i,/^ftp:\/\//i,/^\/\//,/javascript:/i,/data:/i,/vbscript:/i,/about:/i,/\.\.\//,/\.\.\\/,/%2e%2e%2f/i,/%2e%2e%5c/i,/%2f%2f/i,/%5c%5c/i,/[\x00-\x1f\x7f-\x9f]/,/\\/],P=(e,i="/")=>{if(!e||typeof e!="string")return i;let t=e.trim();if(!t)return i;if(!t.startsWith("/"))return console.warn("\u{1F6A8} Open redirect blocked (relative path):",e),i;if(!Be.test(t))return console.warn("\u{1F6A8} Open redirect blocked (invalid characters):",e),i;let r=t.toLowerCase();for(let o of Ze)if(o.test(r))return console.warn("\u{1F6A8} Open redirect blocked (dangerous pattern):",e),i;let n=t.split("?")[0].split("/").filter(Boolean);if(n.length===0)return t;for(let o of n)if(o===".."||o.includes(":")||o.length>100)return console.warn("\u{1F6A8} Open redirect blocked (suspicious path part):",o),i;return t},T=(e,i="/")=>{try{let r=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!r)return i;let n=decodeURIComponent(r);return P(n,i)}catch(t){return console.warn("\u{1F6A8} Error parsing redirect parameter:",t),i}};import{Fragment as N,jsx as R}from"react/jsx-runtime";function k({children:e,loadingComponent:i,loginPath:t="/login"}){let{isAuthenticated:r,isLoading:n,isInitialized:o,tokens:s,error:c}=y(),p=We();if(!o||n)return R(N,{children:i||R(v,{stage:"validating-session"})});let d=r&&s?.accessToken&&s.accessToken.length>0;if(c||!r||!d){s&&(!s.accessToken||s.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let m=p.pathname+p.search,I=P(m),h=encodeURIComponent(I);return R(Ve,{to:`${t}?redirect=${h}`,replace:!0})}return R(N,{children:e})}import{Navigate as qe,useLocation as Ye}from"react-router-dom";import{Fragment as Je,jsx as O}from"react/jsx-runtime";function H({children:e,redirectTo:i="/"}){let{isAuthenticated:t}=y(),r=Ye();if(t){let n=new URLSearchParams(r.search),o=T(n,i);return O(qe,{to:o,replace:!0})}return O(Je,{children:e})}import S from"@nocios/crudify-browser";var C=class e{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return e.instance||(e.instance=new e),e.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:t,publicApiKey:r,env:n,enableLogging:o,requestedBy:s}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==r&&console.warn(`[CrudifyInitialization] ${s} attempted to initialize with different key. Already initialized with key: ${this.state.publicApiKey?.slice(0,10)}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return o&&console.log(`[CrudifyInitialization] ${s} waiting for ongoing initialization...`),this.initializationPromise;if(t==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(o&&console.log(`[CrudifyInitialization] ${s} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(s),await this.waitForHighPriorityOrTimeout(o),this.waitingForHighPriority.delete(s),this.getState().status==="INITIALIZED"){o&&console.log(`[CrudifyInitialization] ${s} found initialization completed by HIGH priority`);return}o&&console.warn(`[CrudifyInitialization] ${s} timeout waiting for HIGH priority, initializing with LOW priority`)}t==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(console.warn(`[CrudifyInitialization] HIGH priority request from ${s} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),o&&console.log(`[CrudifyInitialization] ${s} starting initialization (${t} priority)...`),this.state.status="INITIALIZING",this.state.priority=t,this.state.initializedBy=s,this.initializationPromise=this.performInitialization(r,n,o);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=r,this.state.env=n,this.state.error=null,o&&console.log(`[CrudifyInitialization] \u2705 Successfully initialized by ${s} (${t} priority)`)}catch(c){throw this.state.status="ERROR",this.state.error=c instanceof Error?c:new Error(String(c)),this.initializationPromise=null,console.error(`[CrudifyInitialization] \u274C Initialization failed for ${s}:`,c),c}}async waitForHighPriorityOrTimeout(i){return new Promise(t=>{let n=0,o=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(o),t();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(o),i&&console.log(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),t())},10)})}async performInitialization(i,t,r){let n=S.getTokenData();if(n&&n.endpoint){r&&console.log("[CrudifyInitialization] SDK already initialized externally");return}S.config(t);let o=r?"debug":"none",s=await S.init(i,o);if(s.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(s.errors||"Unknown error")}`)}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},x=C.getInstance();import{createContext as Qe,useContext as Xe,useEffect as je,useRef as U,useState as b}from"react";import{Fragment as ti,jsx as D}from"react/jsx-runtime";var G=Qe(void 0),ei=({config:e,children:i,fallback:t=null,onInitialized:r,onError:n})=>{let[o,s]=b(!1),[c,p]=b(!1),[d,m]=b(null),I=U(!1),h=U(!1);je(()=>{I.current||(x.registerHighPriorityInitializer(),I.current=!0),h.current||(h.current=!0,(async()=>{p(!0),m(null);try{let u=L({publicApiKey:e.publicApiKey,env:e.env,enableDebug:e.enableLogging});if(!u.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");await x.initialize({priority:"HIGH",publicApiKey:u.publicApiKey,env:u.env||"prod",enableLogging:e.enableLogging,requestedBy:"CrudifyInitializer"}),s(!0),p(!1),r&&r()}catch(u){let E=u instanceof Error?u:new Error(String(u));m(E),p(!1),n&&n(E)}})())},[e.publicApiKey,e.env,e.enableLogging,r,n]);let F={isInitialized:o,isInitializing:c,error:d};return c&&t?D(ti,{children:t}):(d&&console.error("[CrudifyInitializer] Initialization failed:",d),D(G.Provider,{value:F,children:i}))},ii=()=>{let e=Xe(G);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};import a from"@nocios/crudify-admin";var K=!1,g=null;async function ri(){let i=f.getInstance().getTokenInfo(),t=i?.apiEndpointAdmin,r=i?.apiKeyEndpointAdmin;return t&&r?{apiUrl:t,apiKey:r}:w.waitForCredentials()}async function oi(){if(!K)return g||(g=(async()=>{try{let e=f.getInstance(),{apiUrl:i,apiKey:t}=await ri();a.init({url:i,apiKey:t,getAdditionalHeaders:()=>{let r=e.getTokenInfo();return r?.crudifyTokens?.accessToken?{Authorization:`Bearer ${r.crudifyTokens.accessToken}`}:{}}}),K=!0}catch(e){throw g=null,console.error("[crudifyAdminWrapper] Initialization failed:",e),e}})(),g)}async function l(e){try{await oi();let i=await e();return!i.success&&i.errors?.includes("401")?await f.getInstance().refreshTokens()?await e():(console.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),i):i}catch(i){return console.error("[crudifyAdmin] Operation error:",i),{success:!1,errors:i instanceof Error?i.message:"Unknown error"}}}var ni={listModules:()=>l(()=>a.listModules()),getModule:e=>l(()=>a.getModule(e)),createModule:e=>l(()=>a.createModule(e)),editModule:(e,i)=>l(()=>a.editModule(e,i)),deleteModule:e=>l(()=>a.deleteModule(e)),activateModule:e=>l(()=>a.activateModule(e)),deactivateModule:e=>l(()=>a.deactivateModule(e)),getModuleVersions:e=>l(()=>a.getModuleVersions(e)),listActions:e=>l(()=>a.listActions(e)),getAction:e=>l(()=>a.getAction(e)),createAction:e=>l(()=>a.createAction(e)),editAction:(e,i)=>l(()=>a.editAction(e,i)),deleteAction:e=>l(()=>a.deleteAction(e)),activateAction:e=>l(()=>a.activateAction(e)),deactivateAction:e=>l(()=>a.deactivateAction(e)),getActionVersions:e=>l(()=>a.getActionVersions(e))};export{H as AuthRoute,$ as CRITICAL_TRANSLATIONS,Te as CrudiaAutoGenerate,C as CrudifyInitializationManager,ei as CrudifyInitializer,Ie as CrudifyLogin,Y as CrudifyProvider,De as CrudifyThemeProvider,ue as ERROR_CODES,pe as ERROR_SEVERITY_MAP,se as GlobalNotificationProvider,xe as LoginComponent,Pe as POLICY_ACTIONS,Re as PREFERRED_POLICY_ORDER,Ce as Policies,k as ProtectedRoute,ce as SessionDebugInfo,v as SessionLoadingScreen,f as SessionManager,le as SessionProvider,ze as SessionStatus,Q as TokenStorage,Z as TranslationService,W as TranslationsProvider,Ae as UserProfileDisplay,ie as createErrorTranslator,Vi as crudify,ni as crudifyAdmin,x as crudifyInitManager,re as decodeJwtSafely,T as extractSafeRedirectFromUrl,z as getCookie,_ as getCriticalLanguages,B as getCriticalTranslations,oe as getCurrentUserEmail,ye as getErrorMessage,me as handleCrudifyError,ne as isTokenExpired,de as parseApiError,ge as parseJavaScriptError,fe as parseTransactionError,Le as secureLocalStorage,we as secureSessionStorage,ee as translateError,X as translateErrorCode,j as translateErrorCodes,V as translationService,be as useAuth,ve as useAutoGenerate,J as useCrudify,ii as useCrudifyInitializer,Me as useCrudifyWithNotifications,Ee as useData,ae as useGlobalNotification,te as useSession,y as useSessionContext,q as useTranslations,Se as useUserData,he as useUserProfile,P as validateInternalRedirect};
package/dist/utils.d.mts CHANGED
@@ -1,6 +1,43 @@
1
1
  export { E as ERROR_CODES, j as ERROR_SEVERITY_MAP, n as ErrorCode, o as ErrorSeverity, q as ErrorTranslationConfig, P as ParsedError, m as createErrorTranslator, d as decodeJwtSafely, a as getCookie, g as getCurrentUserEmail, f as getErrorMessage, h as handleCrudifyError, i as isTokenExpired, p as parseApiError, e as parseJavaScriptError, c as parseTransactionError, b as secureLocalStorage, s as secureSessionStorage, l as translateError, t as translateErrorCode, k as translateErrorCodes } from './errorTranslation-DEn4aqs6.mjs';
2
2
  import './api-Djqihi4n.mjs';
3
3
 
4
+ /**
5
+ * Sistema centralizado de resolución de configuración para npm-crudify-ui
6
+ * Prioridad: Props explícitas > Cookies (producción) > Error (ninguno)
7
+ */
8
+ type CrudifyEnvironment = "dev" | "stg" | "api" | "prod";
9
+ interface ResolvedConfig {
10
+ publicApiKey?: string;
11
+ env?: CrudifyEnvironment;
12
+ appName?: string;
13
+ logo?: string;
14
+ loginActions?: string[];
15
+ sections?: string[];
16
+ theme?: Record<string, any>;
17
+ configSource: "props" | "cookies" | "none";
18
+ }
19
+ interface ConfigResolverOptions {
20
+ publicApiKey?: string;
21
+ env?: CrudifyEnvironment;
22
+ appName?: string;
23
+ logo?: string;
24
+ loginActions?: string[];
25
+ sections?: string[];
26
+ enableDebug?: boolean;
27
+ }
28
+ /**
29
+ * Resuelve la configuración de Crudify con la siguiente prioridad:
30
+ * 1. Cookies (para producción con lambda multitenancy) - MÁXIMA PRIORIDAD
31
+ * 2. Props explícitas (para desarrollo local o cuando no hay cookies)
32
+ * 3. Ninguno (error - falta configuración)
33
+ */
34
+ declare function resolveConfig(options?: ConfigResolverOptions): ResolvedConfig;
35
+ /**
36
+ * Hook de React para usar el config resolver
37
+ * Útil cuando necesitas la config en un componente
38
+ */
39
+ declare function useResolvedConfig(options?: ConfigResolverOptions): ResolvedConfig;
40
+
4
41
  /**
5
42
  * Event Bus para coordinar acciones de autenticación
6
43
  * Previene race conditions y asegura respuesta única a errores
@@ -126,4 +163,4 @@ declare class NavigationTracker {
126
163
  isActive(): boolean;
127
164
  }
128
165
 
129
- export { type AuthEvent, type AuthEventDetails, type AuthEventType, NavigationTracker, authEventBus };
166
+ export { type AuthEvent, type AuthEventDetails, type AuthEventType, type ConfigResolverOptions, type CrudifyEnvironment, NavigationTracker, type ResolvedConfig, authEventBus, resolveConfig, useResolvedConfig };
package/dist/utils.d.ts CHANGED
@@ -1,6 +1,43 @@
1
1
  export { E as ERROR_CODES, j as ERROR_SEVERITY_MAP, n as ErrorCode, o as ErrorSeverity, q as ErrorTranslationConfig, P as ParsedError, m as createErrorTranslator, d as decodeJwtSafely, a as getCookie, g as getCurrentUserEmail, f as getErrorMessage, h as handleCrudifyError, i as isTokenExpired, p as parseApiError, e as parseJavaScriptError, c as parseTransactionError, b as secureLocalStorage, s as secureSessionStorage, l as translateError, t as translateErrorCode, k as translateErrorCodes } from './errorTranslation-DdqZg8JD.js';
2
2
  import './api-Djqihi4n.js';
3
3
 
4
+ /**
5
+ * Sistema centralizado de resolución de configuración para npm-crudify-ui
6
+ * Prioridad: Props explícitas > Cookies (producción) > Error (ninguno)
7
+ */
8
+ type CrudifyEnvironment = "dev" | "stg" | "api" | "prod";
9
+ interface ResolvedConfig {
10
+ publicApiKey?: string;
11
+ env?: CrudifyEnvironment;
12
+ appName?: string;
13
+ logo?: string;
14
+ loginActions?: string[];
15
+ sections?: string[];
16
+ theme?: Record<string, any>;
17
+ configSource: "props" | "cookies" | "none";
18
+ }
19
+ interface ConfigResolverOptions {
20
+ publicApiKey?: string;
21
+ env?: CrudifyEnvironment;
22
+ appName?: string;
23
+ logo?: string;
24
+ loginActions?: string[];
25
+ sections?: string[];
26
+ enableDebug?: boolean;
27
+ }
28
+ /**
29
+ * Resuelve la configuración de Crudify con la siguiente prioridad:
30
+ * 1. Cookies (para producción con lambda multitenancy) - MÁXIMA PRIORIDAD
31
+ * 2. Props explícitas (para desarrollo local o cuando no hay cookies)
32
+ * 3. Ninguno (error - falta configuración)
33
+ */
34
+ declare function resolveConfig(options?: ConfigResolverOptions): ResolvedConfig;
35
+ /**
36
+ * Hook de React para usar el config resolver
37
+ * Útil cuando necesitas la config en un componente
38
+ */
39
+ declare function useResolvedConfig(options?: ConfigResolverOptions): ResolvedConfig;
40
+
4
41
  /**
5
42
  * Event Bus para coordinar acciones de autenticación
6
43
  * Previene race conditions y asegura respuesta única a errores
@@ -126,4 +163,4 @@ declare class NavigationTracker {
126
163
  isActive(): boolean;
127
164
  }
128
165
 
129
- export { type AuthEvent, type AuthEventDetails, type AuthEventType, NavigationTracker, authEventBus };
166
+ export { type AuthEvent, type AuthEventDetails, type AuthEventType, type ConfigResolverOptions, type CrudifyEnvironment, NavigationTracker, type ResolvedConfig, authEventBus, resolveConfig, useResolvedConfig };
package/dist/utils.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkNNY4A73Vjs = require('./chunk-NNY4A73V.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunkAT74WV5Wjs = require('./chunk-AT74WV5W.js');exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.NavigationTracker = _chunkAT74WV5Wjs.g; exports.authEventBus = _chunkAT74WV5Wjs.f; exports.createErrorTranslator = _chunkAT74WV5Wjs.e; exports.decodeJwtSafely = _chunkAT74WV5Wjs.h; exports.getCookie = _chunkAT74WV5Wjs.a; exports.getCurrentUserEmail = _chunkAT74WV5Wjs.i; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunkAT74WV5Wjs.j; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.secureLocalStorage = _chunkNNY4A73Vjs.b; exports.secureSessionStorage = _chunkNNY4A73Vjs.a; exports.translateError = _chunkAT74WV5Wjs.d; exports.translateErrorCode = _chunkAT74WV5Wjs.b; exports.translateErrorCodes = _chunkAT74WV5Wjs.c;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkNNY4A73Vjs = require('./chunk-NNY4A73V.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunk5KZLO3WFjs = require('./chunk-5KZLO3WF.js');exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.NavigationTracker = _chunk5KZLO3WFjs.g; exports.authEventBus = _chunk5KZLO3WFjs.f; exports.createErrorTranslator = _chunk5KZLO3WFjs.e; exports.decodeJwtSafely = _chunk5KZLO3WFjs.h; exports.getCookie = _chunk5KZLO3WFjs.a; exports.getCurrentUserEmail = _chunk5KZLO3WFjs.i; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunk5KZLO3WFjs.j; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.resolveConfig = _chunk5KZLO3WFjs.k; exports.secureLocalStorage = _chunkNNY4A73Vjs.b; exports.secureSessionStorage = _chunkNNY4A73Vjs.a; exports.translateError = _chunk5KZLO3WFjs.d; exports.translateErrorCode = _chunk5KZLO3WFjs.b; exports.translateErrorCodes = _chunk5KZLO3WFjs.c; exports.useResolvedConfig = _chunk5KZLO3WFjs.l;
package/dist/utils.mjs CHANGED
@@ -1 +1 @@
1
- import{a as g,b as v}from"./chunk-T2CPA46I.mjs";import{a as f,b as l,c as m,d as u,e as x,f as d,g as c}from"./chunk-BJ6PIVZR.mjs";import{a as r,b as e,c as o,d as t,e as a,f as E,g as s,h as n,i as p,j as i}from"./chunk-5JKS55SE.mjs";export{f as ERROR_CODES,l as ERROR_SEVERITY_MAP,s as NavigationTracker,E as authEventBus,a as createErrorTranslator,n as decodeJwtSafely,r as getCookie,p as getCurrentUserEmail,x as getErrorMessage,c as handleCrudifyError,i as isTokenExpired,m as parseApiError,d as parseJavaScriptError,u as parseTransactionError,v as secureLocalStorage,g as secureSessionStorage,t as translateError,e as translateErrorCode,o as translateErrorCodes};
1
+ import{a as R,b as c}from"./chunk-T2CPA46I.mjs";import{a as m,b as v,c as d,d as g,e as u,f as x,g as C}from"./chunk-BJ6PIVZR.mjs";import{a as r,b as e,c as o,d as t,e as a,f as n,g as s,h as E,i,j as p,k as f,l}from"./chunk-AWJ3DQQT.mjs";export{m as ERROR_CODES,v as ERROR_SEVERITY_MAP,s as NavigationTracker,n as authEventBus,a as createErrorTranslator,E as decodeJwtSafely,r as getCookie,i as getCurrentUserEmail,u as getErrorMessage,C as handleCrudifyError,p as isTokenExpired,d as parseApiError,x as parseJavaScriptError,g as parseTransactionError,f as resolveConfig,c as secureLocalStorage,R as secureSessionStorage,t as translateError,e as translateErrorCode,o as translateErrorCodes,l as useResolvedConfig};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocios/crudify-ui",
3
- "version": "4.4.4",
3
+ "version": "4.4.8",
4
4
  "description": "Biblioteca de componentes UI para Crudify",
5
5
  "author": "Nocios",
6
6
  "license": "MIT",
@@ -40,7 +40,7 @@
40
40
  },
41
41
  "dependencies": {
42
42
  "@nocios/crudify-admin": "^2.1.0",
43
- "@nocios/crudify-browser": "^4.1.2",
43
+ "@nocios/crudify-browser": "^4.1.6",
44
44
  "crypto-js": "^4.2.0",
45
45
  "dompurify": "^3.2.7",
46
46
  "uuid": "^13.0.0"
@@ -1 +0,0 @@
1
- var I=t=>{let e=document.cookie.match(new RegExp("(^|;)\\s*"+t+"=([^;]+)"));return e?e[2]:null};var T=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],v={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},y={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function c(t,e){let{translateFn:r,currentLanguage:n,enableDebug:s}=e;s&&console.log(`\u{1F50D} [ErrorTranslation] Translating error code: ${t} (lang: ${n||"unknown"})`);let i=t.toUpperCase(),u=v[i],d=T.map(o=>o.replace("{category}",u||"general").replace("{code}",i));s&&console.log("\u{1F511} [ErrorTranslation] Searching keys:",d);for(let o of d){let l=r(o);if(s&&console.log(`\u{1F50D} [ErrorTranslation] Checking key: "${o}" -> result: "${l}" (same as key: ${l===o})`),l&&l!==o)return s&&console.log(`\u2705 [ErrorTranslation] Found translation at key: ${o} = "${l}"`),l}let g=y[i];if(g)return s&&console.log(`\u{1F504} [ErrorTranslation] Using default message: "${g}"`),g;let h=i.replace(/_/g," ").toLowerCase().replace(/\b\w/g,o=>o.toUpperCase());return s&&console.log(`\u26A0\uFE0F [ErrorTranslation] No translation found, using friendly code: "${h}"`),h}function R(t,e){return t.map(r=>c(r,e))}function m(t,e){let{enableDebug:r}=e;r&&console.log("\u{1F50D} [ErrorTranslation] Translating error:",t);let n=c(t.code,e);return n!==t.code.toUpperCase()&&n!==t.code?(r&&console.log(`\u2705 [ErrorTranslation] Using hierarchical translation: "${n}"`),t.field?`${t.field}: ${n}`:n):t.message&&!t.message.includes("Error:")&&t.message.length>0&&t.message!==t.code?(r&&console.log(`\u{1F504} [ErrorTranslation] No hierarchical translation found, using API message: "${t.message}"`),t.message):(r&&console.log(`\u26A0\uFE0F [ErrorTranslation] Using final fallback: "${n}"`),t.field?`${t.field}: ${n}`:n)}function A(t,e={}){let r={translateFn:t,currentLanguage:e.currentLanguage,enableDebug:e.enableDebug||!1};return{translateErrorCode:n=>c(n,r),translateErrorCodes:n=>R(n,r),translateError:n=>m(n,r),translateApiError:n=>n?.data?.response?.status?c(n.data.response.status,r):n?.status?c(n.status,r):n?.code?c(n.code,r):"Unknown error"}}var E=class t{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return t.instance||(t.instance=new t),t.instance}emit(e,r){let n=Date.now();if(this.isHandlingAuthError&&this.lastEventType===e&&n-this.lastErrorTime<this.DEBOUNCE_TIME){console.log(`\u{1F6AB} AuthEventBus: Ignoring duplicate ${e} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=n,this.lastEventType=e,console.log(`\u{1F4E2} AuthEventBus: Emitting ${e} event`,r);let s={type:e,details:r,timestamp:n};this.listeners.forEach(i=>{try{i(s)}catch(u){console.error("AuthEventBus: Error in listener",u)}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},O=E.getInstance();var a=class a{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return a.instance||(a.instance=new a),a.instance}subscribe(e){return this.listeners.add(e),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(e)}}unsubscribe(e){this.listeners.delete(e),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let e=this;window.history.pushState=function(...r){let n=e.originalPushState.apply(this,r);return e.notifyListeners(),n},window.history.replaceState=function(...r){let n=e.originalReplaceState.apply(this,r);return e.notifyListeners(),n},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(e=>{try{e()}catch(r){console.error("NavigationTracker: Error in navigation listener",r)}})}static reset(){a.instance?.isPatched&&a.instance.removePatches(),a.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};a.instance=null;var p=a;var f=t=>{try{let e=t.split(".");if(e.length!==3)return console.warn("Invalid JWT format: token must have 3 parts"),null;let r=e[1],n=r+"=".repeat((4-r.length%4)%4);return JSON.parse(atob(n))}catch(e){return console.warn("Failed to decode JWT token:",e),null}},_=()=>{try{let t=null;if(t=sessionStorage.getItem("authToken"),console.log("\u{1F50D} getCurrentUserEmail - authToken:",t?`${t.substring(0,20)}...`:null),t||(t=sessionStorage.getItem("token"),console.log("\u{1F50D} getCurrentUserEmail - token:",t?`${t.substring(0,20)}...`:null)),t||(t=localStorage.getItem("authToken")||localStorage.getItem("token"),console.log("\u{1F50D} getCurrentUserEmail - localStorage:",t?`${t.substring(0,20)}...`:null)),!t)return console.warn("\u{1F50D} getCurrentUserEmail - No token found in any storage"),null;let e=f(t);if(!e)return console.warn("\u{1F50D} getCurrentUserEmail - Failed to decode token"),null;let r=e.email||e["cognito:username"]||null;return console.log("\u{1F50D} getCurrentUserEmail - Extracted email:",r),r}catch(t){return console.warn("Failed to get current user email:",t),null}},D=t=>{try{let e=f(t);if(!e||!e.exp)return!0;let r=Math.floor(Date.now()/1e3);return e.exp<r}catch{return!0}};export{I as a,c as b,R as c,m as d,A as e,O as f,p as g,f as h,_ as i,D as j};
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 I=t=>{let e=document.cookie.match(new RegExp("(^|;)\\s*"+t+"=([^;]+)"));return e?e[2]:null};var T=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],v={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},y={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function c(t,e){let{translateFn:r,currentLanguage:n,enableDebug:s}=e;s&&console.log(`\u{1F50D} [ErrorTranslation] Translating error code: ${t} (lang: ${n||"unknown"})`);let i=t.toUpperCase(),u=v[i],d=T.map(o=>o.replace("{category}",u||"general").replace("{code}",i));s&&console.log("\u{1F511} [ErrorTranslation] Searching keys:",d);for(let o of d){let l=r(o);if(s&&console.log(`\u{1F50D} [ErrorTranslation] Checking key: "${o}" -> result: "${l}" (same as key: ${l===o})`),l&&l!==o)return s&&console.log(`\u2705 [ErrorTranslation] Found translation at key: ${o} = "${l}"`),l}let g=y[i];if(g)return s&&console.log(`\u{1F504} [ErrorTranslation] Using default message: "${g}"`),g;let h=i.replace(/_/g," ").toLowerCase().replace(/\b\w/g,o=>o.toUpperCase());return s&&console.log(`\u26A0\uFE0F [ErrorTranslation] No translation found, using friendly code: "${h}"`),h}function R(t,e){return t.map(r=>c(r,e))}function m(t,e){let{enableDebug:r}=e;r&&console.log("\u{1F50D} [ErrorTranslation] Translating error:",t);let n=c(t.code,e);return n!==t.code.toUpperCase()&&n!==t.code?(r&&console.log(`\u2705 [ErrorTranslation] Using hierarchical translation: "${n}"`),t.field?`${t.field}: ${n}`:n):t.message&&!t.message.includes("Error:")&&t.message.length>0&&t.message!==t.code?(r&&console.log(`\u{1F504} [ErrorTranslation] No hierarchical translation found, using API message: "${t.message}"`),t.message):(r&&console.log(`\u26A0\uFE0F [ErrorTranslation] Using final fallback: "${n}"`),t.field?`${t.field}: ${n}`:n)}function A(t,e={}){let r={translateFn:t,currentLanguage:e.currentLanguage,enableDebug:e.enableDebug||!1};return{translateErrorCode:n=>c(n,r),translateErrorCodes:n=>R(n,r),translateError:n=>m(n,r),translateApiError:n=>_optionalChain([n, 'optionalAccess', _2 => _2.data, 'optionalAccess', _3 => _3.response, 'optionalAccess', _4 => _4.status])?c(n.data.response.status,r):_optionalChain([n, 'optionalAccess', _5 => _5.status])?c(n.status,r):_optionalChain([n, 'optionalAccess', _6 => _6.code])?c(n.code,r):"Unknown error"}}var E=class t{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return t.instance||(t.instance=new t),t.instance}emit(e,r){let n=Date.now();if(this.isHandlingAuthError&&this.lastEventType===e&&n-this.lastErrorTime<this.DEBOUNCE_TIME){console.log(`\u{1F6AB} AuthEventBus: Ignoring duplicate ${e} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=n,this.lastEventType=e,console.log(`\u{1F4E2} AuthEventBus: Emitting ${e} event`,r);let s={type:e,details:r,timestamp:n};this.listeners.forEach(i=>{try{i(s)}catch(u){console.error("AuthEventBus: Error in listener",u)}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},O= exports.f =E.getInstance();var a=class a{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return a.instance||(a.instance=new a),a.instance}subscribe(e){return this.listeners.add(e),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(e)}}unsubscribe(e){this.listeners.delete(e),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let e=this;window.history.pushState=function(...r){let n=e.originalPushState.apply(this,r);return e.notifyListeners(),n},window.history.replaceState=function(...r){let n=e.originalReplaceState.apply(this,r);return e.notifyListeners(),n},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(e=>{try{e()}catch(r){console.error("NavigationTracker: Error in navigation listener",r)}})}static reset(){_optionalChain([a, 'access', _7 => _7.instance, 'optionalAccess', _8 => _8.isPatched])&&a.instance.removePatches(),a.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};a.instance=null;var p=a;var f=t=>{try{let e=t.split(".");if(e.length!==3)return console.warn("Invalid JWT format: token must have 3 parts"),null;let r=e[1],n=r+"=".repeat((4-r.length%4)%4);return JSON.parse(atob(n))}catch(e){return console.warn("Failed to decode JWT token:",e),null}},_= exports.i =()=>{try{let t=null;if(t=sessionStorage.getItem("authToken"),console.log("\u{1F50D} getCurrentUserEmail - authToken:",t?`${t.substring(0,20)}...`:null),t||(t=sessionStorage.getItem("token"),console.log("\u{1F50D} getCurrentUserEmail - token:",t?`${t.substring(0,20)}...`:null)),t||(t=localStorage.getItem("authToken")||localStorage.getItem("token"),console.log("\u{1F50D} getCurrentUserEmail - localStorage:",t?`${t.substring(0,20)}...`:null)),!t)return console.warn("\u{1F50D} getCurrentUserEmail - No token found in any storage"),null;let e=f(t);if(!e)return console.warn("\u{1F50D} getCurrentUserEmail - Failed to decode token"),null;let r=e.email||e["cognito:username"]||null;return console.log("\u{1F50D} getCurrentUserEmail - Extracted email:",r),r}catch(t){return console.warn("Failed to get current user email:",t),null}},D= exports.j =t=>{try{let e=f(t);if(!e||!e.exp)return!0;let r=Math.floor(Date.now()/1e3);return e.exp<r}catch (e2){return!0}};exports.a = I; exports.b = c; exports.c = R; exports.d = m; exports.e = A; exports.f = O; exports.g = p; exports.h = f; exports.i = _; exports.j = D;
@@ -1 +0,0 @@
1
- import{a as D,b as J,f as N,g as q,h as Z,i as Q}from"./chunk-5JKS55SE.mjs";import{createContext as ge,useContext as pe,useEffect as ye,useState as U}from"react";import z from"@nocios/crudify-browser";var Y=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){console.error("[CredentialsEventBus] Error in listener:",t)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},ee=Y.getInstance();import{jsx as he}from"react/jsx-runtime";var ie=ge(void 0),te=({config:r,children:i})=>{let[e,t]=U(!0),[o,c]=U(null),[y,h]=U(!1),[x,m]=U(""),[I,u]=U();ye(()=>{if(!r.publicApiKey){c("No publicApiKey provided"),t(!1),h(!1);return}let a=`${r.publicApiKey}-${r.env}`;if(a===x&&y){t(!1);return}(async()=>{t(!0),c(null),h(!1);try{z.config(r.env||"prod");let d=await z.init(r.publicApiKey,"none");if(u(d),typeof z.transaction=="function"&&typeof z.login=="function")h(!0),m(a),d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&ee.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(d){let g=d instanceof Error?d.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",d),c(g),h(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,x,y]);let s={crudify:y?z:null,isLoading:e,error:o,isInitialized:y,adminCredentials:I};return he(ie.Provider,{value:s,children:i})},re=()=>{let r=pe(ie);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import F from"crypto-js";var l=class l{static setStorageType(i){l.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return F.SHA256(i).toString()}static getEncryptionKey(){if(l.encryptionKey)return l.encryptionKey;let i=window.localStorage;if(!i)return l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey;try{let e=i.getItem(l.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=l.generateEncryptionKey(),i.setItem(l.ENCRYPTION_KEY_STORAGE,e)),l.encryptionKey=e,e}catch{return console.warn("Crudify: Cannot persist encryption key, using temporary key"),l.encryptionKey=l.generateEncryptionKey(),l.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch{return!1}}static getStorage(){return l.storageType==="none"?null:l.isStorageAvailable(l.storageType)?window[l.storageType]:(console.warn(`Crudify: ${l.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=l.getEncryptionKey();return F.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=l.getEncryptionKey();return F.AES.decrypt(i,e).toString(F.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",e),i}}static saveTokens(i){let e=l.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},o=l.encrypt(JSON.stringify(t));e.setItem(l.TOKEN_KEY,o),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",t)}}static getTokens(){let i=l.getStorage();if(!i)return null;try{let e=i.getItem(l.TOKEN_KEY);if(!e)return null;let t=l.decrypt(e),o=JSON.parse(t);return!o.accessToken||!o.refreshToken||!o.expiresAt||!o.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),l.clearTokens(),null):Date.now()>=o.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),l.clearTokens(),null):{accessToken:o.accessToken,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),l.clearTokens(),null}}static clearTokens(){let i=l.getStorage();if(i)try{i.removeItem(l.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{l.clearTokens(),l.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(l.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",i)}}static hasValidTokens(){return l.getTokens()!==null}static getExpirationInfo(){let i=l.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=l.getTokens();if(!t){console.warn("Crudify: Cannot update access token, no existing tokens found");return}l.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===l.TOKEN_KEY){if(t.newValue===null){console.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let o=l.getTokens();i(o)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};l.TOKEN_KEY="crudify_tokens",l.ENCRYPTION_KEY_STORAGE="crudify_enc_key",l.encryptionKey=null,l.storageType="localStorage";var p=l;import b from"@nocios/crudify-browser";var M=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},p.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),b.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),N.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=p.getTokens();e?p.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):p.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(i,e){try{let t=await b.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let o=p.getTokens(),c={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:o?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:o?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return p.saveTokens(c),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(c),{success:!0,tokens:c,data:t.data}}catch(t){return console.error("[SessionManager] Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await b.logout(),p.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),p.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=p.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),p.clearTokens(),!1;if(b.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),b.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let o=p.getTokens();return o&&this.config.onSessionRestored?.(o),!0}return p.clearTokens(),await b.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(i),!0}catch(i){return this.log("Session restore error:",i),p.clearTokens(),await b.logout(),!1}}isAuthenticated(){return b.isLogin()||p.hasValidTokens()}getTokenInfo(){let i=b.getTokenData(),e=p.getExpirationInfo(),t=p.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:p.hasValidTokens(),apiEndpointAdmin:t?.apiEndpointAdmin,apiKeyEndpointAdmin:t?.apiKeyEndpointAdmin}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let i=await b.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),p.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return p.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),p.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){b.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),N.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(p.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),N.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),N.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=b.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";b.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",c=await b.init(t,o);if(c&&c.success===!1&&c.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(c.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw console.error("[SessionManager] Failed to initialize crudify:",i),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(o=>o.errorType==="Unauthorized"||o.message?.includes("Unauthorized")||o.message?.includes("Not Authorized")||o.message?.includes("NOT_AUTHORIZED")||o.message?.includes("Token")||o.message?.includes("TOKEN")||o.message?.includes("Authentication")||o.message?.includes("UNAUTHENTICATED")||o.extensions?.code==="UNAUTHENTICATED"||o.extensions?.code==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(t.message?.includes("TOKEN")||t.message?.includes("Token"))&&(e.isTokenExpired=!0),t.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let o=Object.values(i.errors).flat().find(c=>typeof c=="string"&&(c.includes("NOT_AUTHORIZED")||c.includes("TOKEN_REFRESH_FAILED")||c.includes("TOKEN_HAS_EXPIRED")||c.includes("PLEASE_LOGIN")||c.includes("Unauthorized")||c.includes("UNAUTHENTICATED")||c.includes("SESSION_EXPIRED")||c.includes("INVALID_TOKEN")));o&&typeof o=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,o.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("TOKEN_HAS_EXPIRED")||o.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.status){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.data)try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch{}if(!e.isAuthError&&i.errorCode){let t=i.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let i=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){p.clearTokens(),b.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?J("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as me,useEffect as H,useCallback as P}from"react";function ne(r={}){let[i,e]=me({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=M.getInstance(),o=P(async()=>{console.log("\u{1F535} [useSession] initialize() CALLED"),console.log("\u{1F50D} [useSession] options received:",{autoRestore:r.autoRestore,enableLogging:r.enableLogging,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin});try{e(n=>({...n,isLoading:!0,error:null}));let u={autoRestore:r.autoRestore??!0,enableLogging:r.enableLogging??!1,showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:"Session expired"})),r.onSessionExpired?.()},onSessionRestored:n=>{e(d=>({...d,isAuthenticated:!0,tokens:n,error:null})),r.onSessionRestored?.(n)},onLoginSuccess:n=>{e(d=>({...d,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",u),await t.initialize(u),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let s=t.isAuthenticated(),a=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",s),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",a),e(n=>({...n,isAuthenticated:s,isInitialized:!0,isLoading:!1,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null}))}catch(u){let s=u instanceof Error?u.message:"Initialization failed";e(a=>({...a,isLoading:!1,isInitialized:!0,error:s}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),c=P(async(u,s)=>{e(a=>({...a,isLoading:!0,error:null}));try{let a=await t.login(u,s);return a.success&&a.tokens?e(n=>({...n,isAuthenticated:!0,tokens:a.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),a}catch(a){let n=a instanceof Error?a.message:"Login failed",d=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(g=>({...g,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:n})),{success:!1,error:n}}},[t]),y=P(async()=>{e(u=>({...u,isLoading:!0}));try{await t.logout(),e(u=>({...u,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(u){e(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:u instanceof Error?u.message:"Logout error"}))}},[t]),h=P(async()=>{try{let u=await t.refreshTokens();if(u){let s=t.getTokenInfo();e(a=>({...a,tokens:s.crudifyTokens.accessToken?{accessToken:s.crudifyTokens.accessToken,refreshToken:s.crudifyTokens.refreshToken,expiresAt:s.crudifyTokens.expiresAt,refreshExpiresAt:s.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(s=>({...s,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return u}catch(u){return e(s=>({...s,isAuthenticated:!1,tokens:null,error:u instanceof Error?u.message:"Token refresh failed"})),!1}},[t]),x=P(()=>{e(u=>({...u,error:null}))},[]),m=P(()=>t.getTokenInfo(),[t]);H(()=>{o()},[o]),H(()=>{if(!i.isAuthenticated||!i.tokens)return;let u=q.getInstance(),s=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},a=u.subscribe(s);window.addEventListener("popstate",s);let n=()=>{let A=t.getTokenInfo().crudifyTokens.expiresIn||0;return A<300*1e3?30*1e3:A<1800*1e3?60*1e3:120*1e3},d,g=()=>{let T=n();d=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),g();return}let A=t.getTokenInfo(),E=A.crudifyTokens.expiresIn||0,S=(A.crudifyTokens.expiresAt||0)-(Date.now()-E),f=S*.5;if(E>0&&E<=f){let O=Math.round(E/S*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${O}% of TTL (${Math.round(E/6e4)}min remaining), refreshing...`),e(C=>({...C,isLoading:!0})),await t.refreshTokens()){let C=t.getTokenInfo();e(fe=>({...fe,isLoading:!1,tokens:C.crudifyTokens.accessToken?{accessToken:C.crudifyTokens.accessToken,refreshToken:C.crudifyTokens.refreshToken,expiresAt:C.crudifyTokens.expiresAt,refreshExpiresAt:C.crudifyTokens.refreshExpiresAt}:null}))}else e(C=>({...C,isLoading:!1,isAuthenticated:!1,tokens:null}))}let w=t.getTimeSinceLastActivity(),L=1800*1e3;w>L?(r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout (30min) - logging out"),await y()):g()},T)};return g(),()=>{clearTimeout(d),window.removeEventListener("popstate",s),a()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,y]),H(()=>{let u=N.subscribe(async s=>{if(r.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${s.type}`),s.type==="TOKEN_EXPIRED"){if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping TOKEN_EXPIRED handler");return}r.enableLogging&&console.log("\u{1F504} Token expired, attempting refresh..."),e(a=>({...a,isLoading:!0}));try{if(await t.refreshTokens()){r.enableLogging&&console.log("\u2705 Token refreshed successfully");let n=t.getTokenInfo();e(d=>({...d,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else r.enableLogging&&console.log("\u274C Token refresh failed, session expired"),N.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(a){r.enableLogging&&console.error("\u274C Error during token refresh:",a),N.emit("SESSION_EXPIRED",{message:a instanceof Error?a.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(s.type==="SESSION_EXPIRED"||s.type==="TOKEN_REFRESH_FAILED")&&(r.enableLogging&&console.log(`\u{1F534} Session expired (${s.type}), logging out...`),e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:s.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>u()},[r.enableLogging,r.onSessionExpired,t]),H(()=>{let u=p.subscribeToChanges(s=>{s?(r.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(a=>({...a,tokens:s,isAuthenticated:!0}))):(r.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(a=>({...a,isAuthenticated:!1,tokens:null})),N.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>u()},[r.enableLogging]);let I=P(()=>{t.updateLastActivity()},[t]);return{...i,login:c,logout:y,refreshTokens:h,clearError:x,getTokenInfo:m,updateActivity:I,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}import{useState as oe,createContext as Ee,useContext as Te,useCallback as G,useEffect as ve}from"react";import{Snackbar as ke,Alert as Ae,Box as be,Portal as xe}from"@mui/material";import{v4 as Se}from"uuid";import Ie from"dompurify";import{jsx as K,jsxs as Ce}from"react/jsx-runtime";var se=Ee(null),Ne=r=>Ie.sanitize(r,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),$=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:c=!1})=>{let[y,h]=oe([]),x=G((s,a="info",n)=>{if(!o)return"";if(!s||typeof s!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";s.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),s=s.substring(0,1e3)+"...");let d=Se(),g={id:d,message:s,severity:a,autoHideDuration:n?.autoHideDuration??e,persistent:n?.persistent??!1,allowHtml:n?.allowHtml??c};return h(T=>[...T.length>=i?T.slice(-(i-1)):T,g]),d},[i,e,o,c]),m=G(s=>{h(a=>a.filter(n=>n.id!==s))},[]),I=G(()=>{h([])},[]),u={showNotification:x,hideNotification:m,clearAllNotifications:I};return Ce(se.Provider,{value:u,children:[r,o&&K(xe,{children:K(be,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:y.map(s=>K(Re,{notification:s,onClose:()=>m(s.id)},s.id))})})]})},Re=({notification:r,onClose:i})=>{let[e,t]=oe(!0),o=G((c,y)=>{y!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return ve(()=>{if(!r.persistent&&r.autoHideDuration){let c=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(c)}},[r.autoHideDuration,r.persistent,o]),K(ke,{open:e,onClose:o,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:K(Ae,{variant:"filled",severity:r.severity,onClose:o,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?K("span",{dangerouslySetInnerHTML:{__html:Ne(r.message)}}):K("span",{children:r.message})})})},ae=()=>{let r=Te(se);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import Le,{createContext as De,useContext as we,useMemo as B}from"react";import{Fragment as Ke,jsx as k,jsxs as R}from"react/jsx-runtime";var ce=De(void 0);function le({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let c;try{let{showNotification:n}=ae();c=n}catch{}let y={};try{let n=re();n.isInitialized&&n.adminCredentials&&(y=n.adminCredentials)}catch{}let h=B(()=>{let n,d;if(e?.publicApiKey&&(n=e.publicApiKey),e?.env&&(d=e.env),!n){let g=D("publicApiKey"),T=D("environment");g&&(n=g),T&&["dev","stg","prod"].includes(T)&&(d=T)}return{publicApiKey:n,env:d||"prod"}},[e]),x=Le.useMemo(()=>({...i,showNotification:c,apiEndpointAdmin:y.apiEndpointAdmin,apiKeyEndpointAdmin:y.apiKeyEndpointAdmin,publicApiKey:h.publicApiKey,env:h.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,c,y.apiEndpointAdmin,y.apiKeyEndpointAdmin,h]),m=ne(x),I=B(()=>{let n,d,g,T,A,E="unknown";if(e?.publicApiKey&&(n=e.publicApiKey,E="props"),e?.env&&(d=e.env),e?.appName&&(g=e.appName),e?.loginActions&&(T=e.loginActions),e?.logo&&(A=e.logo),!n){let v=D("publicApiKey"),S=D("environment"),f=D("appName"),w=D("loginActions"),L=D("logo");v&&(n=v,E="cookies"),S&&["dev","stg","prod"].includes(S)&&(d=S),f&&(g=decodeURIComponent(f)),w&&(T=decodeURIComponent(w).split(",").map(W=>W.trim()).filter(Boolean)),L&&(A=decodeURIComponent(L))}return{publicApiKey:n,env:d,appName:g,loginActions:T,logo:A}},[e]),u=B(()=>{if(!m.tokens?.accessToken||!m.isAuthenticated)return null;try{let n=Z(m.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let d={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(g=>{["sub","email","subscriber"].includes(g)||(d[g]=n[g])}),d}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[m.tokens?.accessToken,m.isAuthenticated]),s={...m,sessionData:u,config:I},a={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return k(ce.Provider,{value:s,children:r})}function Ii(r){let i={enabled:r.showNotifications,maxNotifications:r.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:r.notificationOptions?.defaultAutoHideDuration||6e3,position:r.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:r.notificationOptions?.allowHtml||!1};return r.config?.publicApiKey?k(te,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:k($,{...i,children:k(le,{...r})})}):k($,{...i,children:k(le,{...r})})}function Pe(){let r=we(ce);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Ni(){let r=Pe();return r.isInitialized?R("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[k("h4",{children:"Session Debug Info"}),R("div",{children:[k("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),R("div",{children:[k("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),R("div",{children:[k("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&R(Ke,{children:[R("div",{children:[k("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),R("div",{children:[k("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),R("div",{children:[k("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),R("div",{children:[k("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),R("div",{children:[k("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):k("div",{children:"Session not initialized"})}import{useState as _,useEffect as ue,useCallback as de,useRef as V}from"react";import Oe from"@nocios/crudify-browser";var Pi=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,c]=_(null),[y,h]=_(!1),[x,m]=_(null),[I,u]=_({}),s=V(null),a=V(!0),n=V(0),d=V(0),g=de(()=>{c(null),m(null),h(!1),u({})},[]),T=de(async()=>{let A=Q();if(!A){a.current&&(m("No user email available"),h(!1));return}s.current&&s.current.abort();let E=new AbortController;s.current=E;let v=++n.current;try{a.current&&(h(!0),m(null));let S=await Oe.readItems("users",{filter:{email:A},pagination:{limit:1}});if(v===n.current&&a.current&&!E.signal.aborted)if(S.success&&S.data&&S.data.length>0){let f=S.data[0];c(f);let w={fullProfile:f,totalFields:Object.keys(f).length,displayData:{id:f.id,email:f.email,username:f.username,firstName:f.firstName,lastName:f.lastName,fullName:f.fullName||`${f.firstName||""} ${f.lastName||""}`.trim(),role:f.role,permissions:f.permissions||[],isActive:f.isActive,lastLogin:f.lastLogin,createdAt:f.createdAt,updatedAt:f.updatedAt,...Object.keys(f).filter(L=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(L)).reduce((L,O)=>({...L,[O]:f[O]}),{})}};u(w),m(null),d.current=0}else m("User profile not found"),c(null),u({})}catch(S){if(v===n.current&&a.current){let f=S;if(f.name==="AbortError")return;e&&d.current<t&&(f.message?.includes("Network Error")||f.message?.includes("Failed to fetch"))?(d.current++,setTimeout(()=>{a.current&&T()},1e3*d.current)):(m("Failed to load user profile"),c(null),u({}))}}finally{v===n.current&&a.current&&h(!1),s.current===E&&(s.current=null)}},[e,t]);return ue(()=>{i&&T()},[i,T]),ue(()=>(a.current=!0,()=>{a.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:o,loading:y,error:x,extendedData:I,refreshProfile:T,clearProfile:g}};import{useState as j,useEffect as Ue,useCallback as X,useRef as ze}from"react";import Fe from"@nocios/crudify-browser";var zi=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:c,padding:y=0,separator:h=""}=r,[x,m]=j(""),[I,u]=j(!1),[s,a]=j(null),n=ze(!1),d=X(E=>{let v=String(E).padStart(y,"0");return`${c}${h}${v}`},[c,y,h]),g=X(async()=>{u(!0),a(null);try{let E=await Fe.getNextSequence(c);if(E.success&&E.data?.value){let v=d(E.data.value);m(v),t?.(v)}else{let v=E.errors?._error?.[0]||"Failed to generate code";a(v),o?.(v)}}catch(E){let v=E instanceof Error?E.message:"Unknown error";a(v),o?.(v)}finally{u(!1)}},[c,d,t,o]),T=X(async()=>{await g()},[g]),A=X(()=>{a(null)},[]);return Ue(()=>{e&&!x&&!n.current&&(n.current=!0,g())},[e,x,g]),{value:x,loading:I,error:s,regenerate:T,clearError:A}};export{ee as a,te as b,re as c,p as d,M as e,ne as f,$ as g,ae as h,Ii as i,Pe as j,Ni as k,Pi as l,zi as m};
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkAT74WV5Wjs = require('./chunk-AT74WV5W.js');var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var Y=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){console.error("[CredentialsEventBus] Error in listener:",t)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},ee= exports.a =Y.getInstance();var _jsxruntime = require('react/jsx-runtime');var ie=_react.createContext.call(void 0, void 0),te= exports.b =({config:r,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[o,c]=_react.useState.call(void 0, null),[y,h]=_react.useState.call(void 0, !1),[x,m]=_react.useState.call(void 0, ""),[I,u]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){c("No publicApiKey provided"),t(!1),h(!1);return}let a=`${r.publicApiKey}-${r.env}`;if(a===x&&y){t(!1);return}(async()=>{t(!0),c(null),h(!1);try{_crudifybrowser2.default.config(r.env||"prod");let d=await _crudifybrowser2.default.init(r.publicApiKey,"none");if(u(d),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")h(!0),m(a),d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&ee.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(d){let g=d instanceof Error?d.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",d),c(g),h(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,x,y]);let s={crudify:y?_crudifybrowser2.default:null,isLoading:e,error:o,isInitialized:y,adminCredentials:I};return _jsxruntime.jsx.call(void 0, ie.Provider,{value:s,children:i})},re= exports.c =()=>{let r=_react.useContext.call(void 0, ie);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 p=l;var M=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},p.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_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=p.getTokens();e?p.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):p.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(i,e){try{let t=await _crudifybrowser2.default.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let o=p.getTokens(),c={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:_optionalChain([o, 'optionalAccess', _2 => _2.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([o, 'optionalAccess', _3 => _3.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return p.saveTokens(c),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.onLoginSuccess, 'optionalCall', _6 => _6(c)]),{success:!0,tokens:c,data:t.data}}catch(t){return console.error("[SessionManager] Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await _crudifybrowser2.default.logout(),p.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),p.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=p.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),p.clearTokens(),!1;if(_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=p.getTokens();return o&&_optionalChain([this, 'access', _10 => _10.config, 'access', _11 => _11.onSessionRestored, 'optionalCall', _12 => _12(o)]),!0}return p.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),p.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||p.hasValidTokens()}getTokenInfo(){let i=_crudifybrowser2.default.getTokenData(),e=p.getExpirationInfo(),t=p.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:p.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),p.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 p.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),p.clearTokens(),_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&&(p.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)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=_crudifybrowser2.default.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";_crudifybrowser2.default.config(e);let t=this.config.publicApiKey,o=this.config.enableLogging?"debug":"none",c=await _crudifybrowser2.default.init(t,o);if(c&&c.success===!1&&c.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(c.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw console.error("[SessionManager] Failed to initialize crudify:",i),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(o=>o.errorType==="Unauthorized"||_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(c=>typeof c=="string"&&(c.includes("NOT_AUTHORIZED")||c.includes("TOKEN_REFRESH_FAILED")||c.includes("TOKEN_HAS_EXPIRED")||c.includes("PLEASE_LOGIN")||c.includes("Unauthorized")||c.includes("UNAUTHENTICATED")||c.includes("SESSION_EXPIRED")||c.includes("INVALID_TOKEN")));o&&typeof o=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,o.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("TOKEN_HAS_EXPIRED")||o.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):o.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&_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();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){p.clearTokens(),_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 ne(r={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=M.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(n=>({...n,isLoading:!0,error:null}));let u={autoRestore:_nullishCoalesce(r.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(r.enableLogging, () => (!1)),showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([r, 'access', _69 => _69.onSessionExpired, 'optionalCall', _70 => _70()])},onSessionRestored:n=>{e(d=>({...d,isAuthenticated:!0,tokens:n,error:null})),_optionalChain([r, 'access', _71 => _71.onSessionRestored, 'optionalCall', _72 => _72(n)])},onLoginSuccess:n=>{e(d=>({...d,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",u),await t.initialize(u),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let s=t.isAuthenticated(),a=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",s),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",a),e(n=>({...n,isAuthenticated:s,isInitialized:!0,isLoading:!1,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null}))}catch(u){let s=u instanceof Error?u.message:"Initialization failed";e(a=>({...a,isLoading:!1,isInitialized:!0,error:s}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),c=_react.useCallback.call(void 0, async(u,s)=>{e(a=>({...a,isLoading:!0,error:null}));try{let a=await t.login(u,s);return a.success&&a.tokens?e(n=>({...n,isAuthenticated:!0,tokens:a.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),a}catch(a){let n=a instanceof Error?a.message:"Login failed",d=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(g=>({...g,isAuthenticated:!1,tokens:null,isLoading:!1,error:d?null:n})),{success:!1,error:n}}},[t]),y=_react.useCallback.call(void 0, async()=>{e(u=>({...u,isLoading:!0}));try{await t.logout(),e(u=>({...u,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(u){e(s=>({...s,isAuthenticated:!1,tokens:null,isLoading:!1,error:u instanceof Error?u.message:"Logout error"}))}},[t]),h=_react.useCallback.call(void 0, async()=>{try{let u=await t.refreshTokens();if(u){let s=t.getTokenInfo();e(a=>({...a,tokens:s.crudifyTokens.accessToken?{accessToken:s.crudifyTokens.accessToken,refreshToken:s.crudifyTokens.refreshToken,expiresAt:s.crudifyTokens.expiresAt,refreshExpiresAt:s.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(s=>({...s,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return u}catch(u){return e(s=>({...s,isAuthenticated:!1,tokens:null,error:u instanceof Error?u.message:"Token refresh failed"})),!1}},[t]),x=_react.useCallback.call(void 0, ()=>{e(u=>({...u,error:null}))},[]),m=_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 u=_chunkAT74WV5Wjs.g.getInstance(),s=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},a=u.subscribe(s);window.addEventListener("popstate",s);let n=()=>{let A=t.getTokenInfo().crudifyTokens.expiresIn||0;return A<300*1e3?30*1e3:A<1800*1e3?60*1e3:120*1e3},d,g=()=>{let T=n();d=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),g();return}let A=t.getTokenInfo(),E=A.crudifyTokens.expiresIn||0,S=(A.crudifyTokens.expiresAt||0)-(Date.now()-E),f=S*.5;if(E>0&&E<=f){let O=Math.round(E/S*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${O}% of TTL (${Math.round(E/6e4)}min remaining), refreshing...`),e(C=>({...C,isLoading:!0})),await t.refreshTokens()){let C=t.getTokenInfo();e(fe=>({...fe,isLoading:!1,tokens:C.crudifyTokens.accessToken?{accessToken:C.crudifyTokens.accessToken,refreshToken:C.crudifyTokens.refreshToken,expiresAt:C.crudifyTokens.expiresAt,refreshExpiresAt:C.crudifyTokens.refreshExpiresAt}:null}))}else e(C=>({...C,isLoading:!1,isAuthenticated:!1,tokens:null}))}let w=t.getTimeSinceLastActivity(),L=1800*1e3;w>L?(r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout (30min) - logging out"),await y()):g()},T)};return g(),()=>{clearTimeout(d),window.removeEventListener("popstate",s),a()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,y]),_react.useEffect.call(void 0, ()=>{let u=_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(a=>({...a,isLoading:!0}));try{if(await t.refreshTokens()){r.enableLogging&&console.log("\u2705 Token refreshed successfully");let n=t.getTokenInfo();e(d=>({...d,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else r.enableLogging&&console.log("\u274C Token refresh failed, session expired"),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(a){r.enableLogging&&console.error("\u274C Error during token refresh:",a),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:a instanceof Error?a.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(s.type==="SESSION_EXPIRED"||s.type==="TOKEN_REFRESH_FAILED")&&(r.enableLogging&&console.log(`\u{1F534} Session expired (${s.type}), logging out...`),e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([s, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message])||"Session expired"})),_optionalChain([r, 'access', _75 => _75.onSessionExpired, 'optionalCall', _76 => _76()]))});return()=>u()},[r.enableLogging,r.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{let u=p.subscribeToChanges(s=>{s?(r.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(a=>({...a,tokens:s,isAuthenticated:!0}))):(r.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(a=>({...a,isAuthenticated:!1,tokens:null})),_chunkAT74WV5Wjs.f.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>u()},[r.enableLogging]);let I=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]);return{...i,login:c,logout:y,refreshTokens:h,clearError:x,getTokenInfo:m,updateActivity:I,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var se=_react.createContext.call(void 0, null),Ne=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}),$= exports.g =({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:o=!1,allowHtml:c=!1})=>{let[y,h]=_react.useState.call(void 0, []),x=_react.useCallback.call(void 0, (s,a="info",n)=>{if(!o)return"";if(!s||typeof s!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";s.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),s=s.substring(0,1e3)+"...");let d=_uuid.v4.call(void 0, ),g={id:d,message:s,severity:a,autoHideDuration:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _77 => _77.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _78 => _78.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _79 => _79.allowHtml]), () => (c))};return h(T=>[...T.length>=i?T.slice(-(i-1)):T,g]),d},[i,e,o,c]),m=_react.useCallback.call(void 0, s=>{h(a=>a.filter(n=>n.id!==s))},[]),I=_react.useCallback.call(void 0, ()=>{h([])},[]),u={showNotification:x,hideNotification:m,clearAllNotifications:I};return _jsxruntime.jsxs.call(void 0, se.Provider,{value:u,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:y.map(s=>_jsxruntime.jsx.call(void 0, Re,{notification:s,onClose:()=>m(s.id)},s.id))})})]})},Re=({notification:r,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),o=_react.useCallback.call(void 0, (c,y)=>{y!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let c=setTimeout(()=>{o()},r.autoHideDuration);return()=>clearTimeout(c)}},[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:Ne(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},ae= exports.h =()=>{let r=_react.useContext.call(void 0, se);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var ce=_react.createContext.call(void 0, void 0);function le({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:o={}}){let c;try{let{showNotification:n}=ae();c=n}catch (e5){}let y={};try{let n=re();n.isInitialized&&n.adminCredentials&&(y=n.adminCredentials)}catch (e6){}let h=_react.useMemo.call(void 0, ()=>{let n,d;if(_optionalChain([e, 'optionalAccess', _80 => _80.publicApiKey])&&(n=e.publicApiKey),_optionalChain([e, 'optionalAccess', _81 => _81.env])&&(d=e.env),!n){let g=_chunkAT74WV5Wjs.a.call(void 0, "publicApiKey"),T=_chunkAT74WV5Wjs.a.call(void 0, "environment");g&&(n=g),T&&["dev","stg","prod"].includes(T)&&(d=T)}return{publicApiKey:n,env:d||"prod"}},[e]),x=_react2.default.useMemo(()=>({...i,showNotification:c,apiEndpointAdmin:y.apiEndpointAdmin,apiKeyEndpointAdmin:y.apiKeyEndpointAdmin,publicApiKey:h.publicApiKey,env:h.env,onSessionExpired:()=>{_optionalChain([i, 'access', _82 => _82.onSessionExpired, 'optionalCall', _83 => _83()])}}),[i,c,y.apiEndpointAdmin,y.apiKeyEndpointAdmin,h]),m=ne(x),I=_react.useMemo.call(void 0, ()=>{let n,d,g,T,A,E="unknown";if(_optionalChain([e, 'optionalAccess', _84 => _84.publicApiKey])&&(n=e.publicApiKey,E="props"),_optionalChain([e, 'optionalAccess', _85 => _85.env])&&(d=e.env),_optionalChain([e, 'optionalAccess', _86 => _86.appName])&&(g=e.appName),_optionalChain([e, 'optionalAccess', _87 => _87.loginActions])&&(T=e.loginActions),_optionalChain([e, 'optionalAccess', _88 => _88.logo])&&(A=e.logo),!n){let v=_chunkAT74WV5Wjs.a.call(void 0, "publicApiKey"),S=_chunkAT74WV5Wjs.a.call(void 0, "environment"),f=_chunkAT74WV5Wjs.a.call(void 0, "appName"),w=_chunkAT74WV5Wjs.a.call(void 0, "loginActions"),L=_chunkAT74WV5Wjs.a.call(void 0, "logo");v&&(n=v,E="cookies"),S&&["dev","stg","prod"].includes(S)&&(d=S),f&&(g=decodeURIComponent(f)),w&&(T=decodeURIComponent(w).split(",").map(W=>W.trim()).filter(Boolean)),L&&(A=decodeURIComponent(L))}return{publicApiKey:n,env:d,appName:g,loginActions:T,logo:A}},[e]),u=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([m, 'access', _89 => _89.tokens, 'optionalAccess', _90 => _90.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 d={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(g=>{["sub","email","subscriber"].includes(g)||(d[g]=n[g])}),d}}catch(n){console.error("Error decoding JWT token for sessionData:",n)}return null},[_optionalChain([m, 'access', _91 => _91.tokens, 'optionalAccess', _92 => _92.accessToken]),m.isAuthenticated]),s={...m,sessionData:u,config:I},a={enabled:t,maxNotifications:o.maxNotifications||5,defaultAutoHideDuration:o.defaultAutoHideDuration||6e3,position:o.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, ce.Provider,{value:s,children:r})}function Ii(r){let i={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _93 => _93.notificationOptions, 'optionalAccess', _94 => _94.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _95 => _95.notificationOptions, 'optionalAccess', _96 => _96.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _97 => _97.notificationOptions, 'optionalAccess', _98 => _98.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _99 => _99.notificationOptions, 'optionalAccess', _100 => _100.allowHtml])||!1};return _optionalChain([r, 'access', _101 => _101.config, 'optionalAccess', _102 => _102.publicApiKey])?_jsxruntime.jsx.call(void 0, te,{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, $,{...i,children:_jsxruntime.jsx.call(void 0, le,{...r})})}):_jsxruntime.jsx.call(void 0, $,{...i,children:_jsxruntime.jsx.call(void 0, le,{...r})})}function Pe(){let r=_react.useContext.call(void 0, ce);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Ni(){let r=Pe();return r.isInitialized?_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 Pi=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[o,c]=_react.useState.call(void 0, null),[y,h]=_react.useState.call(void 0, !1),[x,m]=_react.useState.call(void 0, null),[I,u]=_react.useState.call(void 0, {}),s=_react.useRef.call(void 0, null),a=_react.useRef.call(void 0, !0),n=_react.useRef.call(void 0, 0),d=_react.useRef.call(void 0, 0),g=_react.useCallback.call(void 0, ()=>{c(null),m(null),h(!1),u({})},[]),T=_react.useCallback.call(void 0, async()=>{let A=_chunkAT74WV5Wjs.i.call(void 0, );if(!A){a.current&&(m("No user email available"),h(!1));return}s.current&&s.current.abort();let E=new AbortController;s.current=E;let v=++n.current;try{a.current&&(h(!0),m(null));let S=await _crudifybrowser2.default.readItems("users",{filter:{email:A},pagination:{limit:1}});if(v===n.current&&a.current&&!E.signal.aborted)if(S.success&&S.data&&S.data.length>0){let f=S.data[0];c(f);let w={fullProfile:f,totalFields:Object.keys(f).length,displayData:{id:f.id,email:f.email,username:f.username,firstName:f.firstName,lastName:f.lastName,fullName:f.fullName||`${f.firstName||""} ${f.lastName||""}`.trim(),role:f.role,permissions:f.permissions||[],isActive:f.isActive,lastLogin:f.lastLogin,createdAt:f.createdAt,updatedAt:f.updatedAt,...Object.keys(f).filter(L=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(L)).reduce((L,O)=>({...L,[O]:f[O]}),{})}};u(w),m(null),d.current=0}else m("User profile not found"),c(null),u({})}catch(S){if(v===n.current&&a.current){let f=S;if(f.name==="AbortError")return;e&&d.current<t&&(_optionalChain([f, 'access', _103 => _103.message, 'optionalAccess', _104 => _104.includes, 'call', _105 => _105("Network Error")])||_optionalChain([f, 'access', _106 => _106.message, 'optionalAccess', _107 => _107.includes, 'call', _108 => _108("Failed to fetch")]))?(d.current++,setTimeout(()=>{a.current&&T()},1e3*d.current)):(m("Failed to load user profile"),c(null),u({}))}}finally{v===n.current&&a.current&&h(!1),s.current===E&&(s.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{i&&T()},[i,T]),_react.useEffect.call(void 0, ()=>(a.current=!0,()=>{a.current=!1,s.current&&(s.current.abort(),s.current=null)}),[]),{userProfile:o,loading:y,error:x,extendedData:I,refreshProfile:T,clearProfile:g}};var zi=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:o}=i,{prefix:c,padding:y=0,separator:h=""}=r,[x,m]=_react.useState.call(void 0, ""),[I,u]=_react.useState.call(void 0, !1),[s,a]=_react.useState.call(void 0, null),n=_react.useRef.call(void 0, !1),d=_react.useCallback.call(void 0, E=>{let v=String(E).padStart(y,"0");return`${c}${h}${v}`},[c,y,h]),g=_react.useCallback.call(void 0, async()=>{u(!0),a(null);try{let E=await _crudifybrowser2.default.getNextSequence(c);if(E.success&&_optionalChain([E, 'access', _109 => _109.data, 'optionalAccess', _110 => _110.value])){let v=d(E.data.value);m(v),_optionalChain([t, 'optionalCall', _111 => _111(v)])}else{let v=_optionalChain([E, 'access', _112 => _112.errors, 'optionalAccess', _113 => _113._error, 'optionalAccess', _114 => _114[0]])||"Failed to generate code";a(v),_optionalChain([o, 'optionalCall', _115 => _115(v)])}}catch(E){let v=E instanceof Error?E.message:"Unknown error";a(v),_optionalChain([o, 'optionalCall', _116 => _116(v)])}finally{u(!1)}},[c,d,t,o]),T=_react.useCallback.call(void 0, async()=>{await g()},[g]),A=_react.useCallback.call(void 0, ()=>{a(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!x&&!n.current&&(n.current=!0,g())},[e,x,g]),{value:x,loading:I,error:s,regenerate:T,clearError:A}};exports.a = ee; exports.b = te; exports.c = re; exports.d = p; exports.e = M; exports.f = ne; exports.g = $; exports.h = ae; exports.i = Ii; exports.j = Pe; exports.k = Ni; exports.l = Pi; exports.m = zi;