@nocios/crudify-ui 4.4.82 → 4.4.84

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.js CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createStarExport(obj) { Object.keys(obj) .filter((key) => key !== "default" && key !== "__esModule") .forEach((key) => { if (exports.hasOwnProperty(key)) { return; } Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]}); }); } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkFK52OAX7js = require('./chunk-FK52OAX7.js');var _chunk7YI7UR5Pjs = require('./chunk-7YI7UR5P.js');var _chunkE2B7CUHDjs = require('./chunk-E2B7CUHD.js');var _chunk2M2IM334js = require('./chunk-2M2IM334.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunkDJ3T7VVSjs = require('./chunk-DJ3T7VVS.js');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser); _createStarExport(_crudifybrowser);var _react = require('react');var _material = require('@mui/material');var _jsxruntime = require('react/jsx-runtime');var _e=(e={})=>{try{let r=_chunkDJ3T7VVSjs.b.call(void 0, "theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){_chunkDJ3T7VVSjs.a.warn("Error parsing theme from cookie",r instanceof Error?{errorMessage:r.message}:{message:String(r)})}return e};function Ke({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=_react.useMemo.call(void 0, ()=>{let s=_e(r);return _material.createTheme.call(void 0, s)},[r]);return _jsxruntime.jsxs.call(void 0, _material.ThemeProvider,{theme:t,children:[!o&&_jsxruntime.jsx.call(void 0, _material.CssBaseline,{}),e]})}var _reactrouterdom = require('react-router-dom');var He={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},Ye=()=>_jsxruntime.jsx.call(void 0, "style",{children:`
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createStarExport(obj) { Object.keys(obj) .filter((key) => key !== "default" && key !== "__esModule") .forEach((key) => { if (exports.hasOwnProperty(key)) { return; } Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]}); }); } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkUDDA2MQQjs = require('./chunk-UDDA2MQQ.js');var _chunkE342MLZOjs = require('./chunk-E342MLZO.js');var _chunkL7LTBWM5js = require('./chunk-L7LTBWM5.js');var _chunk2M2IM334js = require('./chunk-2M2IM334.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunkDJ3T7VVSjs = require('./chunk-DJ3T7VVS.js');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser); _createStarExport(_crudifybrowser);var _react = require('react');var _material = require('@mui/material');var _jsxruntime = require('react/jsx-runtime');var _e=(e={})=>{try{let r=_chunkDJ3T7VVSjs.b.call(void 0, "theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){_chunkDJ3T7VVSjs.a.warn("Error parsing theme from cookie",r instanceof Error?{errorMessage:r.message}:{message:String(r)})}return e};function Ke({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=_react.useMemo.call(void 0, ()=>{let s=_e(r);return _material.createTheme.call(void 0, s)},[r]);return _jsxruntime.jsxs.call(void 0, _material.ThemeProvider,{theme:t,children:[!o&&_jsxruntime.jsx.call(void 0, _material.CssBaseline,{}),e]})}var _reactrouterdom = require('react-router-dom');var He={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},Ye=()=>_jsxruntime.jsx.call(void 0, "style",{children:`
2
2
  @keyframes spin {
3
3
  0% { transform: rotate(0deg); }
4
4
  100% { transform: rotate(360deg); }
5
5
  }
6
- `});function T({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, Ye,{}),_jsxruntime.jsxs.call(void 0, "div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[_jsxruntime.jsx.call(void 0, "div",{style:He}),_jsxruntime.jsx.call(void 0, "p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:t})]})]})}var We=/^[a-zA-Z0-9\-_./\?=&%#]+$/,Je=[/^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]/,/\\/],h= exports.validateInternalRedirect =(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return _chunkDJ3T7VVSjs.a.warn("Open redirect blocked (relative path)",{path:e}),r;if(!We.test(o))return _chunkDJ3T7VVSjs.a.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let p of Je)if(p.test(t))return _chunkDJ3T7VVSjs.a.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let s=o.split("?")[0].split("/").filter(Boolean);if(s.length===0)return o;for(let p of s)if(p===".."||p.includes(":")||p.length>100)return _chunkDJ3T7VVSjs.a.warn("Open redirect blocked (suspicious path part)",{part:p}),r;return o},E= exports.extractSafeRedirectFromUrl =(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let s=decodeURIComponent(t);return h(s,r)}catch(o){return _chunkDJ3T7VVSjs.a.warn("Error parsing redirect parameter",o instanceof Error?{errorMessage:o.message}:{message:String(o)}),r}};function L({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:s,isInitialized:p,tokens:l,error:y}=_chunkE2B7CUHDjs.j.call(void 0, ),d=_reactrouterdom.useLocation.call(void 0, );if(!p||s)return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:r||_jsxruntime.jsx.call(void 0, T,{stage:"validating-session"})});let u=t&&_optionalChain([l, 'optionalAccess', _2 => _2.accessToken])&&l.accessToken.length>0;if(y||!t||!u){l&&(!l.accessToken||l.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let A=d.pathname+d.search,C=h(A),x=encodeURIComponent(C);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:`${o}?redirect=${x}`,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function F({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=_chunkE2B7CUHDjs.j.call(void 0, ),t=_reactrouterdom.useLocation.call(void 0, );if(o){let s=new URLSearchParams(t.search),p=E(s,r);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:p,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}var N=_react.createContext.call(void 0, void 0),tr= exports.CrudifyInitializer =({config:e,children:r,fallback:o=null,onInitialized:t,onError:s})=>{let[p,l]=_react.useState.call(void 0, !1),[y,d]=_react.useState.call(void 0, !1),[u,A]=_react.useState.call(void 0, null),C=_react.useRef.call(void 0, !1),x=_react.useRef.call(void 0, !1);_react.useEffect.call(void 0, ()=>{C.current||(_chunkE2B7CUHDjs.o.registerHighPriorityInitializer(),C.current=!0),x.current||(x.current=!0,(async()=>{console.log("[CRUDIFY_DEBUG] CrudifyInitializer.initializeAsync() starting"),console.log("[CRUDIFY_DEBUG] config prop:",e),console.log("[CRUDIFY_DEBUG] document.cookie:",document.cookie),d(!0),A(null);try{let c=_chunkDJ3T7VVSjs.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _3 => _3.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _4 => _4.env]),enableDebug:_optionalChain([e, 'optionalAccess', _5 => _5.enableLogging])});if(console.log("[CRUDIFY_DEBUG] resolvedConfig:",c),!c.publicApiKey)throw console.error("[CRUDIFY_DEBUG] No publicApiKey found in resolvedConfig!"),new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");let R=c.env||"prod";_chunkDJ3T7VVSjs.a.setEnvironment(R),await _chunkE2B7CUHDjs.o.initialize({priority:"HIGH",publicApiKey:c.publicApiKey,env:c.env||"prod",enableLogging:_optionalChain([e, 'optionalAccess', _6 => _6.enableLogging]),requestedBy:"CrudifyInitializer"}),l(!0),d(!1),t&&t()}catch(c){let R=c instanceof Error?c:new Error(String(c));A(R),d(!1),s&&s(R)}})())},[_optionalChain([e, 'optionalAccess', _7 => _7.publicApiKey]),_optionalChain([e, 'optionalAccess', _8 => _8.env]),_optionalChain([e, 'optionalAccess', _9 => _9.enableLogging]),t,s]);let _={isInitialized:p,isInitializing:y,error:u};return y&&o?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:o}):(u&&_chunkDJ3T7VVSjs.a.error("[CrudifyInitializer] Initialization failed",u),_jsxruntime.jsx.call(void 0, N.Provider,{value:_,children:r}))},ir= exports.useCrudifyInitializer =()=>{let e=_react.useContext.call(void 0, N);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};var _crudifyadmin = require('@nocios/crudify-admin'); var _crudifyadmin2 = _interopRequireDefault(_crudifyadmin);var G=!1,g=null;async function sr(){let r=_chunkE2B7CUHDjs.e.getInstance().getTokenInfo(),o=_optionalChain([r, 'optionalAccess', _10 => _10.apiEndpointAdmin]),t=_optionalChain([r, 'optionalAccess', _11 => _11.apiKeyEndpointAdmin]);return o&&t?{apiUrl:o,apiKey:t}:_chunkE2B7CUHDjs.a.waitForCredentials()}async function ar(){if(!G)return g||(g=(async()=>{try{let e=_chunkE2B7CUHDjs.e.getInstance(),{apiUrl:r,apiKey:o}=await sr();_crudifyadmin2.default.init({url:r,apiKey:o,getAdditionalHeaders:()=>{let t=e.getTokenInfo();return _optionalChain([t, 'optionalAccess', _12 => _12.crudifyTokens, 'optionalAccess', _13 => _13.accessToken])?{Authorization:`Bearer ${t.crudifyTokens.accessToken}`}:{}}}),G=!0}catch(e){throw g=null,_chunkDJ3T7VVSjs.a.error("[crudifyAdminWrapper] Initialization failed",e instanceof Error?e:{message:String(e)}),e}})(),g)}async function n(e){try{await ar();let r=await e(),o=r.errors&&(typeof r.errors=="string"&&r.errors.includes("401")||Array.isArray(r.errors)&&r.errors.some(t=>typeof t=="string"&&t.includes("401")));return!r.success&&o?await _chunkE2B7CUHDjs.e.getInstance().refreshTokens()?await e():(_chunkDJ3T7VVSjs.a.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),r):r}catch(r){return _chunkDJ3T7VVSjs.a.error("[crudifyAdmin] Operation error",r instanceof Error?r:{message:String(r)}),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var pr={listModules:()=>n(()=>_crudifyadmin2.default.listModules()),getModule:e=>n(()=>_crudifyadmin2.default.getModule(e)),createModule:e=>n(()=>_crudifyadmin2.default.createModule(e)),editModule:(e,r)=>n(()=>_crudifyadmin2.default.editModule(e,r)),deleteModule:e=>n(()=>_crudifyadmin2.default.deleteModule(e)),activateModule:e=>n(()=>_crudifyadmin2.default.activateModule(e)),deactivateModule:e=>n(()=>_crudifyadmin2.default.deactivateModule(e)),getModuleVersions:e=>n(()=>_crudifyadmin2.default.getModuleVersions(e)),listActions:e=>n(()=>_crudifyadmin2.default.listActions(e)),getAction:e=>n(()=>_crudifyadmin2.default.getAction(e)),createAction:e=>n(()=>_crudifyadmin2.default.createAction(e)),editAction:(e,r)=>n(()=>_crudifyadmin2.default.editAction(e,r)),deleteAction:e=>n(()=>_crudifyadmin2.default.deleteAction(e)),activateAction:e=>n(()=>_crudifyadmin2.default.activateAction(e)),deactivateAction:e=>n(()=>_crudifyadmin2.default.deactivateAction(e)),getActionVersions:e=>n(()=>_crudifyadmin2.default.getActionVersions(e)),getActionsByProfile:e=>n(()=>_crudifyadmin2.default.getActionsByProfile(e)),updateActionsProfiles:e=>n(()=>_crudifyadmin2.default.updateActionsProfiles(e))};exports.AuthRoute = F; exports.CRITICAL_TRANSLATIONS = _chunkFK52OAX7js.a; exports.CrudiaAutoGenerate = _chunkFK52OAX7js.o; exports.CrudiaFileField = _chunkFK52OAX7js.p; exports.CrudiaMarkdownField = _chunkFK52OAX7js.q; exports.CrudifyInitializationManager = _chunkE2B7CUHDjs.n; exports.CrudifyInitializer = tr; exports.CrudifyLogin = _chunkFK52OAX7js.h; exports.CrudifyProvider = _chunkE2B7CUHDjs.b; exports.CrudifyThemeProvider = Ke; exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.GlobalNotificationProvider = _chunkE2B7CUHDjs.g; exports.LoginComponent = _chunkFK52OAX7js.m; exports.POLICY_ACTIONS = _chunkFK52OAX7js.j; exports.PREFERRED_POLICY_ORDER = _chunkFK52OAX7js.k; exports.Policies = _chunkFK52OAX7js.l; exports.ProtectedRoute = L; exports.SessionDebugInfo = _chunkE2B7CUHDjs.k; exports.SessionLoadingScreen = T; exports.SessionManager = _chunkE2B7CUHDjs.e; exports.SessionProvider = _chunkE2B7CUHDjs.i; exports.SessionStatus = _chunkFK52OAX7js.n; exports.TokenStorage = _chunkE2B7CUHDjs.d; exports.TranslationService = _chunkFK52OAX7js.d; exports.TranslationsProvider = _chunkFK52OAX7js.f; exports.UserProfileDisplay = _chunkFK52OAX7js.i; exports.createErrorTranslator = _chunkDJ3T7VVSjs.h; exports.crudify = _crudifybrowser2.default; exports.crudifyAdmin = pr; exports.crudifyInitManager = _chunkE2B7CUHDjs.o; exports.decodeJwtSafely = _chunkDJ3T7VVSjs.k; exports.extractSafeRedirectFromUrl = E; exports.getCookie = _chunkDJ3T7VVSjs.b; exports.getCriticalLanguages = _chunkFK52OAX7js.b; exports.getCriticalTranslations = _chunkFK52OAX7js.c; exports.getCurrentUserEmail = _chunkDJ3T7VVSjs.l; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunkDJ3T7VVSjs.m; exports.logger = _chunkDJ3T7VVSjs.a; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.secureLocalStorage = _chunk2M2IM334js.b; exports.secureSessionStorage = _chunk2M2IM334js.a; exports.translateError = _chunkDJ3T7VVSjs.g; exports.translateErrorCode = _chunkDJ3T7VVSjs.e; exports.translateErrorCodes = _chunkDJ3T7VVSjs.f; exports.translationService = _chunkFK52OAX7js.e; exports.useAuth = _chunk7YI7UR5Pjs.b; exports.useAutoGenerate = _chunkE2B7CUHDjs.m; exports.useCrudify = _chunkE2B7CUHDjs.c; exports.useCrudifyInitializer = ir; exports.useCrudifyWithNotifications = _chunk7YI7UR5Pjs.d; exports.useData = _chunk7YI7UR5Pjs.c; exports.useFileUpload = _chunkE2B7CUHDjs.p; exports.useGlobalNotification = _chunkE2B7CUHDjs.h; exports.useSession = _chunkE2B7CUHDjs.f; exports.useSessionContext = _chunkE2B7CUHDjs.j; exports.useTranslations = _chunkFK52OAX7js.g; exports.useUserData = _chunk7YI7UR5Pjs.a; exports.useUserProfile = _chunkE2B7CUHDjs.l; exports.validateInternalRedirect = h;
6
+ `});function T({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, Ye,{}),_jsxruntime.jsxs.call(void 0, "div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[_jsxruntime.jsx.call(void 0, "div",{style:He}),_jsxruntime.jsx.call(void 0, "p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:t})]})]})}var We=/^[a-zA-Z0-9\-_./\?=&%#]+$/,Je=[/^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]/,/\\/],h= exports.validateInternalRedirect =(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return _chunkDJ3T7VVSjs.a.warn("Open redirect blocked (relative path)",{path:e}),r;if(!We.test(o))return _chunkDJ3T7VVSjs.a.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let p of Je)if(p.test(t))return _chunkDJ3T7VVSjs.a.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let s=o.split("?")[0].split("/").filter(Boolean);if(s.length===0)return o;for(let p of s)if(p===".."||p.includes(":")||p.length>100)return _chunkDJ3T7VVSjs.a.warn("Open redirect blocked (suspicious path part)",{part:p}),r;return o},E= exports.extractSafeRedirectFromUrl =(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let s=decodeURIComponent(t);return h(s,r)}catch(o){return _chunkDJ3T7VVSjs.a.warn("Error parsing redirect parameter",o instanceof Error?{errorMessage:o.message}:{message:String(o)}),r}};function L({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:s,isInitialized:p,tokens:l,error:y}=_chunkL7LTBWM5js.j.call(void 0, ),d=_reactrouterdom.useLocation.call(void 0, );if(!p||s)return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:r||_jsxruntime.jsx.call(void 0, T,{stage:"validating-session"})});let u=t&&_optionalChain([l, 'optionalAccess', _2 => _2.accessToken])&&l.accessToken.length>0;if(y||!t||!u){l&&(!l.accessToken||l.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let A=d.pathname+d.search,C=h(A),x=encodeURIComponent(C);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:`${o}?redirect=${x}`,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function F({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=_chunkL7LTBWM5js.j.call(void 0, ),t=_reactrouterdom.useLocation.call(void 0, );if(o){let s=new URLSearchParams(t.search),p=E(s,r);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:p,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}var N=_react.createContext.call(void 0, void 0),tr= exports.CrudifyInitializer =({config:e,children:r,fallback:o=null,onInitialized:t,onError:s})=>{let[p,l]=_react.useState.call(void 0, !1),[y,d]=_react.useState.call(void 0, !1),[u,A]=_react.useState.call(void 0, null),C=_react.useRef.call(void 0, !1),x=_react.useRef.call(void 0, !1);_react.useEffect.call(void 0, ()=>{C.current||(_chunkL7LTBWM5js.o.registerHighPriorityInitializer(),C.current=!0),x.current||(x.current=!0,(async()=>{console.log("[CRUDIFY_DEBUG] CrudifyInitializer.initializeAsync() starting"),console.log("[CRUDIFY_DEBUG] config prop:",e),console.log("[CRUDIFY_DEBUG] document.cookie:",document.cookie),d(!0),A(null);try{let c=_chunkDJ3T7VVSjs.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _3 => _3.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _4 => _4.env]),enableDebug:_optionalChain([e, 'optionalAccess', _5 => _5.enableLogging])});if(console.log("[CRUDIFY_DEBUG] resolvedConfig:",c),!c.publicApiKey)throw console.error("[CRUDIFY_DEBUG] No publicApiKey found in resolvedConfig!"),new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");let R=c.env||"prod";_chunkDJ3T7VVSjs.a.setEnvironment(R),await _chunkL7LTBWM5js.o.initialize({priority:"HIGH",publicApiKey:c.publicApiKey,env:c.env||"prod",enableLogging:_optionalChain([e, 'optionalAccess', _6 => _6.enableLogging]),requestedBy:"CrudifyInitializer"}),l(!0),d(!1),t&&t()}catch(c){let R=c instanceof Error?c:new Error(String(c));A(R),d(!1),s&&s(R)}})())},[_optionalChain([e, 'optionalAccess', _7 => _7.publicApiKey]),_optionalChain([e, 'optionalAccess', _8 => _8.env]),_optionalChain([e, 'optionalAccess', _9 => _9.enableLogging]),t,s]);let _={isInitialized:p,isInitializing:y,error:u};return y&&o?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:o}):(u&&_chunkDJ3T7VVSjs.a.error("[CrudifyInitializer] Initialization failed",u),_jsxruntime.jsx.call(void 0, N.Provider,{value:_,children:r}))},ir= exports.useCrudifyInitializer =()=>{let e=_react.useContext.call(void 0, N);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};var _crudifyadmin = require('@nocios/crudify-admin'); var _crudifyadmin2 = _interopRequireDefault(_crudifyadmin);var G=!1,g=null;async function sr(){let r=_chunkL7LTBWM5js.e.getInstance().getTokenInfo(),o=_optionalChain([r, 'optionalAccess', _10 => _10.apiEndpointAdmin]),t=_optionalChain([r, 'optionalAccess', _11 => _11.apiKeyEndpointAdmin]);return o&&t?{apiUrl:o,apiKey:t}:_chunkL7LTBWM5js.a.waitForCredentials()}async function ar(){if(!G)return g||(g=(async()=>{try{let e=_chunkL7LTBWM5js.e.getInstance(),{apiUrl:r,apiKey:o}=await sr();_crudifyadmin2.default.init({url:r,apiKey:o,getAdditionalHeaders:()=>{let t=e.getTokenInfo();return _optionalChain([t, 'optionalAccess', _12 => _12.crudifyTokens, 'optionalAccess', _13 => _13.accessToken])?{Authorization:`Bearer ${t.crudifyTokens.accessToken}`}:{}}}),G=!0}catch(e){throw g=null,_chunkDJ3T7VVSjs.a.error("[crudifyAdminWrapper] Initialization failed",e instanceof Error?e:{message:String(e)}),e}})(),g)}async function n(e){try{await ar();let r=await e(),o=r.errors&&(typeof r.errors=="string"&&r.errors.includes("401")||Array.isArray(r.errors)&&r.errors.some(t=>typeof t=="string"&&t.includes("401")));return!r.success&&o?await _chunkL7LTBWM5js.e.getInstance().refreshTokens()?await e():(_chunkDJ3T7VVSjs.a.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),r):r}catch(r){return _chunkDJ3T7VVSjs.a.error("[crudifyAdmin] Operation error",r instanceof Error?r:{message:String(r)}),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var pr={listModules:()=>n(()=>_crudifyadmin2.default.listModules()),getModule:e=>n(()=>_crudifyadmin2.default.getModule(e)),createModule:e=>n(()=>_crudifyadmin2.default.createModule(e)),editModule:(e,r)=>n(()=>_crudifyadmin2.default.editModule(e,r)),deleteModule:e=>n(()=>_crudifyadmin2.default.deleteModule(e)),activateModule:e=>n(()=>_crudifyadmin2.default.activateModule(e)),deactivateModule:e=>n(()=>_crudifyadmin2.default.deactivateModule(e)),getModuleVersions:e=>n(()=>_crudifyadmin2.default.getModuleVersions(e)),listActions:e=>n(()=>_crudifyadmin2.default.listActions(e)),getAction:e=>n(()=>_crudifyadmin2.default.getAction(e)),createAction:e=>n(()=>_crudifyadmin2.default.createAction(e)),editAction:(e,r)=>n(()=>_crudifyadmin2.default.editAction(e,r)),deleteAction:e=>n(()=>_crudifyadmin2.default.deleteAction(e)),activateAction:e=>n(()=>_crudifyadmin2.default.activateAction(e)),deactivateAction:e=>n(()=>_crudifyadmin2.default.deactivateAction(e)),getActionVersions:e=>n(()=>_crudifyadmin2.default.getActionVersions(e)),getActionsByProfile:e=>n(()=>_crudifyadmin2.default.getActionsByProfile(e)),updateActionsProfiles:e=>n(()=>_crudifyadmin2.default.updateActionsProfiles(e))};exports.AuthRoute = F; exports.CRITICAL_TRANSLATIONS = _chunkUDDA2MQQjs.a; exports.CrudiaAutoGenerate = _chunkUDDA2MQQjs.o; exports.CrudiaFileField = _chunkUDDA2MQQjs.p; exports.CrudiaMarkdownField = _chunkUDDA2MQQjs.q; exports.CrudifyInitializationManager = _chunkL7LTBWM5js.n; exports.CrudifyInitializer = tr; exports.CrudifyLogin = _chunkUDDA2MQQjs.h; exports.CrudifyProvider = _chunkL7LTBWM5js.b; exports.CrudifyThemeProvider = Ke; exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.GlobalNotificationProvider = _chunkL7LTBWM5js.g; exports.LoginComponent = _chunkUDDA2MQQjs.m; exports.POLICY_ACTIONS = _chunkUDDA2MQQjs.j; exports.PREFERRED_POLICY_ORDER = _chunkUDDA2MQQjs.k; exports.Policies = _chunkUDDA2MQQjs.l; exports.ProtectedRoute = L; exports.SessionDebugInfo = _chunkL7LTBWM5js.k; exports.SessionLoadingScreen = T; exports.SessionManager = _chunkL7LTBWM5js.e; exports.SessionProvider = _chunkL7LTBWM5js.i; exports.SessionStatus = _chunkUDDA2MQQjs.n; exports.TokenStorage = _chunkL7LTBWM5js.d; exports.TranslationService = _chunkUDDA2MQQjs.d; exports.TranslationsProvider = _chunkUDDA2MQQjs.f; exports.UserProfileDisplay = _chunkUDDA2MQQjs.i; exports.createErrorTranslator = _chunkDJ3T7VVSjs.h; exports.crudify = _crudifybrowser2.default; exports.crudifyAdmin = pr; exports.crudifyInitManager = _chunkL7LTBWM5js.o; exports.decodeJwtSafely = _chunkDJ3T7VVSjs.k; exports.extractSafeRedirectFromUrl = E; exports.getCookie = _chunkDJ3T7VVSjs.b; exports.getCriticalLanguages = _chunkUDDA2MQQjs.b; exports.getCriticalTranslations = _chunkUDDA2MQQjs.c; exports.getCurrentUserEmail = _chunkDJ3T7VVSjs.l; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunkDJ3T7VVSjs.m; exports.logger = _chunkDJ3T7VVSjs.a; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.secureLocalStorage = _chunk2M2IM334js.b; exports.secureSessionStorage = _chunk2M2IM334js.a; exports.translateError = _chunkDJ3T7VVSjs.g; exports.translateErrorCode = _chunkDJ3T7VVSjs.e; exports.translateErrorCodes = _chunkDJ3T7VVSjs.f; exports.translationService = _chunkUDDA2MQQjs.e; exports.useAuth = _chunkE342MLZOjs.b; exports.useAutoGenerate = _chunkL7LTBWM5js.m; exports.useCrudify = _chunkL7LTBWM5js.c; exports.useCrudifyInitializer = ir; exports.useCrudifyWithNotifications = _chunkE342MLZOjs.d; exports.useData = _chunkE342MLZOjs.c; exports.useFileUpload = _chunkL7LTBWM5js.p; exports.useGlobalNotification = _chunkL7LTBWM5js.h; exports.useSession = _chunkL7LTBWM5js.f; exports.useSessionContext = _chunkL7LTBWM5js.j; exports.useTranslations = _chunkUDDA2MQQjs.g; exports.useUserData = _chunkE342MLZOjs.a; exports.useUserProfile = _chunkL7LTBWM5js.l; exports.validateInternalRedirect = h;
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{a as K,b as B,c as V,d as H,e as Y,f as q,g as W,h as ye,i as Ce,j as xe,k as Re,l as Pe,m as Ie,n as he,o as Se,p as Ue,q as Me}from"./chunk-5GNPQK6D.mjs";import{a as ze,b as ke,c as be,d as Fe}from"./chunk-HVWKFUDX.mjs";import{a as z,b as J,c as $,d as Z,e as f,f as re,g as ne,h as se,i as ae,j as m,k as pe,l as Ae,m as ve,n as Te,o as P,p as Ee}from"./chunk-EWX62JA4.mjs";import{a as Le,b as we}from"./chunk-PXFVXBFM.mjs";import{a as ce,b as le,c as de,d as ue,e as fe,f as me,g as ge}from"./chunk-BJ6PIVZR.mjs";import{a,b as S,c as M,e as Q,f as X,g as j,h as ee,k as oe,l as te,m as ie}from"./chunk-HQKET2ZX.mjs";import{default as Zr}from"@nocios/crudify-browser";export*from"@nocios/crudify-browser";import{useMemo as De}from"react";import{ThemeProvider as Oe,createTheme as Ne,CssBaseline as Ge}from"@mui/material";import{jsx as Be,jsxs as Ve}from"react/jsx-runtime";var _e=(e={})=>{try{let r=S("theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){a.warn("Error parsing theme from cookie",r instanceof Error?{errorMessage:r.message}:{message:String(r)})}return e};function Ke({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=De(()=>{let s=_e(r);return Ne(s)},[r]);return Ve(Oe,{theme:t,children:[!o&&Be(Ge,{}),e]})}import{Navigate as $e,useLocation as Ze}from"react-router-dom";import{Fragment as qe,jsx as I,jsxs as k}from"react/jsx-runtime";var He={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},Ye=()=>I("style",{children:`
1
+ import{a as K,b as B,c as V,d as H,e as Y,f as q,g as W,h as ye,i as Ce,j as xe,k as Re,l as Pe,m as Ie,n as he,o as Se,p as Ue,q as Me}from"./chunk-YSQ33BDT.mjs";import{a as ze,b as ke,c as be,d as Fe}from"./chunk-HI2IXLS6.mjs";import{a as z,b as J,c as $,d as Z,e as f,f as re,g as ne,h as se,i as ae,j as m,k as pe,l as Ae,m as ve,n as Te,o as P,p as Ee}from"./chunk-7DIOFA73.mjs";import{a as Le,b as we}from"./chunk-PXFVXBFM.mjs";import{a as ce,b as le,c as de,d as ue,e as fe,f as me,g as ge}from"./chunk-BJ6PIVZR.mjs";import{a,b as S,c as M,e as Q,f as X,g as j,h as ee,k as oe,l as te,m as ie}from"./chunk-HQKET2ZX.mjs";import{default as Zr}from"@nocios/crudify-browser";export*from"@nocios/crudify-browser";import{useMemo as De}from"react";import{ThemeProvider as Oe,createTheme as Ne,CssBaseline as Ge}from"@mui/material";import{jsx as Be,jsxs as Ve}from"react/jsx-runtime";var _e=(e={})=>{try{let r=S("theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){a.warn("Error parsing theme from cookie",r instanceof Error?{errorMessage:r.message}:{message:String(r)})}return e};function Ke({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=De(()=>{let s=_e(r);return Ne(s)},[r]);return Ve(Oe,{theme:t,children:[!o&&Be(Ge,{}),e]})}import{Navigate as $e,useLocation as Ze}from"react-router-dom";import{Fragment as qe,jsx as I,jsxs as k}from"react/jsx-runtime";var He={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},Ye=()=>I("style",{children:`
2
2
  @keyframes spin {
3
3
  0% { transform: rotate(0deg); }
4
4
  100% { transform: rotate(360deg); }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocios/crudify-ui",
3
- "version": "4.4.82",
3
+ "version": "4.4.84",
4
4
  "description": "Biblioteca de componentes UI para Crudify",
5
5
  "author": "Nocios",
6
6
  "license": "MIT",
@@ -1,3 +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 _chunkDJ3T7VVSjs = require('./chunk-DJ3T7VVS.js');var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var de=class n{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return n.instance||(n.instance=new n),n.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){_chunkDJ3T7VVSjs.a.error("[CredentialsEventBus] Error in listener",t instanceof Error?t:{message:String(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}},J= exports.a =de.getInstance();var _jsxruntime = require('react/jsx-runtime');var Ae=_react.createContext.call(void 0, void 0),ke= exports.b =({config:n,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[r,s]=_react.useState.call(void 0, null),[d,m]=_react.useState.call(void 0, !1),[D,T]=_react.useState.call(void 0, ""),[E,b]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!n.publicApiKey){s("No publicApiKey provided"),t(!1),m(!1);return}let a=`${n.publicApiKey}-${n.env}`;if(a===D&&d){t(!1);return}(async()=>{t(!0),s(null),m(!1);try{_crudifybrowser2.default.config(n.env||"prod");let c=await _crudifybrowser2.default.init(n.publicApiKey,"none");if(b(c),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")m(!0),T(a),c.apiEndpointAdmin&&c.apiKeyEndpointAdmin&&J.notifyCredentialsReady({apiUrl:c.apiEndpointAdmin,apiKey:c.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(c){let y=c instanceof Error?c.message:"Failed to initialize Crudify";_chunkDJ3T7VVSjs.a.error("[CrudifyProvider] Initialization error",c instanceof Error?c:{message:String(c)}),s(y),m(!1)}finally{t(!1)}})()},[n.publicApiKey,n.env,D,d]);let l={crudify:d?_crudifybrowser2.default:null,isLoading:e,error:r,isInitialized:d,adminCredentials:E};return _jsxruntime.jsx.call(void 0, Ae.Provider,{value:l,children:i})},be= exports.c =()=>{let n=_react.useContext.call(void 0, Ae);if(n===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return n};var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var f=class f{static setStorageType(i){f.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(f.encryptionKey)return f.encryptionKey;let i=window.localStorage;if(!i)return f.encryptionKey=f.generateEncryptionKey(),f.encryptionKey;try{let e=i.getItem(f.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=f.generateEncryptionKey(),i.setItem(f.ENCRYPTION_KEY_STORAGE,e)),f.encryptionKey=e,e}catch (e2){return _chunkDJ3T7VVSjs.a.warn("Crudify: Cannot persist encryption key, using temporary key"),f.encryptionKey=f.generateEncryptionKey(),f.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 f.storageType==="none"?null:f.isStorageAvailable(f.storageType)?window[f.storageType]:(_chunkDJ3T7VVSjs.a.warn(`Crudify: ${f.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=f.getEncryptionKey();return _cryptojs2.default.AES.encrypt(i,e).toString()}catch(e){return _chunkDJ3T7VVSjs.a.error("Crudify: Encryption failed",e instanceof Error?e:{message:String(e)}),i}}static decrypt(i){try{let e=f.getEncryptionKey();return _cryptojs2.default.AES.decrypt(i,e).toString(_cryptojs2.default.enc.Utf8)||i}catch(e){return _chunkDJ3T7VVSjs.a.error("Crudify: Decryption failed",e instanceof Error?e:{message:String(e)}),i}}static saveTokens(i){let e=f.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},r=f.encrypt(JSON.stringify(t));e.setItem(f.TOKEN_KEY,r),_chunkDJ3T7VVSjs.a.debug("Crudify: Tokens saved successfully")}catch(t){_chunkDJ3T7VVSjs.a.error("Crudify: Failed to save tokens",t instanceof Error?t:{message:String(t)})}}static getTokens(){let i=f.getStorage();if(!i)return null;try{let e=i.getItem(f.TOKEN_KEY);if(!e)return null;let t=f.decrypt(e),r=JSON.parse(t);return!r.accessToken||!r.refreshToken||!r.expiresAt||!r.refreshExpiresAt?(_chunkDJ3T7VVSjs.a.warn("Crudify: Incomplete token data found, clearing storage"),f.clearTokens(),null):Date.now()>=r.refreshExpiresAt?(_chunkDJ3T7VVSjs.a.info("Crudify: Refresh token expired, clearing storage"),f.clearTokens(),null):{accessToken:r.accessToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,refreshExpiresAt:r.refreshExpiresAt}}catch(e){return _chunkDJ3T7VVSjs.a.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),f.clearTokens(),null}}static clearTokens(){let i=f.getStorage();if(i)try{i.removeItem(f.TOKEN_KEY),_chunkDJ3T7VVSjs.a.debug("Crudify: Tokens cleared from storage")}catch(e){_chunkDJ3T7VVSjs.a.error("Crudify: Failed to clear tokens",e instanceof Error?e:{message:String(e)})}}static rotateEncryptionKey(){try{f.clearTokens(),f.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(f.ENCRYPTION_KEY_STORAGE),_chunkDJ3T7VVSjs.a.info("Crudify: Encryption key rotated successfully")}catch(i){_chunkDJ3T7VVSjs.a.error("Crudify: Failed to rotate encryption key",i instanceof Error?i:{message:String(i)})}}static hasValidTokens(){return f.getTokens()!==null}static getExpirationInfo(){let i=f.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=f.getTokens();if(!t){_chunkDJ3T7VVSjs.a.warn("Crudify: Cannot update access token, no existing tokens found");return}f.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===f.TOKEN_KEY){if(t.newValue===null){_chunkDJ3T7VVSjs.a.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){_chunkDJ3T7VVSjs.a.debug("Crudify: Tokens updated in another tab");let r=f.getTokens();i(r)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};f.TOKEN_KEY="crudify_tokens",f.ENCRYPTION_KEY_STORAGE="crudify_enc_key",f.encryptionKey=null,f.storageType="localStorage";var v=f;var ee=class n{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return n.instance||(n.instance=new n),n.instance}async initialize(i={}){if(console.log("[CRUDIFY_DEBUG] SessionManager.initialize() called"),this.initialized){console.log("[CRUDIFY_DEBUG] SessionManager already initialized, skipping");return}if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},console.log("[CRUDIFY_DEBUG] SessionManager config set, env:",this.config.env),v.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&(console.log("[CRUDIFY_DEBUG] About to initialize crudify SDK"),await this.ensureCrudifyInitialized(),console.log("[CRUDIFY_DEBUG] crudify SDK initialized")),_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkDJ3T7VVSjs.i.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=v.getTokens();e?v.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):v.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&(console.log("[CRUDIFY_DEBUG] About to restore session"),await this.restoreSession(),console.log("[CRUDIFY_DEBUG] Session restored (or no session to restore)")),this.initialized=!0,console.log("[CRUDIFY_DEBUG] SessionManager.initialize() completed successfully")}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 r=v.getTokens(),s=t.data,d={accessToken:s.token,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt,apiEndpointAdmin:_optionalChain([r, 'optionalAccess', _2 => _2.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([r, 'optionalAccess', _3 => _3.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return v.saveTokens(d),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.onLoginSuccess, 'optionalCall', _6 => _6(d)]),{success:!0,tokens:d,data:s}}catch(t){return _chunkDJ3T7VVSjs.a.error("[SessionManager] Login error",t instanceof Error?t:{message:String(t)}),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await _crudifybrowser2.default.logout(),v.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),v.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=v.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"),v.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 r=v.getTokens();return r&&_optionalChain([this, 'access', _10 => _10.config, 'access', _11 => _11.onSessionRestored, 'optionalCall', _12 => _12(r)]),!0}return v.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),v.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||v.hasValidTokens()}getTokenInfo(){let i=_crudifybrowser2.default.getTokenData(),e=v.getExpirationInfo(),t=v.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:v.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),v.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=i.data,t={accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt};return v.saveTokens(t),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),v.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"),_chunkDJ3T7VVSjs.i.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(v.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunkDJ3T7VVSjs.i.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"),_chunkDJ3T7VVSjs.i.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(console.log("[CRUDIFY_DEBUG] ensureCrudifyInitialized() called"),this.crudifyInitialized){console.log("[CRUDIFY_DEBUG] crudify already initialized, skipping");return}try{this.log("Initializing crudify SDK...");let i=_crudifybrowser2.default.getTokenData();if(console.log("[CRUDIFY_DEBUG] Existing tokenData:",i?"exists":"null"),i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0,console.log("[CRUDIFY_DEBUG] Crudify was already initialized by another service");return}let e=this.config.env||"stg";console.log("[CRUDIFY_DEBUG] Configuring crudify with env:",e),_crudifybrowser2.default.config(e);let t=this.config.publicApiKey,r=this.config.enableLogging?"debug":"none";console.log("[CRUDIFY_DEBUG] Calling crudify.init() with apiKey:",_optionalChain([t, 'optionalAccess', _30 => _30.substring, 'call', _31 => _31(0,8)])+"...","logLevel:",r);let s=await _crudifybrowser2.default.init(t,r);if(console.log("[CRUDIFY_DEBUG] crudify.init() response:",JSON.stringify(s)),s&&s.success===!1&&s.errors)throw console.error("[CRUDIFY_DEBUG] crudify.init() FAILED:",s.errors),new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully"),console.log("[CRUDIFY_DEBUG] crudify SDK initialized successfully")}catch(i){throw console.error("[CRUDIFY_DEBUG] ensureCrudifyInitialized FAILED:",i),_chunkDJ3T7VVSjs.a.error("[SessionManager] Failed to initialize crudify",i instanceof Error?i:{message:String(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(r=>r.errorType==="Unauthorized"||_optionalChain([r, 'access', _32 => _32.message, 'optionalAccess', _33 => _33.includes, 'call', _34 => _34("Unauthorized")])||_optionalChain([r, 'access', _35 => _35.message, 'optionalAccess', _36 => _36.includes, 'call', _37 => _37("Not Authorized")])||_optionalChain([r, 'access', _38 => _38.message, 'optionalAccess', _39 => _39.includes, 'call', _40 => _40("NOT_AUTHORIZED")])||_optionalChain([r, 'access', _41 => _41.message, 'optionalAccess', _42 => _42.includes, 'call', _43 => _43("Token")])||_optionalChain([r, 'access', _44 => _44.message, 'optionalAccess', _45 => _45.includes, 'call', _46 => _46("TOKEN")])||_optionalChain([r, 'access', _47 => _47.message, 'optionalAccess', _48 => _48.includes, 'call', _49 => _49("Authentication")])||_optionalChain([r, 'access', _50 => _50.message, 'optionalAccess', _51 => _51.includes, 'call', _52 => _52("UNAUTHENTICATED")])||_optionalChain([r, 'access', _53 => _53.extensions, 'optionalAccess', _54 => _54.code])==="UNAUTHENTICATED"||_optionalChain([r, 'access', _55 => _55.extensions, 'optionalAccess', _56 => _56.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', _57 => _57.message, 'optionalAccess', _58 => _58.includes, 'call', _59 => _59("TOKEN")])||_optionalChain([t, 'access', _60 => _60.message, 'optionalAccess', _61 => _61.includes, 'call', _62 => _62("Token")]))&&(e.isTokenExpired=!0),_optionalChain([t, 'access', _63 => _63.extensions, 'optionalAccess', _64 => _64.code])==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let r=Object.values(i.errors).flat().find(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.includes("INVALID_TOKEN")));r&&typeof r=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,r.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."):r.includes("TOKEN_HAS_EXPIRED")||r.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):r.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', _65 => _65.data, 'optionalAccess', _66 => _66.response, 'optionalAccess', _67 => _67.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', _68 => _68.data, 'optionalAccess', _69 => _69.response, 'optionalAccess', _70 => _70.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=String(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(){v.clearTokens(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkDJ3T7VVSjs.e.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().map(String).join(", "):"Authentication failed":"Unknown error"}};function Se(n={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=l=>{e(a=>{let o=typeof l=="function"?l(a):l;return o.error!==a.error&&console.log("[CRUDIFY_DEBUG] \u{1F534} STATE ERROR CHANGED:",{from:a.error,to:o.error,stack:_optionalChain([new Error(), 'access', _71 => _71.stack, 'optionalAccess', _72 => _72.split, 'call', _73 => _73(`
2
- `), 'access', _74 => _74.slice, 'call', _75 => _75(2,6), 'access', _76 => _76.join, 'call', _77 => _77(`
3
- `)])}),o.isAuthenticated!==a.isAuthenticated&&console.log("[CRUDIFY_DEBUG] \u{1F535} AUTH STATE CHANGED:",{from:a.isAuthenticated,to:o.isAuthenticated}),o})},r=ee.getInstance(),s=_react.useCallback.call(void 0, async()=>{console.log("[CRUDIFY_DEBUG] useSession.initialize() called");try{t(c=>({...c,isLoading:!0,error:null}));let l={autoRestore:_nullishCoalesce(n.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(n.enableLogging, () => (!1)),showNotification:n.showNotification,translateFn:n.translateFn,apiEndpointAdmin:n.apiEndpointAdmin,apiKeyEndpointAdmin:n.apiKeyEndpointAdmin,publicApiKey:n.publicApiKey,env:n.env||"stg",onSessionExpired:()=>{console.log("[CRUDIFY_DEBUG] onSessionExpired callback triggered"),t(c=>({...c,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([n, 'access', _78 => _78.onSessionExpired, 'optionalCall', _79 => _79()])},onSessionRestored:c=>{console.log("[CRUDIFY_DEBUG] onSessionRestored callback triggered"),t(y=>({...y,isAuthenticated:!0,tokens:c,error:null})),_optionalChain([n, 'access', _80 => _80.onSessionRestored, 'optionalCall', _81 => _81(c)])},onLoginSuccess:c=>{console.log("[CRUDIFY_DEBUG] onLoginSuccess callback triggered"),t(y=>({...y,isAuthenticated:!0,tokens:c,error:null}))},onLogout:()=>{console.log("[CRUDIFY_DEBUG] onLogout callback triggered"),t(c=>({...c,isAuthenticated:!1,tokens:null,error:null}))}};console.log("[CRUDIFY_DEBUG] About to call sessionManager.initialize()"),await r.initialize(l),console.log("[CRUDIFY_DEBUG] sessionManager.initialize() completed"),r.setupResponseInterceptor(),console.log("[CRUDIFY_DEBUG] Response interceptor configured");let a=r.isAuthenticated(),o=r.getTokenInfo();console.log("[CRUDIFY_DEBUG] isAuth:",a,"hasAccessToken:",!!o.crudifyTokens.accessToken),t(c=>({...c,isAuthenticated:a,isInitialized:!0,isLoading:!1,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null})),console.log("[CRUDIFY_DEBUG] Initialize completed successfully")}catch(l){let a=l instanceof Error?l.message:"Initialization failed";console.error("[CRUDIFY_DEBUG] Initialize FAILED with error:",a,l),t(o=>({...o,isLoading:!1,isInitialized:!0,error:a}))}},[n.autoRestore,n.enableLogging,n.onSessionExpired,n.onSessionRestored]),d=_react.useCallback.call(void 0, async(l,a)=>{console.log("[CRUDIFY_DEBUG] login() called with email:",l),t(o=>({...o,isLoading:!0,error:null}));try{console.log("[CRUDIFY_DEBUG] Calling sessionManager.login()");let o=await r.login(l,a);return console.log("[CRUDIFY_DEBUG] sessionManager.login() result:",{success:o.success,hasTokens:!!o.tokens,error:o.error}),o.success&&o.tokens?(console.log("[CRUDIFY_DEBUG] Login SUCCESS, updating state with tokens"),t(c=>({...c,isAuthenticated:!0,tokens:o.tokens,isLoading:!1,error:null})),console.log("[CRUDIFY_DEBUG] State updated after successful login")):(console.log("[CRUDIFY_DEBUG] Login FAILED (no tokens), error:",o.error),t(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))),o}catch(o){let c=o instanceof Error?o.message:"Login failed";console.error("[CRUDIFY_DEBUG] login() CAUGHT EXCEPTION:",c,o);let y=c.includes("INVALID_CREDENTIALS")||c.includes("Invalid email")||c.includes("Invalid password")||c.includes("credentials");return console.log("[CRUDIFY_DEBUG] isCredentialError:",y,"- will set global error:",!y),t(I=>({...I,isAuthenticated:!1,tokens:null,isLoading:!1,error:y?null:c})),{success:!1,error:c}}},[r]),m=_react.useCallback.call(void 0, async()=>{console.log("[CRUDIFY_DEBUG] logout() called"),t(l=>({...l,isLoading:!0}));try{await r.logout(),t(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(l){t(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:l instanceof Error?l.message:"Logout error"}))}},[r]),D=_react.useCallback.call(void 0, async()=>{console.log("[CRUDIFY_DEBUG] refreshTokens() called");try{let l=await r.refreshTokens();if(l){let a=r.getTokenInfo();t(o=>({...o,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null,error:null}))}else t(a=>({...a,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return l}catch(l){return t(a=>({...a,isAuthenticated:!1,tokens:null,error:l instanceof Error?l.message:"Token refresh failed"})),!1}},[r]),T=_react.useCallback.call(void 0, ()=>{console.log("[CRUDIFY_DEBUG] clearError() called"),t(l=>({...l,error:null}))},[]),E=_react.useCallback.call(void 0, ()=>r.getTokenInfo(),[r]);_react.useEffect.call(void 0, ()=>{s()},[s]),_react.useEffect.call(void 0, ()=>{if(!i.isAuthenticated||!i.tokens)return;let l=_chunkDJ3T7VVSjs.j.getInstance(),a=()=>{r.updateLastActivity()},o=l.subscribe(a);window.addEventListener("popstate",a);let c=()=>{let S=r.getTokenInfo().crudifyTokens.expiresIn||0;return S<300*1e3?30*1e3:S<1800*1e3?60*1e3:120*1e3},y,I=()=>{let z=c();y=setTimeout(async()=>{if(r.isRefreshing()){I();return}let S=r.getTokenInfo(),R=S.crudifyTokens.expiresIn||0,k=((S.crudifyTokens.expiresAt||0)-(Date.now()-R))*.5;if(R>0&&R<=k)if(console.log("[CRUDIFY_DEBUG] Token renewal triggered (TTL threshold)"),t(K=>({...K,isLoading:!0})),await r.refreshTokens()){let K=r.getTokenInfo();t(le=>({...le,isLoading:!1,tokens:K.crudifyTokens.accessToken?{accessToken:K.crudifyTokens.accessToken,refreshToken:K.crudifyTokens.refreshToken,expiresAt:K.crudifyTokens.expiresAt,refreshExpiresAt:K.crudifyTokens.refreshExpiresAt}:null}))}else t(K=>({...K,isLoading:!1,isAuthenticated:!1,tokens:null}));let W=r.getTimeSinceLastActivity(),B=1800*1e3;W>B?await m():I()},z)};return I(),()=>{clearTimeout(y),window.removeEventListener("popstate",a),o()}},[i.isAuthenticated,i.tokens,r,n.enableLogging,m]),_react.useEffect.call(void 0, ()=>{let l=_chunkDJ3T7VVSjs.i.subscribe(async a=>{if(a.type==="TOKEN_EXPIRED"){if(console.log("[CRUDIFY_DEBUG] authEventBus received TOKEN_EXPIRED event"),r.isRefreshing()){console.log("[CRUDIFY_DEBUG] Refresh already in progress, ignoring TOKEN_EXPIRED");return}t(o=>({...o,isLoading:!0}));try{if(await r.refreshTokens()){let c=r.getTokenInfo();t(y=>({...y,isLoading:!1,tokens:c.crudifyTokens.accessToken?{accessToken:c.crudifyTokens.accessToken,refreshToken:c.crudifyTokens.refreshToken,expiresAt:c.crudifyTokens.expiresAt,refreshExpiresAt:c.crudifyTokens.refreshExpiresAt}:null}))}else _chunkDJ3T7VVSjs.i.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(o){_chunkDJ3T7VVSjs.i.emit("SESSION_EXPIRED",{message:o instanceof Error?o.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(a.type==="SESSION_EXPIRED"||a.type==="TOKEN_REFRESH_FAILED")&&(console.log("[CRUDIFY_DEBUG] authEventBus received",a.type,"event:",a.details),t(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([a, 'access', _82 => _82.details, 'optionalAccess', _83 => _83.message])||"Session expired"})),_optionalChain([n, 'access', _84 => _84.onSessionExpired, 'optionalCall', _85 => _85()]))});return()=>l()},[n.onSessionExpired,r]),_react.useEffect.call(void 0, ()=>{let l=v.subscribeToChanges(a=>{console.log("[CRUDIFY_DEBUG] Cross-tab storage change detected:",a?"tokens updated":"tokens cleared"),a?t(o=>({...o,tokens:a,isAuthenticated:!0})):(t(o=>({...o,isAuthenticated:!1,tokens:null})),_chunkDJ3T7VVSjs.i.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>l()},[]);let b=_react.useCallback.call(void 0, ()=>{r.updateLastActivity()},[r]);return{...i,login:d,logout:m,refreshTokens:D,clearError:T,getTokenInfo:E,updateActivity:b,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 De=_react.createContext.call(void 0, null),ti=n=>_dompurify2.default.sanitize(n,{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}),fe= exports.g =({children:n,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:r=!1,allowHtml:s=!1})=>{let[d,m]=_react.useState.call(void 0, []),D=_react.useCallback.call(void 0, (l,a="info",o)=>{if(!r)return"";if(!l||typeof l!="string")return _chunkDJ3T7VVSjs.a.warn("GlobalNotificationProvider: Invalid message provided"),"";l.length>1e3&&(_chunkDJ3T7VVSjs.a.warn("GlobalNotificationProvider: Message too long, truncating"),l=l.substring(0,1e3)+"...");let c=_uuid.v4.call(void 0, ),y={id:c,message:l,severity:a,autoHideDuration:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _86 => _86.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _87 => _87.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _88 => _88.allowHtml]), () => (s))};return m(I=>[...I.length>=i?I.slice(-(i-1)):I,y]),c},[i,e,r,s]),T=_react.useCallback.call(void 0, l=>{m(a=>a.filter(o=>o.id!==l))},[]),E=_react.useCallback.call(void 0, ()=>{m([])},[]),b={showNotification:D,hideNotification:T,clearAllNotifications:E};return _jsxruntime.jsxs.call(void 0, De.Provider,{value:b,children:[n,r&&_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:d.map(l=>_jsxruntime.jsx.call(void 0, ri,{notification:l,onClose:()=>T(l.id)},l.id))})})]})},ri=({notification:n,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),r=_react.useCallback.call(void 0, (s,d)=>{d!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return _react.useEffect.call(void 0, ()=>{if(!n.persistent&&n.autoHideDuration){let s=setTimeout(()=>{r()},n.autoHideDuration);return()=>clearTimeout(s)}},[n.autoHideDuration,n.persistent,r]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:e,onClose:r,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:n.severity,onClose:r,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:n.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:ti(n.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:n.message})})})},Re= exports.h =()=>{let n=_react.useContext.call(void 0, De);if(!n)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return n};var we=_react.createContext.call(void 0, void 0);function Ce({children:n,options:i={},config:e,showNotifications:t=!1,notificationOptions:r={}}){let s;try{let{showNotification:o}=Re();s=o}catch (e5){}let d={};try{let o=be();o.isInitialized&&o.adminCredentials&&(d=o.adminCredentials)}catch (e6){}let m=_react.useMemo.call(void 0, ()=>{let o=_chunkDJ3T7VVSjs.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _89 => _89.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _90 => _90.env]),enableDebug:_optionalChain([i, 'optionalAccess', _91 => _91.enableLogging])});return{publicApiKey:o.publicApiKey,env:o.env||"prod"}},[e,_optionalChain([i, 'optionalAccess', _92 => _92.enableLogging])]),D=_react2.default.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:d.apiEndpointAdmin,apiKeyEndpointAdmin:d.apiKeyEndpointAdmin,publicApiKey:m.publicApiKey,env:m.env,onSessionExpired:()=>{_optionalChain([i, 'access', _93 => _93.onSessionExpired, 'optionalCall', _94 => _94()])}}),[i,s,d.apiEndpointAdmin,d.apiKeyEndpointAdmin,m]),T=Se(D),E=_react.useMemo.call(void 0, ()=>{let o=_chunkDJ3T7VVSjs.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _95 => _95.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _96 => _96.env]),appName:_optionalChain([e, 'optionalAccess', _97 => _97.appName]),logo:_optionalChain([e, 'optionalAccess', _98 => _98.logo]),loginActions:_optionalChain([e, 'optionalAccess', _99 => _99.loginActions]),enableDebug:_optionalChain([i, 'optionalAccess', _100 => _100.enableLogging])});return{publicApiKey:o.publicApiKey,env:o.env,appName:o.appName,loginActions:o.loginActions,logo:o.logo}},[e,_optionalChain([i, 'optionalAccess', _101 => _101.enableLogging])]),b=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([T, 'access', _102 => _102.tokens, 'optionalAccess', _103 => _103.accessToken])||!T.isAuthenticated)return null;try{let o=_chunkDJ3T7VVSjs.k.call(void 0, T.tokens.accessToken);if(o&&o.sub&&o.email&&o.subscriber){let c={_id:o.sub,email:o.email,subscriberKey:o.subscriber};return Object.keys(o).forEach(y=>{["sub","email","subscriber"].includes(y)||(c[y]=o[y])}),c}}catch(o){_chunkDJ3T7VVSjs.a.error("Error decoding JWT token for sessionData",o instanceof Error?o:{message:String(o)})}return null},[_optionalChain([T, 'access', _104 => _104.tokens, 'optionalAccess', _105 => _105.accessToken]),T.isAuthenticated]),l={...T,sessionData:b,config:E};T.error&&console.log("[CRUDIFY_DEBUG] SessionProvider contextValue.error:",T.error);let a={enabled:t,maxNotifications:r.maxNotifications||5,defaultAutoHideDuration:r.defaultAutoHideDuration||6e3,position:r.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, we.Provider,{value:l,children:n})}function ct(n){let i={enabled:n.showNotifications,maxNotifications:_optionalChain([n, 'access', _106 => _106.notificationOptions, 'optionalAccess', _107 => _107.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([n, 'access', _108 => _108.notificationOptions, 'optionalAccess', _109 => _109.defaultAutoHideDuration])||6e3,position:_optionalChain([n, 'access', _110 => _110.notificationOptions, 'optionalAccess', _111 => _111.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([n, 'access', _112 => _112.notificationOptions, 'optionalAccess', _113 => _113.allowHtml])||!1};return _optionalChain([n, 'access', _114 => _114.config, 'optionalAccess', _115 => _115.publicApiKey])?_jsxruntime.jsx.call(void 0, ke,{config:{publicApiKey:n.config.publicApiKey,env:n.config.env||"prod",appName:n.config.appName,loginActions:n.config.loginActions,logo:n.config.logo},children:_jsxruntime.jsx.call(void 0, fe,{...i,children:_jsxruntime.jsx.call(void 0, Ce,{...n})})}):_jsxruntime.jsx.call(void 0, fe,{...i,children:_jsxruntime.jsx.call(void 0, Ce,{...n})})}function li(){let n=_react.useContext.call(void 0, we);if(n===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return n}function ut(){let n=li();return n.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:"})," ",n.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",n.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",n.error||"None"]}),n.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:"})," ",n.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",n.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(n.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(n.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",n.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var ht=(n={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=n,[r,s]=_react.useState.call(void 0, null),[d,m]=_react.useState.call(void 0, !1),[D,T]=_react.useState.call(void 0, null),[E,b]=_react.useState.call(void 0, {}),l=_react.useRef.call(void 0, null),a=_react.useRef.call(void 0, !0),o=_react.useRef.call(void 0, 0),c=_react.useRef.call(void 0, 0),y=_react.useCallback.call(void 0, ()=>{s(null),T(null),m(!1),b({})},[]),I=_react.useCallback.call(void 0, async()=>{let z=_chunkDJ3T7VVSjs.l.call(void 0, );if(!z){a.current&&(T("No user email available"),m(!1));return}l.current&&l.current.abort();let S=new AbortController;l.current=S;let R=++o.current;try{a.current&&(m(!0),T(null));let P=await _crudifybrowser2.default.readItems("users",{filter:{email:z},pagination:{limit:1}});if(R===o.current&&a.current&&!S.signal.aborted){let O=P.data;if(P.success&&O&&O.length>0){let k=O[0];s(k);let W={fullProfile:k,totalFields:Object.keys(k).length,displayData:{id:k.id,email:k.email,username:k.username,firstName:k.firstName,lastName:k.lastName,fullName:k.fullName||`${k.firstName||""} ${k.lastName||""}`.trim(),role:k.role,permissions:k.permissions||[],isActive:k.isActive,lastLogin:k.lastLogin,createdAt:k.createdAt,updatedAt:k.updatedAt,...Object.keys(k).filter(B=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(B)).reduce((B,Z)=>({...B,[Z]:k[Z]}),{})}};b(W),T(null),c.current=0}else T("User profile not found"),s(null),b({})}}catch(P){if(R===o.current&&a.current){let O=P;if(O.name==="AbortError")return;e&&c.current<t&&(_optionalChain([O, 'access', _116 => _116.message, 'optionalAccess', _117 => _117.includes, 'call', _118 => _118("Network Error")])||_optionalChain([O, 'access', _119 => _119.message, 'optionalAccess', _120 => _120.includes, 'call', _121 => _121("Failed to fetch")]))?(c.current++,setTimeout(()=>{a.current&&I()},1e3*c.current)):(T("Failed to load user profile"),s(null),b({}))}}finally{R===o.current&&a.current&&m(!1),l.current===S&&(l.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{i&&I()},[i,I]),_react.useEffect.call(void 0, ()=>(a.current=!0,()=>{a.current=!1,l.current&&(l.current.abort(),l.current=null)}),[]),{userProfile:r,loading:d,error:D,extendedData:E,refreshProfile:I,clearProfile:y}};var vt=(n,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:r}=i,{prefix:s,padding:d=0,separator:m=""}=n,[D,T]=_react.useState.call(void 0, ""),[E,b]=_react.useState.call(void 0, !1),[l,a]=_react.useState.call(void 0, null),o=_react.useRef.call(void 0, !1),c=_react.useCallback.call(void 0, S=>{let R=String(S).padStart(d,"0");return`${s}${m}${R}`},[s,d,m]),y=_react.useCallback.call(void 0, async()=>{b(!0),a(null);try{let S=await _crudifybrowser2.default.getNextSequence(s),R=S.data;if(S.success&&_optionalChain([R, 'optionalAccess', _122 => _122.value])){let P=c(R.value);T(P),_optionalChain([t, 'optionalCall', _123 => _123(P)])}else{let P=_optionalChain([S, 'access', _124 => _124.errors, 'optionalAccess', _125 => _125._error, 'optionalAccess', _126 => _126[0]])||"Failed to generate code";a(P),_optionalChain([r, 'optionalCall', _127 => _127(P)])}}catch(S){let R=S instanceof Error?S.message:"Unknown error";a(R),_optionalChain([r, 'optionalCall', _128 => _128(R)])}finally{b(!1)}},[s,c,t,r]),I=_react.useCallback.call(void 0, async()=>{await y()},[y]),z=_react.useCallback.call(void 0, ()=>{a(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!D&&!o.current&&(o.current=!0,y())},[e,D,y]),{value:D,loading:E,error:l,regenerate:I,clearError:z}};var he=class n{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 n.instance||(n.instance=new n),n.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:r,enableLogging:s,requestedBy:d}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&_chunkDJ3T7VVSjs.a.warn(`[CrudifyInitialization] ${d} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _129 => _129.state, 'access', _130 => _130.publicApiKey, 'optionalAccess', _131 => _131.slice, 'call', _132 => _132(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&_chunkDJ3T7VVSjs.a.debug(`[CrudifyInitialization] ${d} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&_chunkDJ3T7VVSjs.a.debug(`[CrudifyInitialization] ${d} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(d),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(d),this.getState().status==="INITIALIZED"){s&&_chunkDJ3T7VVSjs.a.debug(`[CrudifyInitialization] ${d} found initialization completed by HIGH priority`);return}s&&_chunkDJ3T7VVSjs.a.warn(`[CrudifyInitialization] ${d} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(_chunkDJ3T7VVSjs.a.warn(`[CrudifyInitialization] HIGH priority request from ${d} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&_chunkDJ3T7VVSjs.a.debug(`[CrudifyInitialization] ${d} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=d,this.initializationPromise=this.performInitialization(t,r,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=r,this.state.error=null,s&&_chunkDJ3T7VVSjs.a.info(`[CrudifyInitialization] Successfully initialized by ${d} (${e} priority)`)}catch(m){throw this.state.status="ERROR",this.state.error=m instanceof Error?m:new Error(String(m)),this.initializationPromise=null,_chunkDJ3T7VVSjs.a.error(`[CrudifyInitialization] Initialization failed for ${d}`,m instanceof Error?m:{message:String(m)}),m}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let r=0,s=setInterval(()=>{if(r+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){r=0;return}r>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),i&&_chunkDJ3T7VVSjs.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let r=_crudifybrowser2.default.getTokenData();if(r&&r.endpoint){t&&_chunkDJ3T7VVSjs.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifybrowser2.default.config(e);let s=t?"debug":"none",d=await _crudifybrowser2.default.init(i,s);if(d.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(d.errors||"Unknown error")}`);d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&J.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin})}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}}},se= exports.o =he.getInstance();var Fe=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,yi=n=>{let i=n.lastIndexOf("."),e=i>0?n.substring(i):"",t=Date.now(),r=Math.random().toString(36).substring(2,8);return`${t}_${r}${e}`},wt= exports.p =(n={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:r=0,visibility:s="private",onUploadComplete:d,onUploadError:m,onFileRemoved:D,onFilesChange:T}=n,[E,b]=_react.useState.call(void 0, []),[l,a]=_react.useState.call(void 0, !1),o=_react.useRef.call(void 0, new Map),c=_react.useCallback.call(void 0, ()=>{a(!0)},[]),y=_react.useCallback.call(void 0, (u,h)=>{b(p=>p.map(A=>A.id===u?{...A,...h}:A))},[]),I=_react.useCallback.call(void 0, u=>{_optionalChain([T, 'optionalCall', _133 => _133(u)])},[T]),z=_react.useCallback.call(void 0, u=>i&&i.length>0&&!i.includes(u.type)?{valid:!1,error:`File type not allowed: ${u.type}`}:u.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),S=_react.useCallback.call(void 0, async(u,h)=>{try{if(!se.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let p=yi(h.name),x=await _crudifybrowser2.default.generateSignedUrl({fileName:p,contentType:h.type,visibility:s});if(!x.success||!x.data)throw new Error("Failed to get upload URL");let A=x.data,{uploadUrl:N,s3Key:C,publicUrl:G}=A;if(!N||!C)throw new Error("Incomplete signed URL response");let X=C.indexOf("/"),Ge=X>0?C.substring(X+1):C;y(u.id,{status:"uploading",progress:0}),await new Promise((ce,Y)=>{let F=new XMLHttpRequest;F.upload.addEventListener("progress",M=>{if(M.lengthComputable){let He=Math.round(M.loaded/M.total*100);y(u.id,{progress:He})}}),F.addEventListener("load",()=>{F.status>=200&&F.status<300?ce():Y(new Error(`Upload failed with status ${F.status}`))}),F.addEventListener("error",()=>{Y(new Error("Network error during upload"))}),F.addEventListener("abort",()=>{Y(new Error("Upload cancelled"))}),F.open("PUT",N),F.setRequestHeader("Content-Type",h.type),F.send(h)});let _e={status:"completed",progress:100,filePath:Ge,visibility:s,publicUrl:s==="public"?G:void 0,file:void 0};b(ce=>{let Y=ce.map(M=>M.id===u.id?{...M,..._e}:M);I(Y);let F=Y.find(M=>M.id===u.id);return F&&_optionalChain([d, 'optionalCall', _134 => _134(F)]),Y})}catch(p){let x=p instanceof Error?p.message:"Unknown error";y(u.id,{status:"error",progress:0,errorMessage:x}),b(A=>{let N=A.find(C=>C.id===u.id);return N&&_optionalChain([m, 'optionalCall', _135 => _135(N,x)]),A})}},[y,d,m,s]),R=_react.useCallback.call(void 0, async u=>{let h=Array.from(u),p=[];b(x=>{if(t!==void 0){let C=x.filter(X=>X.status!=="error").length,G=t-C;if(G<=0)return _chunkDJ3T7VVSjs.a.warn(`File limit of ${t} already reached`),x;h.length>G&&(h=h.slice(0,G),_chunkDJ3T7VVSjs.a.warn(`Only ${G} files will be added to not exceed limit`))}let A=[];for(let C of h){let G=z(C),X={id:Fe(),name:C.name,size:C.size,contentType:C.type,status:G.valid?"pending":"error",progress:0,createdAt:Date.now(),file:G.valid?C:void 0,errorMessage:G.error};A.push(X)}p=A;let N=[...x,...A];return I(N),N}),setTimeout(()=>{let x=p.filter(A=>A.status==="pending"&&A.file);for(let A of x)if(A.file){let N=S(A,A.file);o.current.set(A.id,N),N.finally(()=>{o.current.delete(A.id)})}},0)},[t,z,S,I]),P=_react.useCallback.call(void 0, async u=>{let h=E.find(p=>p.id===u);if(!h)return!1;y(u,{status:"removing"});try{if(h.filePath){if(!se.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");if(!(await _crudifybrowser2.default.disableFile({filePath:h.filePath})).success)throw new Error("Failed to remove file from server")}return b(p=>{let x=p.filter(A=>A.id!==u);return I(x),x}),_optionalChain([D, 'optionalCall', _136 => _136(h)]),!0}catch(p){return y(u,{status:h.filePath?"completed":"error",errorMessage:p instanceof Error?p.message:"Error removing file"}),!1}},[E,y,I,D]),O=_react.useCallback.call(void 0, ()=>{b([]),I([])},[I]),k=_react.useCallback.call(void 0, async u=>{let h=E.find(x=>x.id===u);if(!h||h.status!=="error"||!h.file){_chunkDJ3T7VVSjs.a.warn("Cannot retry: file not found or no original file");return}y(u,{status:"pending",progress:0,errorMessage:void 0});let p=S(h,h.file);o.current.set(u,p),p.finally(()=>{o.current.delete(u)})},[E,y,S]),W=_react.useCallback.call(void 0, async()=>{let u=Array.from(o.current.values());u.length>0&&await Promise.allSettled(u)},[]),B=u=>{let h=_optionalChain([u, 'access', _137 => _137.split, 'call', _138 => _138("."), 'access', _139 => _139.pop, 'call', _140 => _140(), 'optionalAccess', _141 => _141.toLowerCase, 'call', _142 => _142()])||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",csv:"text/csv",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",zip:"application/zip",rar:"application/x-rar-compressed",json:"application/json",xml:"application/xml"}[h]||"application/octet-stream"},Z=_react.useCallback.call(void 0, u=>{let h=u.map(p=>{let A=p.filePath.startsWith("http://")||p.filePath.startsWith("https://")?new URL(p.filePath).pathname:p.filePath,N=A.includes("/public/")||A.startsWith("public/")?"public":"private",C=p.contentType||B(p.name);return{id:Fe(),name:p.name,size:p.size||0,contentType:C,status:"completed",progress:100,filePath:p.filePath,visibility:N,createdAt:Date.now()}});b(h),I(h)},[I]),K=_react.useCallback.call(void 0, async u=>{let h=E.find(p=>p.id===u);if(!h||!h.filePath)return null;if(h.visibility==="public"&&h.publicUrl)return h.publicUrl;try{if(!se.isInitialized())return null;let p=await _crudifybrowser2.default.getFileUrl({filePath:h.filePath,expiresIn:3600}),x=p.data;return p.success&&_optionalChain([x, 'optionalAccess', _143 => _143.url])?x.url:null}catch (e7){return null}},[E]),le=_react.useMemo.call(void 0, ()=>E.some(u=>u.status==="uploading"||u.status==="pending"),[E]),Le=_react.useMemo.call(void 0, ()=>E.filter(u=>u.status==="uploading"||u.status==="pending").length,[E]),ze=_react.useMemo.call(void 0, ()=>E.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[E]),{isValid:Ke,validationError:Oe}=_react.useMemo.call(void 0, ()=>{let u=E.filter(p=>p.status==="completed").length;return u<r?{isValid:!1,validationError:r===1?"At least one file is required":`At least ${r} files are required`}:t!==void 0&&u>t?{isValid:!1,validationError:`Maximum ${t} files allowed`}:E.some(p=>p.status==="error")?{isValid:!1,validationError:"Some files have errors"}:{isValid:!0,validationError:null}},[E,r,t]);return{files:E,isUploading:le,pendingCount:Le,addFiles:R,removeFile:P,clearFiles:O,retryUpload:k,isValid:Ke,validationError:Oe,waitForUploads:W,completedFilePaths:ze,initializeFiles:Z,isTouched:l,markAsTouched:c,getPreviewUrl:K}};exports.a = J; exports.b = ke; exports.c = be; exports.d = v; exports.e = ee; exports.f = Se; exports.g = fe; exports.h = Re; exports.i = ct; exports.j = li; exports.k = ut; exports.l = ht; exports.m = vt; exports.n = he; exports.o = se; exports.p = wt;
@@ -1,3 +0,0 @@
1
- import{a as g,c as ue,e as Ee,i as _,j as Te,k as ve,l as Ie}from"./chunk-HQKET2ZX.mjs";import{createContext as Me,useContext as Be,useEffect as Ye,useState as q}from"react";import j from"@nocios/crudify-browser";var de=class n{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return n.instance||(n.instance=new n),n.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){g.error("[CredentialsEventBus] Error in listener",t instanceof Error?t:{message:String(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}},J=de.getInstance();import{jsx as $e}from"react/jsx-runtime";var Ae=Me(void 0),ke=({config:n,children:i})=>{let[e,t]=q(!0),[r,s]=q(null),[d,m]=q(!1),[D,T]=q(""),[E,b]=q();Ye(()=>{if(!n.publicApiKey){s("No publicApiKey provided"),t(!1),m(!1);return}let a=`${n.publicApiKey}-${n.env}`;if(a===D&&d){t(!1);return}(async()=>{t(!0),s(null),m(!1);try{j.config(n.env||"prod");let c=await j.init(n.publicApiKey,"none");if(b(c),typeof j.transaction=="function"&&typeof j.login=="function")m(!0),T(a),c.apiEndpointAdmin&&c.apiKeyEndpointAdmin&&J.notifyCredentialsReady({apiUrl:c.apiEndpointAdmin,apiKey:c.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(c){let y=c instanceof Error?c.message:"Failed to initialize Crudify";g.error("[CrudifyProvider] Initialization error",c instanceof Error?c:{message:String(c)}),s(y),m(!1)}finally{t(!1)}})()},[n.publicApiKey,n.env,D,d]);let l={crudify:d?j:null,isLoading:e,error:r,isInitialized:d,adminCredentials:E};return $e(Ae.Provider,{value:l,children:i})},be=()=>{let n=Be(Ae);if(n===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return n};import Q from"crypto-js";var f=class f{static setStorageType(i){f.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 Q.SHA256(i).toString()}static getEncryptionKey(){if(f.encryptionKey)return f.encryptionKey;let i=window.localStorage;if(!i)return f.encryptionKey=f.generateEncryptionKey(),f.encryptionKey;try{let e=i.getItem(f.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=f.generateEncryptionKey(),i.setItem(f.ENCRYPTION_KEY_STORAGE,e)),f.encryptionKey=e,e}catch{return g.warn("Crudify: Cannot persist encryption key, using temporary key"),f.encryptionKey=f.generateEncryptionKey(),f.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 f.storageType==="none"?null:f.isStorageAvailable(f.storageType)?window[f.storageType]:(g.warn(`Crudify: ${f.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=f.getEncryptionKey();return Q.AES.encrypt(i,e).toString()}catch(e){return g.error("Crudify: Encryption failed",e instanceof Error?e:{message:String(e)}),i}}static decrypt(i){try{let e=f.getEncryptionKey();return Q.AES.decrypt(i,e).toString(Q.enc.Utf8)||i}catch(e){return g.error("Crudify: Decryption failed",e instanceof Error?e:{message:String(e)}),i}}static saveTokens(i){let e=f.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},r=f.encrypt(JSON.stringify(t));e.setItem(f.TOKEN_KEY,r),g.debug("Crudify: Tokens saved successfully")}catch(t){g.error("Crudify: Failed to save tokens",t instanceof Error?t:{message:String(t)})}}static getTokens(){let i=f.getStorage();if(!i)return null;try{let e=i.getItem(f.TOKEN_KEY);if(!e)return null;let t=f.decrypt(e),r=JSON.parse(t);return!r.accessToken||!r.refreshToken||!r.expiresAt||!r.refreshExpiresAt?(g.warn("Crudify: Incomplete token data found, clearing storage"),f.clearTokens(),null):Date.now()>=r.refreshExpiresAt?(g.info("Crudify: Refresh token expired, clearing storage"),f.clearTokens(),null):{accessToken:r.accessToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,refreshExpiresAt:r.refreshExpiresAt}}catch(e){return g.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),f.clearTokens(),null}}static clearTokens(){let i=f.getStorage();if(i)try{i.removeItem(f.TOKEN_KEY),g.debug("Crudify: Tokens cleared from storage")}catch(e){g.error("Crudify: Failed to clear tokens",e instanceof Error?e:{message:String(e)})}}static rotateEncryptionKey(){try{f.clearTokens(),f.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(f.ENCRYPTION_KEY_STORAGE),g.info("Crudify: Encryption key rotated successfully")}catch(i){g.error("Crudify: Failed to rotate encryption key",i instanceof Error?i:{message:String(i)})}}static hasValidTokens(){return f.getTokens()!==null}static getExpirationInfo(){let i=f.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=f.getTokens();if(!t){g.warn("Crudify: Cannot update access token, no existing tokens found");return}f.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===f.TOKEN_KEY){if(t.newValue===null){g.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){g.debug("Crudify: Tokens updated in another tab");let r=f.getTokens();i(r)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};f.TOKEN_KEY="crudify_tokens",f.ENCRYPTION_KEY_STORAGE="crudify_enc_key",f.encryptionKey=null,f.storageType="localStorage";var v=f;import U from"@nocios/crudify-browser";var ee=class n{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return n.instance||(n.instance=new n),n.instance}async initialize(i={}){if(console.log("[CRUDIFY_DEBUG] SessionManager.initialize() called"),this.initialized){console.log("[CRUDIFY_DEBUG] SessionManager already initialized, skipping");return}if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},console.log("[CRUDIFY_DEBUG] SessionManager config set, env:",this.config.env),v.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&(console.log("[CRUDIFY_DEBUG] About to initialize crudify SDK"),await this.ensureCrudifyInitialized(),console.log("[CRUDIFY_DEBUG] crudify SDK initialized")),U.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=v.getTokens();e?v.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):v.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&(console.log("[CRUDIFY_DEBUG] About to restore session"),await this.restoreSession(),console.log("[CRUDIFY_DEBUG] Session restored (or no session to restore)")),this.initialized=!0,console.log("[CRUDIFY_DEBUG] SessionManager.initialize() completed successfully")}async login(i,e){try{let t=await U.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let r=v.getTokens(),s=t.data,d={accessToken:s.token,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt,apiEndpointAdmin:r?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:r?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return v.saveTokens(d),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(d),{success:!0,tokens:d,data:s}}catch(t){return g.error("[SessionManager] Login error",t instanceof Error?t:{message:String(t)}),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await U.logout(),v.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),v.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=v.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"),v.clearTokens(),!1;if(U.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),U.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 r=v.getTokens();return r&&this.config.onSessionRestored?.(r),!0}return v.clearTokens(),await U.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),v.clearTokens(),await U.logout(),!1}}isAuthenticated(){return U.isLogin()||v.hasValidTokens()}getTokenInfo(){let i=U.getTokenData(),e=v.getExpirationInfo(),t=v.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:v.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 U.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),v.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e=i.data,t={accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt};return v.saveTokens(t),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),v.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){U.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"),_.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(v.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_.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"),_.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(console.log("[CRUDIFY_DEBUG] ensureCrudifyInitialized() called"),this.crudifyInitialized){console.log("[CRUDIFY_DEBUG] crudify already initialized, skipping");return}try{this.log("Initializing crudify SDK...");let i=U.getTokenData();if(console.log("[CRUDIFY_DEBUG] Existing tokenData:",i?"exists":"null"),i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0,console.log("[CRUDIFY_DEBUG] Crudify was already initialized by another service");return}let e=this.config.env||"stg";console.log("[CRUDIFY_DEBUG] Configuring crudify with env:",e),U.config(e);let t=this.config.publicApiKey,r=this.config.enableLogging?"debug":"none";console.log("[CRUDIFY_DEBUG] Calling crudify.init() with apiKey:",t?.substring(0,8)+"...","logLevel:",r);let s=await U.init(t,r);if(console.log("[CRUDIFY_DEBUG] crudify.init() response:",JSON.stringify(s)),s&&s.success===!1&&s.errors)throw console.error("[CRUDIFY_DEBUG] crudify.init() FAILED:",s.errors),new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully"),console.log("[CRUDIFY_DEBUG] crudify SDK initialized successfully")}catch(i){throw console.error("[CRUDIFY_DEBUG] ensureCrudifyInitialized FAILED:",i),g.error("[SessionManager] Failed to initialize crudify",i instanceof Error?i:{message:String(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(r=>r.errorType==="Unauthorized"||r.message?.includes("Unauthorized")||r.message?.includes("Not Authorized")||r.message?.includes("NOT_AUTHORIZED")||r.message?.includes("Token")||r.message?.includes("TOKEN")||r.message?.includes("Authentication")||r.message?.includes("UNAUTHENTICATED")||r.extensions?.code==="UNAUTHENTICATED"||r.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 r=Object.values(i.errors).flat().find(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.includes("INVALID_TOKEN")));r&&typeof r=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,r.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."):r.includes("TOKEN_HAS_EXPIRED")||r.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):r.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=String(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(){v.clearTokens(),U.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?Ee("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().map(String).join(", "):"Authentication failed":"Unknown error"}};import{useState as Ve,useEffect as ie,useCallback as $}from"react";function Se(n={}){let[i,e]=Ve({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=l=>{e(a=>{let o=typeof l=="function"?l(a):l;return o.error!==a.error&&console.log("[CRUDIFY_DEBUG] \u{1F534} STATE ERROR CHANGED:",{from:a.error,to:o.error,stack:new Error().stack?.split(`
2
- `).slice(2,6).join(`
3
- `)}),o.isAuthenticated!==a.isAuthenticated&&console.log("[CRUDIFY_DEBUG] \u{1F535} AUTH STATE CHANGED:",{from:a.isAuthenticated,to:o.isAuthenticated}),o})},r=ee.getInstance(),s=$(async()=>{console.log("[CRUDIFY_DEBUG] useSession.initialize() called");try{t(c=>({...c,isLoading:!0,error:null}));let l={autoRestore:n.autoRestore??!0,enableLogging:n.enableLogging??!1,showNotification:n.showNotification,translateFn:n.translateFn,apiEndpointAdmin:n.apiEndpointAdmin,apiKeyEndpointAdmin:n.apiKeyEndpointAdmin,publicApiKey:n.publicApiKey,env:n.env||"stg",onSessionExpired:()=>{console.log("[CRUDIFY_DEBUG] onSessionExpired callback triggered"),t(c=>({...c,isAuthenticated:!1,tokens:null,error:"Session expired"})),n.onSessionExpired?.()},onSessionRestored:c=>{console.log("[CRUDIFY_DEBUG] onSessionRestored callback triggered"),t(y=>({...y,isAuthenticated:!0,tokens:c,error:null})),n.onSessionRestored?.(c)},onLoginSuccess:c=>{console.log("[CRUDIFY_DEBUG] onLoginSuccess callback triggered"),t(y=>({...y,isAuthenticated:!0,tokens:c,error:null}))},onLogout:()=>{console.log("[CRUDIFY_DEBUG] onLogout callback triggered"),t(c=>({...c,isAuthenticated:!1,tokens:null,error:null}))}};console.log("[CRUDIFY_DEBUG] About to call sessionManager.initialize()"),await r.initialize(l),console.log("[CRUDIFY_DEBUG] sessionManager.initialize() completed"),r.setupResponseInterceptor(),console.log("[CRUDIFY_DEBUG] Response interceptor configured");let a=r.isAuthenticated(),o=r.getTokenInfo();console.log("[CRUDIFY_DEBUG] isAuth:",a,"hasAccessToken:",!!o.crudifyTokens.accessToken),t(c=>({...c,isAuthenticated:a,isInitialized:!0,isLoading:!1,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null})),console.log("[CRUDIFY_DEBUG] Initialize completed successfully")}catch(l){let a=l instanceof Error?l.message:"Initialization failed";console.error("[CRUDIFY_DEBUG] Initialize FAILED with error:",a,l),t(o=>({...o,isLoading:!1,isInitialized:!0,error:a}))}},[n.autoRestore,n.enableLogging,n.onSessionExpired,n.onSessionRestored]),d=$(async(l,a)=>{console.log("[CRUDIFY_DEBUG] login() called with email:",l),t(o=>({...o,isLoading:!0,error:null}));try{console.log("[CRUDIFY_DEBUG] Calling sessionManager.login()");let o=await r.login(l,a);return console.log("[CRUDIFY_DEBUG] sessionManager.login() result:",{success:o.success,hasTokens:!!o.tokens,error:o.error}),o.success&&o.tokens?(console.log("[CRUDIFY_DEBUG] Login SUCCESS, updating state with tokens"),t(c=>({...c,isAuthenticated:!0,tokens:o.tokens,isLoading:!1,error:null})),console.log("[CRUDIFY_DEBUG] State updated after successful login")):(console.log("[CRUDIFY_DEBUG] Login FAILED (no tokens), error:",o.error),t(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))),o}catch(o){let c=o instanceof Error?o.message:"Login failed";console.error("[CRUDIFY_DEBUG] login() CAUGHT EXCEPTION:",c,o);let y=c.includes("INVALID_CREDENTIALS")||c.includes("Invalid email")||c.includes("Invalid password")||c.includes("credentials");return console.log("[CRUDIFY_DEBUG] isCredentialError:",y,"- will set global error:",!y),t(I=>({...I,isAuthenticated:!1,tokens:null,isLoading:!1,error:y?null:c})),{success:!1,error:c}}},[r]),m=$(async()=>{console.log("[CRUDIFY_DEBUG] logout() called"),t(l=>({...l,isLoading:!0}));try{await r.logout(),t(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(l){t(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:l instanceof Error?l.message:"Logout error"}))}},[r]),D=$(async()=>{console.log("[CRUDIFY_DEBUG] refreshTokens() called");try{let l=await r.refreshTokens();if(l){let a=r.getTokenInfo();t(o=>({...o,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null,error:null}))}else t(a=>({...a,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return l}catch(l){return t(a=>({...a,isAuthenticated:!1,tokens:null,error:l instanceof Error?l.message:"Token refresh failed"})),!1}},[r]),T=$(()=>{console.log("[CRUDIFY_DEBUG] clearError() called"),t(l=>({...l,error:null}))},[]),E=$(()=>r.getTokenInfo(),[r]);ie(()=>{s()},[s]),ie(()=>{if(!i.isAuthenticated||!i.tokens)return;let l=Te.getInstance(),a=()=>{r.updateLastActivity()},o=l.subscribe(a);window.addEventListener("popstate",a);let c=()=>{let S=r.getTokenInfo().crudifyTokens.expiresIn||0;return S<300*1e3?30*1e3:S<1800*1e3?60*1e3:120*1e3},y,I=()=>{let z=c();y=setTimeout(async()=>{if(r.isRefreshing()){I();return}let S=r.getTokenInfo(),R=S.crudifyTokens.expiresIn||0,k=((S.crudifyTokens.expiresAt||0)-(Date.now()-R))*.5;if(R>0&&R<=k)if(console.log("[CRUDIFY_DEBUG] Token renewal triggered (TTL threshold)"),t(K=>({...K,isLoading:!0})),await r.refreshTokens()){let K=r.getTokenInfo();t(le=>({...le,isLoading:!1,tokens:K.crudifyTokens.accessToken?{accessToken:K.crudifyTokens.accessToken,refreshToken:K.crudifyTokens.refreshToken,expiresAt:K.crudifyTokens.expiresAt,refreshExpiresAt:K.crudifyTokens.refreshExpiresAt}:null}))}else t(K=>({...K,isLoading:!1,isAuthenticated:!1,tokens:null}));let W=r.getTimeSinceLastActivity(),B=1800*1e3;W>B?await m():I()},z)};return I(),()=>{clearTimeout(y),window.removeEventListener("popstate",a),o()}},[i.isAuthenticated,i.tokens,r,n.enableLogging,m]),ie(()=>{let l=_.subscribe(async a=>{if(a.type==="TOKEN_EXPIRED"){if(console.log("[CRUDIFY_DEBUG] authEventBus received TOKEN_EXPIRED event"),r.isRefreshing()){console.log("[CRUDIFY_DEBUG] Refresh already in progress, ignoring TOKEN_EXPIRED");return}t(o=>({...o,isLoading:!0}));try{if(await r.refreshTokens()){let c=r.getTokenInfo();t(y=>({...y,isLoading:!1,tokens:c.crudifyTokens.accessToken?{accessToken:c.crudifyTokens.accessToken,refreshToken:c.crudifyTokens.refreshToken,expiresAt:c.crudifyTokens.expiresAt,refreshExpiresAt:c.crudifyTokens.refreshExpiresAt}:null}))}else _.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(o){_.emit("SESSION_EXPIRED",{message:o instanceof Error?o.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(a.type==="SESSION_EXPIRED"||a.type==="TOKEN_REFRESH_FAILED")&&(console.log("[CRUDIFY_DEBUG] authEventBus received",a.type,"event:",a.details),t(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:a.details?.message||"Session expired"})),n.onSessionExpired?.())});return()=>l()},[n.onSessionExpired,r]),ie(()=>{let l=v.subscribeToChanges(a=>{console.log("[CRUDIFY_DEBUG] Cross-tab storage change detected:",a?"tokens updated":"tokens cleared"),a?t(o=>({...o,tokens:a,isAuthenticated:!0})):(t(o=>({...o,isAuthenticated:!1,tokens:null})),_.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>l()},[]);let b=$(()=>{r.updateLastActivity()},[r]);return{...i,login:d,logout:m,refreshTokens:D,clearError:T,getTokenInfo:E,updateActivity:b,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 xe,createContext as Xe,useContext as We,useCallback as te,useEffect as Ze}from"react";import{Snackbar as qe,Alert as je,Box as Je,Portal as Qe}from"@mui/material";import{v4 as ei}from"uuid";import ii from"dompurify";import{jsx as V,jsxs as ni}from"react/jsx-runtime";var De=Xe(null),ti=n=>ii.sanitize(n,{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}),fe=({children:n,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:r=!1,allowHtml:s=!1})=>{let[d,m]=xe([]),D=te((l,a="info",o)=>{if(!r)return"";if(!l||typeof l!="string")return g.warn("GlobalNotificationProvider: Invalid message provided"),"";l.length>1e3&&(g.warn("GlobalNotificationProvider: Message too long, truncating"),l=l.substring(0,1e3)+"...");let c=ei(),y={id:c,message:l,severity:a,autoHideDuration:o?.autoHideDuration??e,persistent:o?.persistent??!1,allowHtml:o?.allowHtml??s};return m(I=>[...I.length>=i?I.slice(-(i-1)):I,y]),c},[i,e,r,s]),T=te(l=>{m(a=>a.filter(o=>o.id!==l))},[]),E=te(()=>{m([])},[]),b={showNotification:D,hideNotification:T,clearAllNotifications:E};return ni(De.Provider,{value:b,children:[n,r&&V(Qe,{children:V(Je,{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:d.map(l=>V(ri,{notification:l,onClose:()=>T(l.id)},l.id))})})]})},ri=({notification:n,onClose:i})=>{let[e,t]=xe(!0),r=te((s,d)=>{d!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return Ze(()=>{if(!n.persistent&&n.autoHideDuration){let s=setTimeout(()=>{r()},n.autoHideDuration);return()=>clearTimeout(s)}},[n.autoHideDuration,n.persistent,r]),V(qe,{open:e,onClose:r,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:V(je,{variant:"filled",severity:n.severity,onClose:r,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:n.allowHtml?V("span",{dangerouslySetInnerHTML:{__html:ti(n.message)}}):V("span",{children:n.message})})})},Re=()=>{let n=We(De);if(!n)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return n};import oi,{createContext as si,useContext as ai,useMemo as ge}from"react";import{Fragment as ci,jsx as w,jsxs as H}from"react/jsx-runtime";var we=si(void 0);function Ce({children:n,options:i={},config:e,showNotifications:t=!1,notificationOptions:r={}}){let s;try{let{showNotification:o}=Re();s=o}catch{}let d={};try{let o=be();o.isInitialized&&o.adminCredentials&&(d=o.adminCredentials)}catch{}let m=ge(()=>{let o=ue({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:i?.enableLogging});return{publicApiKey:o.publicApiKey,env:o.env||"prod"}},[e,i?.enableLogging]),D=oi.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:d.apiEndpointAdmin,apiKeyEndpointAdmin:d.apiKeyEndpointAdmin,publicApiKey:m.publicApiKey,env:m.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,s,d.apiEndpointAdmin,d.apiKeyEndpointAdmin,m]),T=Se(D),E=ge(()=>{let o=ue({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:i?.enableLogging});return{publicApiKey:o.publicApiKey,env:o.env,appName:o.appName,loginActions:o.loginActions,logo:o.logo}},[e,i?.enableLogging]),b=ge(()=>{if(!T.tokens?.accessToken||!T.isAuthenticated)return null;try{let o=ve(T.tokens.accessToken);if(o&&o.sub&&o.email&&o.subscriber){let c={_id:o.sub,email:o.email,subscriberKey:o.subscriber};return Object.keys(o).forEach(y=>{["sub","email","subscriber"].includes(y)||(c[y]=o[y])}),c}}catch(o){g.error("Error decoding JWT token for sessionData",o instanceof Error?o:{message:String(o)})}return null},[T.tokens?.accessToken,T.isAuthenticated]),l={...T,sessionData:b,config:E};T.error&&console.log("[CRUDIFY_DEBUG] SessionProvider contextValue.error:",T.error);let a={enabled:t,maxNotifications:r.maxNotifications||5,defaultAutoHideDuration:r.defaultAutoHideDuration||6e3,position:r.position||{vertical:"top",horizontal:"right"}};return w(we.Provider,{value:l,children:n})}function ct(n){let i={enabled:n.showNotifications,maxNotifications:n.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:n.notificationOptions?.defaultAutoHideDuration||6e3,position:n.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:n.notificationOptions?.allowHtml||!1};return n.config?.publicApiKey?w(ke,{config:{publicApiKey:n.config.publicApiKey,env:n.config.env||"prod",appName:n.config.appName,loginActions:n.config.loginActions,logo:n.config.logo},children:w(fe,{...i,children:w(Ce,{...n})})}):w(fe,{...i,children:w(Ce,{...n})})}function li(){let n=ai(we);if(n===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return n}function ut(){let n=li();return n.isInitialized?H("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[w("h4",{children:"Session Debug Info"}),H("div",{children:[w("strong",{children:"Authenticated:"})," ",n.isAuthenticated?"Yes":"No"]}),H("div",{children:[w("strong",{children:"Loading:"})," ",n.isLoading?"Yes":"No"]}),H("div",{children:[w("strong",{children:"Error:"})," ",n.error||"None"]}),n.tokens&&H(ci,{children:[H("div",{children:[w("strong",{children:"Access Token:"})," ",n.tokens.accessToken.substring(0,20),"..."]}),H("div",{children:[w("strong",{children:"Refresh Token:"})," ",n.tokens.refreshToken.substring(0,20),"..."]}),H("div",{children:[w("strong",{children:"Access Expires In:"})," ",Math.round(n.expiresIn/1e3/60)," minutes"]}),H("div",{children:[w("strong",{children:"Refresh Expires In:"})," ",Math.round(n.refreshExpiresIn/1e3/60/60)," hours"]}),H("div",{children:[w("strong",{children:"Expiring Soon:"})," ",n.isExpiringSoon?"Yes":"No"]})]})]}):w("div",{children:"Session not initialized"})}import{useState as re,useEffect as Ue,useCallback as Pe,useRef as ne}from"react";import ui from"@nocios/crudify-browser";var ht=(n={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=n,[r,s]=re(null),[d,m]=re(!1),[D,T]=re(null),[E,b]=re({}),l=ne(null),a=ne(!0),o=ne(0),c=ne(0),y=Pe(()=>{s(null),T(null),m(!1),b({})},[]),I=Pe(async()=>{let z=Ie();if(!z){a.current&&(T("No user email available"),m(!1));return}l.current&&l.current.abort();let S=new AbortController;l.current=S;let R=++o.current;try{a.current&&(m(!0),T(null));let P=await ui.readItems("users",{filter:{email:z},pagination:{limit:1}});if(R===o.current&&a.current&&!S.signal.aborted){let O=P.data;if(P.success&&O&&O.length>0){let k=O[0];s(k);let W={fullProfile:k,totalFields:Object.keys(k).length,displayData:{id:k.id,email:k.email,username:k.username,firstName:k.firstName,lastName:k.lastName,fullName:k.fullName||`${k.firstName||""} ${k.lastName||""}`.trim(),role:k.role,permissions:k.permissions||[],isActive:k.isActive,lastLogin:k.lastLogin,createdAt:k.createdAt,updatedAt:k.updatedAt,...Object.keys(k).filter(B=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(B)).reduce((B,Z)=>({...B,[Z]:k[Z]}),{})}};b(W),T(null),c.current=0}else T("User profile not found"),s(null),b({})}}catch(P){if(R===o.current&&a.current){let O=P;if(O.name==="AbortError")return;e&&c.current<t&&(O.message?.includes("Network Error")||O.message?.includes("Failed to fetch"))?(c.current++,setTimeout(()=>{a.current&&I()},1e3*c.current)):(T("Failed to load user profile"),s(null),b({}))}}finally{R===o.current&&a.current&&m(!1),l.current===S&&(l.current=null)}},[e,t]);return Ue(()=>{i&&I()},[i,I]),Ue(()=>(a.current=!0,()=>{a.current=!1,l.current&&(l.current.abort(),l.current=null)}),[]),{userProfile:r,loading:d,error:D,extendedData:E,refreshProfile:I,clearProfile:y}};import{useState as pe,useEffect as di,useCallback as oe,useRef as fi}from"react";import gi from"@nocios/crudify-browser";var vt=(n,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:r}=i,{prefix:s,padding:d=0,separator:m=""}=n,[D,T]=pe(""),[E,b]=pe(!1),[l,a]=pe(null),o=fi(!1),c=oe(S=>{let R=String(S).padStart(d,"0");return`${s}${m}${R}`},[s,d,m]),y=oe(async()=>{b(!0),a(null);try{let S=await gi.getNextSequence(s),R=S.data;if(S.success&&R?.value){let P=c(R.value);T(P),t?.(P)}else{let P=S.errors?._error?.[0]||"Failed to generate code";a(P),r?.(P)}}catch(S){let R=S instanceof Error?S.message:"Unknown error";a(R),r?.(R)}finally{b(!1)}},[s,c,t,r]),I=oe(async()=>{await y()},[y]),z=oe(()=>{a(null)},[]);return di(()=>{e&&!D&&!o.current&&(o.current=!0,y())},[e,D,y]),{value:D,loading:E,error:l,regenerate:I,clearError:z}};import ye from"@nocios/crudify-browser";var he=class n{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 n.instance||(n.instance=new n),n.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:r,enableLogging:s,requestedBy:d}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&g.warn(`[CrudifyInitialization] ${d} 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 s&&g.debug(`[CrudifyInitialization] ${d} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&g.debug(`[CrudifyInitialization] ${d} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(d),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(d),this.getState().status==="INITIALIZED"){s&&g.debug(`[CrudifyInitialization] ${d} found initialization completed by HIGH priority`);return}s&&g.warn(`[CrudifyInitialization] ${d} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(g.warn(`[CrudifyInitialization] HIGH priority request from ${d} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&g.debug(`[CrudifyInitialization] ${d} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=d,this.initializationPromise=this.performInitialization(t,r,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=r,this.state.error=null,s&&g.info(`[CrudifyInitialization] Successfully initialized by ${d} (${e} priority)`)}catch(m){throw this.state.status="ERROR",this.state.error=m instanceof Error?m:new Error(String(m)),this.initializationPromise=null,g.error(`[CrudifyInitialization] Initialization failed for ${d}`,m instanceof Error?m:{message:String(m)}),m}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let r=0,s=setInterval(()=>{if(r+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){r=0;return}r>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),i&&g.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let r=ye.getTokenData();if(r&&r.endpoint){t&&g.debug("[CrudifyInitialization] SDK already initialized externally");return}ye.config(e);let s=t?"debug":"none",d=await ye.init(i,s);if(d.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(d.errors||"Unknown error")}`);d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&J.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin})}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}}},se=he.getInstance();import{useState as Ne,useCallback as L,useRef as pi,useMemo as ae}from"react";import me from"@nocios/crudify-browser";var Fe=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,yi=n=>{let i=n.lastIndexOf("."),e=i>0?n.substring(i):"",t=Date.now(),r=Math.random().toString(36).substring(2,8);return`${t}_${r}${e}`},wt=(n={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:r=0,visibility:s="private",onUploadComplete:d,onUploadError:m,onFileRemoved:D,onFilesChange:T}=n,[E,b]=Ne([]),[l,a]=Ne(!1),o=pi(new Map),c=L(()=>{a(!0)},[]),y=L((u,h)=>{b(p=>p.map(A=>A.id===u?{...A,...h}:A))},[]),I=L(u=>{T?.(u)},[T]),z=L(u=>i&&i.length>0&&!i.includes(u.type)?{valid:!1,error:`File type not allowed: ${u.type}`}:u.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),S=L(async(u,h)=>{try{if(!se.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let p=yi(h.name),x=await me.generateSignedUrl({fileName:p,contentType:h.type,visibility:s});if(!x.success||!x.data)throw new Error("Failed to get upload URL");let A=x.data,{uploadUrl:N,s3Key:C,publicUrl:G}=A;if(!N||!C)throw new Error("Incomplete signed URL response");let X=C.indexOf("/"),Ge=X>0?C.substring(X+1):C;y(u.id,{status:"uploading",progress:0}),await new Promise((ce,Y)=>{let F=new XMLHttpRequest;F.upload.addEventListener("progress",M=>{if(M.lengthComputable){let He=Math.round(M.loaded/M.total*100);y(u.id,{progress:He})}}),F.addEventListener("load",()=>{F.status>=200&&F.status<300?ce():Y(new Error(`Upload failed with status ${F.status}`))}),F.addEventListener("error",()=>{Y(new Error("Network error during upload"))}),F.addEventListener("abort",()=>{Y(new Error("Upload cancelled"))}),F.open("PUT",N),F.setRequestHeader("Content-Type",h.type),F.send(h)});let _e={status:"completed",progress:100,filePath:Ge,visibility:s,publicUrl:s==="public"?G:void 0,file:void 0};b(ce=>{let Y=ce.map(M=>M.id===u.id?{...M,..._e}:M);I(Y);let F=Y.find(M=>M.id===u.id);return F&&d?.(F),Y})}catch(p){let x=p instanceof Error?p.message:"Unknown error";y(u.id,{status:"error",progress:0,errorMessage:x}),b(A=>{let N=A.find(C=>C.id===u.id);return N&&m?.(N,x),A})}},[y,d,m,s]),R=L(async u=>{let h=Array.from(u),p=[];b(x=>{if(t!==void 0){let C=x.filter(X=>X.status!=="error").length,G=t-C;if(G<=0)return g.warn(`File limit of ${t} already reached`),x;h.length>G&&(h=h.slice(0,G),g.warn(`Only ${G} files will be added to not exceed limit`))}let A=[];for(let C of h){let G=z(C),X={id:Fe(),name:C.name,size:C.size,contentType:C.type,status:G.valid?"pending":"error",progress:0,createdAt:Date.now(),file:G.valid?C:void 0,errorMessage:G.error};A.push(X)}p=A;let N=[...x,...A];return I(N),N}),setTimeout(()=>{let x=p.filter(A=>A.status==="pending"&&A.file);for(let A of x)if(A.file){let N=S(A,A.file);o.current.set(A.id,N),N.finally(()=>{o.current.delete(A.id)})}},0)},[t,z,S,I]),P=L(async u=>{let h=E.find(p=>p.id===u);if(!h)return!1;y(u,{status:"removing"});try{if(h.filePath){if(!se.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");if(!(await me.disableFile({filePath:h.filePath})).success)throw new Error("Failed to remove file from server")}return b(p=>{let x=p.filter(A=>A.id!==u);return I(x),x}),D?.(h),!0}catch(p){return y(u,{status:h.filePath?"completed":"error",errorMessage:p instanceof Error?p.message:"Error removing file"}),!1}},[E,y,I,D]),O=L(()=>{b([]),I([])},[I]),k=L(async u=>{let h=E.find(x=>x.id===u);if(!h||h.status!=="error"||!h.file){g.warn("Cannot retry: file not found or no original file");return}y(u,{status:"pending",progress:0,errorMessage:void 0});let p=S(h,h.file);o.current.set(u,p),p.finally(()=>{o.current.delete(u)})},[E,y,S]),W=L(async()=>{let u=Array.from(o.current.values());u.length>0&&await Promise.allSettled(u)},[]),B=u=>{let h=u.split(".").pop()?.toLowerCase()||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",csv:"text/csv",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",zip:"application/zip",rar:"application/x-rar-compressed",json:"application/json",xml:"application/xml"}[h]||"application/octet-stream"},Z=L(u=>{let h=u.map(p=>{let A=p.filePath.startsWith("http://")||p.filePath.startsWith("https://")?new URL(p.filePath).pathname:p.filePath,N=A.includes("/public/")||A.startsWith("public/")?"public":"private",C=p.contentType||B(p.name);return{id:Fe(),name:p.name,size:p.size||0,contentType:C,status:"completed",progress:100,filePath:p.filePath,visibility:N,createdAt:Date.now()}});b(h),I(h)},[I]),K=L(async u=>{let h=E.find(p=>p.id===u);if(!h||!h.filePath)return null;if(h.visibility==="public"&&h.publicUrl)return h.publicUrl;try{if(!se.isInitialized())return null;let p=await me.getFileUrl({filePath:h.filePath,expiresIn:3600}),x=p.data;return p.success&&x?.url?x.url:null}catch{return null}},[E]),le=ae(()=>E.some(u=>u.status==="uploading"||u.status==="pending"),[E]),Le=ae(()=>E.filter(u=>u.status==="uploading"||u.status==="pending").length,[E]),ze=ae(()=>E.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[E]),{isValid:Ke,validationError:Oe}=ae(()=>{let u=E.filter(p=>p.status==="completed").length;return u<r?{isValid:!1,validationError:r===1?"At least one file is required":`At least ${r} files are required`}:t!==void 0&&u>t?{isValid:!1,validationError:`Maximum ${t} files allowed`}:E.some(p=>p.status==="error")?{isValid:!1,validationError:"Some files have errors"}:{isValid:!0,validationError:null}},[E,r,t]);return{files:E,isUploading:le,pendingCount:Le,addFiles:R,removeFile:P,clearFiles:O,retryUpload:k,isValid:Ke,validationError:Oe,waitForUploads:W,completedFilePaths:ze,initializeFiles:Z,isTouched:l,markAsTouched:c,getPreviewUrl:K}};export{J as a,ke as b,be as c,v as d,ee as e,Se as f,fe as g,Re as h,ct as i,li as j,ut as k,ht as l,vt as m,he as n,se as o,wt as p};