@nocios/crudify-ui 4.4.76 → 4.4.80
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/{chunk-D3NBX3SM.js → chunk-2M2IM334.js} +1 -1
- package/dist/chunk-5EG7G2PU.js +1 -0
- package/dist/{chunk-HDNGW5H5.js → chunk-6ERAYG7A.js} +1 -1
- package/dist/chunk-DJ3T7VVS.js +1 -0
- package/dist/{chunk-AEHAZP5F.js → chunk-EHN353DG.js} +1 -1
- package/dist/chunk-HQKET2ZX.mjs +1 -0
- package/dist/chunk-MA2GBL6O.mjs +1 -0
- package/dist/{chunk-ZKWTILQT.mjs → chunk-P7ZXOFUG.mjs} +1 -1
- package/dist/{chunk-7J5RTLCS.mjs → chunk-PXFVXBFM.mjs} +1 -1
- package/dist/{chunk-NZIH26GS.mjs → chunk-UHE5AR26.mjs} +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/utils.js +1 -1
- package/dist/utils.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-2G33BADS.mjs +0 -1
- package/dist/chunk-GCH3QGKL.mjs +0 -1
- package/dist/chunk-GNGIFVA4.js +0 -1
- package/dist/chunk-IYTXJHKO.js +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as
|
|
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-UHE5AR26.mjs";import{a as ze,b as ke,c as be,d as Fe}from"./chunk-P7ZXOFUG.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-MA2GBL6O.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); }
|
|
5
5
|
}
|
|
6
|
-
`});function T({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return
|
|
6
|
+
`});function T({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return k(qe,{children:[I(Ye,{}),k("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:[I("div",{style:He}),I("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=(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return a.warn("Open redirect blocked (relative path)",{path:e}),r;if(!We.test(o))return a.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let p of Je)if(p.test(t))return 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 a.warn("Open redirect blocked (suspicious path part)",{part:p}),r;return o},E=(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 a.warn("Error parsing redirect parameter",o instanceof Error?{errorMessage:o.message}:{message:String(o)}),r}};import{Fragment as b,jsx as v}from"react/jsx-runtime";function L({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:s,isInitialized:p,tokens:l,error:y}=m(),d=Ze();if(!p||s)return v(b,{children:r||v(T,{stage:"validating-session"})});let u=t&&l?.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 v($e,{to:`${o}?redirect=${x}`,replace:!0})}return v(b,{children:e})}import{Navigate as Qe,useLocation as Xe}from"react-router-dom";import{Fragment as je,jsx as w}from"react/jsx-runtime";function F({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=m(),t=Xe();if(o){let s=new URLSearchParams(t.search),p=E(s,r);return w(Qe,{to:p,replace:!0})}return w(je,{children:e})}import{createContext as er,useContext as rr,useEffect as or,useRef as D,useState as U}from"react";import{Fragment as nr,jsx as O}from"react/jsx-runtime";var N=er(void 0),tr=({config:e,children:r,fallback:o=null,onInitialized:t,onError:s})=>{let[p,l]=U(!1),[y,d]=U(!1),[u,A]=U(null),C=D(!1),x=D(!1);or(()=>{C.current||(P.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=M({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:e?.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";a.setEnvironment(R),await P.initialize({priority:"HIGH",publicApiKey:c.publicApiKey,env:c.env||"prod",enableLogging:e?.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)}})())},[e?.publicApiKey,e?.env,e?.enableLogging,t,s]);let _={isInitialized:p,isInitializing:y,error:u};return y&&o?O(nr,{children:o}):(u&&a.error("[CrudifyInitializer] Initialization failed",u),O(N.Provider,{value:_,children:r}))},ir=()=>{let e=rr(N);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};import i from"@nocios/crudify-admin";var G=!1,g=null;async function sr(){let r=f.getInstance().getTokenInfo(),o=r?.apiEndpointAdmin,t=r?.apiKeyEndpointAdmin;return o&&t?{apiUrl:o,apiKey:t}:z.waitForCredentials()}async function ar(){if(!G)return g||(g=(async()=>{try{let e=f.getInstance(),{apiUrl:r,apiKey:o}=await sr();i.init({url:r,apiKey:o,getAdditionalHeaders:()=>{let t=e.getTokenInfo();return t?.crudifyTokens?.accessToken?{Authorization:`Bearer ${t.crudifyTokens.accessToken}`}:{}}}),G=!0}catch(e){throw g=null,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 f.getInstance().refreshTokens()?await e():(a.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),r):r}catch(r){return 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(()=>i.listModules()),getModule:e=>n(()=>i.getModule(e)),createModule:e=>n(()=>i.createModule(e)),editModule:(e,r)=>n(()=>i.editModule(e,r)),deleteModule:e=>n(()=>i.deleteModule(e)),activateModule:e=>n(()=>i.activateModule(e)),deactivateModule:e=>n(()=>i.deactivateModule(e)),getModuleVersions:e=>n(()=>i.getModuleVersions(e)),listActions:e=>n(()=>i.listActions(e)),getAction:e=>n(()=>i.getAction(e)),createAction:e=>n(()=>i.createAction(e)),editAction:(e,r)=>n(()=>i.editAction(e,r)),deleteAction:e=>n(()=>i.deleteAction(e)),activateAction:e=>n(()=>i.activateAction(e)),deactivateAction:e=>n(()=>i.deactivateAction(e)),getActionVersions:e=>n(()=>i.getActionVersions(e)),getActionsByProfile:e=>n(()=>i.getActionsByProfile(e)),updateActionsProfiles:e=>n(()=>i.updateActionsProfiles(e))};export{F as AuthRoute,K as CRITICAL_TRANSLATIONS,Se as CrudiaAutoGenerate,Ue as CrudiaFileField,Me as CrudiaMarkdownField,Te as CrudifyInitializationManager,tr as CrudifyInitializer,ye as CrudifyLogin,J as CrudifyProvider,Ke as CrudifyThemeProvider,ce as ERROR_CODES,le as ERROR_SEVERITY_MAP,ne as GlobalNotificationProvider,Ie as LoginComponent,xe as POLICY_ACTIONS,Re as PREFERRED_POLICY_ORDER,Pe as Policies,L as ProtectedRoute,pe as SessionDebugInfo,T as SessionLoadingScreen,f as SessionManager,ae as SessionProvider,he as SessionStatus,Z as TokenStorage,H as TranslationService,q as TranslationsProvider,Ce as UserProfileDisplay,ee as createErrorTranslator,Zr as crudify,pr as crudifyAdmin,P as crudifyInitManager,oe as decodeJwtSafely,E as extractSafeRedirectFromUrl,S as getCookie,B as getCriticalLanguages,V as getCriticalTranslations,te as getCurrentUserEmail,fe as getErrorMessage,ge as handleCrudifyError,ie as isTokenExpired,a as logger,de as parseApiError,me as parseJavaScriptError,ue as parseTransactionError,we as secureLocalStorage,Le as secureSessionStorage,j as translateError,Q as translateErrorCode,X as translateErrorCodes,Y as translationService,ke as useAuth,ve as useAutoGenerate,$ as useCrudify,ir as useCrudifyInitializer,Fe as useCrudifyWithNotifications,be as useData,Ee as useFileUpload,se as useGlobalNotification,re as useSession,m as useSessionContext,W as useTranslations,ze as useUserData,Ae as useUserProfile,h as validateInternalRedirect};
|
package/dist/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk2M2IM334js = require('./chunk-2M2IM334.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunkDJ3T7VVSjs = require('./chunk-DJ3T7VVS.js');exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.NavigationTracker = _chunkDJ3T7VVSjs.j; exports.authEventBus = _chunkDJ3T7VVSjs.i; exports.createErrorTranslator = _chunkDJ3T7VVSjs.h; exports.decodeJwtSafely = _chunkDJ3T7VVSjs.k; exports.getCookie = _chunkDJ3T7VVSjs.b; exports.getCurrentUserEmail = _chunkDJ3T7VVSjs.l; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunkDJ3T7VVSjs.m; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.resolveConfig = _chunkDJ3T7VVSjs.c; exports.secureLocalStorage = _chunk2M2IM334js.b; exports.secureSessionStorage = _chunk2M2IM334js.a; exports.translateError = _chunkDJ3T7VVSjs.g; exports.translateErrorCode = _chunkDJ3T7VVSjs.e; exports.translateErrorCodes = _chunkDJ3T7VVSjs.f; exports.useResolvedConfig = _chunkDJ3T7VVSjs.d;
|
package/dist/utils.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as R,b as c}from"./chunk-
|
|
1
|
+
import{a as R,b as c}from"./chunk-PXFVXBFM.mjs";import{a as m,b as v,c as d,d as g,e as u,f as x,g as C}from"./chunk-BJ6PIVZR.mjs";import{b as r,c as e,d as o,e as t,f as a,g as n,h as s,i as E,j as i,k as p,l as f,m as l}from"./chunk-HQKET2ZX.mjs";export{m as ERROR_CODES,v as ERROR_SEVERITY_MAP,i as NavigationTracker,E as authEventBus,s as createErrorTranslator,p as decodeJwtSafely,r as getCookie,f as getCurrentUserEmail,u as getErrorMessage,C as handleCrudifyError,l as isTokenExpired,d as parseApiError,x as parseJavaScriptError,g as parseTransactionError,e as resolveConfig,c as secureLocalStorage,R as secureSessionStorage,n as translateError,t as translateErrorCode,a as translateErrorCodes,o as useResolvedConfig};
|
package/package.json
CHANGED
package/dist/chunk-2G33BADS.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as p,c as ce,e as me,i as M,j as Ee,k as Te,l as ve}from"./chunk-GCH3QGKL.mjs";import{createContext as _e,useContext as $e,useEffect as Ve,useState as Z}from"react";import q from"@nocios/crudify-browser";var ue=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){p.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=ue.getInstance();import{jsx as Be}from"react/jsx-runtime";var Ae=_e(void 0),Ie=({config:r,children:i})=>{let[e,t]=Z(!0),[s,o]=Z(null),[c,m]=Z(!1),[w,I]=Z(""),[T,u]=Z();Ve(()=>{if(!r.publicApiKey){o("No publicApiKey provided"),t(!1),m(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===w&&c){t(!1);return}(async()=>{t(!0),o(null),m(!1);try{q.config(r.env||"prod");let y=await q.init(r.publicApiKey,"none");if(u(y),typeof q.transaction=="function"&&typeof q.login=="function")m(!0),I(l),y.apiEndpointAdmin&&y.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:y.apiEndpointAdmin,apiKey:y.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(y){let E=y instanceof Error?y.message:"Failed to initialize Crudify";p.error("[CrudifyProvider] Initialization error",y instanceof Error?y:{message:String(y)}),o(E),m(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,w,c]);let a={crudify:c?q:null,isLoading:e,error:s,isInitialized:c,adminCredentials:T};return Be(Ae.Provider,{value:a,children:i})},ke=()=>{let r=$e(Ae);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import J 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 J.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 p.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]:(p.warn(`Crudify: ${f.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=f.getEncryptionKey();return J.AES.encrypt(i,e).toString()}catch(e){return p.error("Crudify: Encryption failed",e instanceof Error?e:{message:String(e)}),i}}static decrypt(i){try{let e=f.getEncryptionKey();return J.AES.decrypt(i,e).toString(J.enc.Utf8)||i}catch(e){return p.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()},s=f.encrypt(JSON.stringify(t));e.setItem(f.TOKEN_KEY,s),p.debug("Crudify: Tokens saved successfully")}catch(t){p.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),s=JSON.parse(t);return!s.accessToken||!s.refreshToken||!s.expiresAt||!s.refreshExpiresAt?(p.warn("Crudify: Incomplete token data found, clearing storage"),f.clearTokens(),null):Date.now()>=s.refreshExpiresAt?(p.info("Crudify: Refresh token expired, clearing storage"),f.clearTokens(),null):{accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt}}catch(e){return p.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),p.debug("Crudify: Tokens cleared from storage")}catch(e){p.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),p.info("Crudify: Encryption key rotated successfully")}catch(i){p.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){p.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){p.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){p.debug("Crudify: Tokens updated in another tab");let s=f.getTokens();i(s)}}};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 N from"@nocios/crudify-browser";var Q=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},v.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),N.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),M.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&&await this.restoreSession(),this.initialized=!0}}async login(i,e){try{let t=await N.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let s=v.getTokens(),o=t.data,c={accessToken:o.token,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt,apiEndpointAdmin:s?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:s?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return v.saveTokens(c),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(c),{success:!0,tokens:c,data:o}}catch(t){return p.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 N.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(N.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),N.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 s=v.getTokens();return s&&this.config.onSessionRestored?.(s),!0}return v.clearTokens(),await N.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 N.logout(),!1}}isAuthenticated(){return N.isLogin()||v.hasValidTokens()}getTokenInfo(){let i=N.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 N.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(){N.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"),M.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"),M.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"),M.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=N.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";N.config(e);let t=this.config.publicApiKey,s=this.config.enableLogging?"debug":"none",o=await N.init(t,s);if(o&&o.success===!1&&o.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(o.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw p.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(s=>s.errorType==="Unauthorized"||s.message?.includes("Unauthorized")||s.message?.includes("Not Authorized")||s.message?.includes("NOT_AUTHORIZED")||s.message?.includes("Token")||s.message?.includes("TOKEN")||s.message?.includes("Authentication")||s.message?.includes("UNAUTHENTICATED")||s.extensions?.code==="UNAUTHENTICATED"||s.extensions?.code==="FORBIDDEN");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 s=Object.values(i.errors).flat().find(o=>typeof o=="string"&&(o.includes("NOT_AUTHORIZED")||o.includes("TOKEN_REFRESH_FAILED")||o.includes("TOKEN_HAS_EXPIRED")||o.includes("PLEASE_LOGIN")||o.includes("Unauthorized")||o.includes("UNAUTHENTICATED")||o.includes("SESSION_EXPIRED")||o.includes("INVALID_TOKEN")));s&&typeof s=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,s.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):s.includes("TOKEN_HAS_EXPIRED")||s.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):s.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&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(),N.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?me("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 Ye,useEffect as ee,useCallback as V}from"react";function be(r={}){let[i,e]=Ye({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=Q.getInstance(),s=V(async()=>{try{e(n=>({...n,isLoading:!0,error:null}));let u={autoRestore:r.autoRestore??!0,enableLogging:r.enableLogging??!1,showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:"Session expired"})),r.onSessionExpired?.()},onSessionRestored:n=>{e(y=>({...y,isAuthenticated:!0,tokens:n,error:null})),r.onSessionRestored?.(n)},onLoginSuccess:n=>{e(y=>({...y,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(u),t.setupResponseInterceptor();let a=t.isAuthenticated(),l=t.getTokenInfo();e(n=>({...n,isAuthenticated:a,isInitialized:!0,isLoading:!1,tokens:l.crudifyTokens.accessToken?{accessToken:l.crudifyTokens.accessToken,refreshToken:l.crudifyTokens.refreshToken,expiresAt:l.crudifyTokens.expiresAt,refreshExpiresAt:l.crudifyTokens.refreshExpiresAt}:null}))}catch(u){let a=u instanceof Error?u.message:"Initialization failed";e(l=>({...l,isLoading:!1,isInitialized:!0,error:a}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),o=V(async(u,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(u,a);return l.success&&l.tokens?e(n=>({...n,isAuthenticated:!0,tokens:l.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),l}catch(l){let n=l instanceof Error?l.message:"Login failed",y=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(E=>({...E,isAuthenticated:!1,tokens:null,isLoading:!1,error:y?null:n})),{success:!1,error:n}}},[t]),c=V(async()=>{e(u=>({...u,isLoading:!0}));try{await t.logout(),e(u=>({...u,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(u){e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:u instanceof Error?u.message:"Logout error"}))}},[t]),m=V(async()=>{try{let u=await t.refreshTokens();if(u){let a=t.getTokenInfo();e(l=>({...l,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return u}catch(u){return e(a=>({...a,isAuthenticated:!1,tokens:null,error:u instanceof Error?u.message:"Token refresh failed"})),!1}},[t]),w=V(()=>{e(u=>({...u,error:null}))},[]),I=V(()=>t.getTokenInfo(),[t]);ee(()=>{s()},[s]),ee(()=>{if(!i.isAuthenticated||!i.tokens)return;let u=Ee.getInstance(),a=()=>{t.updateLastActivity()},l=u.subscribe(a);window.addEventListener("popstate",a);let n=()=>{let C=t.getTokenInfo().crudifyTokens.expiresIn||0;return C<300*1e3?30*1e3:C<1800*1e3?60*1e3:120*1e3},y,E=()=>{let b=n();y=setTimeout(async()=>{if(t.isRefreshing()){E();return}let C=t.getTokenInfo(),S=C.crudifyTokens.expiresIn||0,O=((C.crudifyTokens.expiresAt||0)-(Date.now()-S))*.5;if(S>0&&S<=O)if(e(L=>({...L,isLoading:!0})),await t.refreshTokens()){let L=t.getTokenInfo();e(ae=>({...ae,isLoading:!1,tokens:L.crudifyTokens.accessToken?{accessToken:L.crudifyTokens.accessToken,refreshToken:L.crudifyTokens.refreshToken,expiresAt:L.crudifyTokens.expiresAt,refreshExpiresAt:L.crudifyTokens.refreshExpiresAt}:null}))}else e(L=>({...L,isLoading:!1,isAuthenticated:!1,tokens:null}));let k=t.getTimeSinceLastActivity(),W=1800*1e3;k>W?await c():E()},b)};return E(),()=>{clearTimeout(y),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,c]),ee(()=>{let u=M.subscribe(async a=>{if(a.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;e(l=>({...l,isLoading:!0}));try{if(await t.refreshTokens()){let n=t.getTokenInfo();e(y=>({...y,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else M.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){M.emit("SESSION_EXPIRED",{message:l instanceof Error?l.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(a.type==="SESSION_EXPIRED"||a.type==="TOKEN_REFRESH_FAILED")&&(e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:a.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>u()},[r.onSessionExpired,t]),ee(()=>{let u=v.subscribeToChanges(a=>{a?e(l=>({...l,tokens:a,isAuthenticated:!0})):(e(l=>({...l,isAuthenticated:!1,tokens:null})),M.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>u()},[]);let T=V(()=>{t.updateLastActivity()},[t]);return{...i,login:o,logout:c,refreshTokens:m,clearError:w,getTokenInfo:I,updateActivity:T,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 ie,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 B,jsxs as ni}from"react/jsx-runtime";var Se=Xe(null),ti=r=>ii.sanitize(r,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),de=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:s=!1,allowHtml:o=!1})=>{let[c,m]=xe([]),w=ie((a,l="info",n)=>{if(!s)return"";if(!a||typeof a!="string")return p.warn("GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(p.warn("GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let y=ei(),E={id:y,message:a,severity:l,autoHideDuration:n?.autoHideDuration??e,persistent:n?.persistent??!1,allowHtml:n?.allowHtml??o};return m(b=>[...b.length>=i?b.slice(-(i-1)):b,E]),y},[i,e,s,o]),I=ie(a=>{m(l=>l.filter(n=>n.id!==a))},[]),T=ie(()=>{m([])},[]),u={showNotification:w,hideNotification:I,clearAllNotifications:T};return ni(Se.Provider,{value:u,children:[r,s&&B(Qe,{children:B(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:c.map(a=>B(ri,{notification:a,onClose:()=>I(a.id)},a.id))})})]})},ri=({notification:r,onClose:i})=>{let[e,t]=xe(!0),s=ie((o,c)=>{c!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return Ze(()=>{if(!r.persistent&&r.autoHideDuration){let o=setTimeout(()=>{s()},r.autoHideDuration);return()=>clearTimeout(o)}},[r.autoHideDuration,r.persistent,s]),B(qe,{open:e,onClose:s,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:B(je,{variant:"filled",severity:r.severity,onClose:s,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?B("span",{dangerouslySetInnerHTML:{__html:ti(r.message)}}):B("span",{children:r.message})})})},we=()=>{let r=We(Se);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import si,{createContext as oi,useContext as ai,useMemo as fe}from"react";import{Fragment as ci,jsx as R,jsxs as G}from"react/jsx-runtime";var Re=oi(void 0);function Pe({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:s={}}){let o;try{let{showNotification:n}=we();o=n}catch{}let c={};try{let n=ke();n.isInitialized&&n.adminCredentials&&(c=n.adminCredentials)}catch{}let m=fe(()=>{let n=ce({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,i?.enableLogging]),w=si.useMemo(()=>({...i,showNotification:o,apiEndpointAdmin:c.apiEndpointAdmin,apiKeyEndpointAdmin:c.apiKeyEndpointAdmin,publicApiKey:m.publicApiKey,env:m.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,o,c.apiEndpointAdmin,c.apiKeyEndpointAdmin,m]),I=be(w),T=fe(()=>{let n=ce({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,i?.enableLogging]),u=fe(()=>{if(!I.tokens?.accessToken||!I.isAuthenticated)return null;try{let n=Te(I.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let y={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(E=>{["sub","email","subscriber"].includes(E)||(y[E]=n[E])}),y}}catch(n){p.error("Error decoding JWT token for sessionData",n instanceof Error?n:{message:String(n)})}return null},[I.tokens?.accessToken,I.isAuthenticated]),a={...I,sessionData:u,config:T},l={enabled:t,maxNotifications:s.maxNotifications||5,defaultAutoHideDuration:s.defaultAutoHideDuration||6e3,position:s.position||{vertical:"top",horizontal:"right"}};return R(Re.Provider,{value:a,children:r})}function ct(r){let i={enabled:r.showNotifications,maxNotifications:r.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:r.notificationOptions?.defaultAutoHideDuration||6e3,position:r.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:r.notificationOptions?.allowHtml||!1};return r.config?.publicApiKey?R(Ie,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:R(de,{...i,children:R(Pe,{...r})})}):R(de,{...i,children:R(Pe,{...r})})}function li(){let r=ai(Re);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function ut(){let r=li();return r.isInitialized?G("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[R("h4",{children:"Session Debug Info"}),G("div",{children:[R("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),G("div",{children:[R("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),G("div",{children:[R("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&G(ci,{children:[G("div",{children:[R("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),G("div",{children:[R("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),G("div",{children:[R("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),G("div",{children:[R("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),G("div",{children:[R("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):R("div",{children:"Session not initialized"})}import{useState as te,useEffect as Ne,useCallback as Ce,useRef as re}from"react";import ui from"@nocios/crudify-browser";var ht=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[s,o]=te(null),[c,m]=te(!1),[w,I]=te(null),[T,u]=te({}),a=re(null),l=re(!0),n=re(0),y=re(0),E=Ce(()=>{o(null),I(null),m(!1),u({})},[]),b=Ce(async()=>{let C=ve();if(!C){l.current&&(I("No user email available"),m(!1));return}a.current&&a.current.abort();let S=new AbortController;a.current=S;let D=++n.current;try{l.current&&(m(!0),I(null));let F=await ui.readItems("users",{filter:{email:C},pagination:{limit:1}});if(D===n.current&&l.current&&!S.signal.aborted){let O=F.data;if(F.success&&O&&O.length>0){let k=O[0];o(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(Y=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(Y)).reduce((Y,L)=>({...Y,[L]:k[L]}),{})}};u(W),I(null),y.current=0}else I("User profile not found"),o(null),u({})}}catch(F){if(D===n.current&&l.current){let O=F;if(O.name==="AbortError")return;e&&y.current<t&&(O.message?.includes("Network Error")||O.message?.includes("Failed to fetch"))?(y.current++,setTimeout(()=>{l.current&&b()},1e3*y.current)):(I("Failed to load user profile"),o(null),u({}))}}finally{D===n.current&&l.current&&m(!1),a.current===S&&(a.current=null)}},[e,t]);return Ne(()=>{i&&b()},[i,b]),Ne(()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:s,loading:c,error:w,extendedData:T,refreshProfile:b,clearProfile:E}};import{useState as pe,useEffect as di,useCallback as ne,useRef as fi}from"react";import pi from"@nocios/crudify-browser";var vt=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:s}=i,{prefix:o,padding:c=0,separator:m=""}=r,[w,I]=pe(""),[T,u]=pe(!1),[a,l]=pe(null),n=fi(!1),y=ne(S=>{let D=String(S).padStart(c,"0");return`${o}${m}${D}`},[o,c,m]),E=ne(async()=>{u(!0),l(null);try{let S=await pi.getNextSequence(o),D=S.data;if(S.success&&D?.value){let F=y(D.value);I(F),t?.(F)}else{let F=S.errors?._error?.[0]||"Failed to generate code";l(F),s?.(F)}}catch(S){let D=S instanceof Error?S.message:"Unknown error";l(D),s?.(D)}finally{u(!1)}},[o,y,t,s]),b=ne(async()=>{await E()},[E]),C=ne(()=>{l(null)},[]);return di(()=>{e&&!w&&!n.current&&(n.current=!0,E())},[e,w,E]),{value:w,loading:T,error:a,regenerate:b,clearError:C}};import ge from"@nocios/crudify-browser";var ye=class r{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 r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:s,enableLogging:o,requestedBy:c}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&p.warn(`[CrudifyInitialization] ${c} attempted to initialize with different key. Already initialized with key: ${this.state.publicApiKey?.slice(0,10)}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return o&&p.debug(`[CrudifyInitialization] ${c} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(o&&p.debug(`[CrudifyInitialization] ${c} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(c),await this.waitForHighPriorityOrTimeout(o),this.waitingForHighPriority.delete(c),this.getState().status==="INITIALIZED"){o&&p.debug(`[CrudifyInitialization] ${c} found initialization completed by HIGH priority`);return}o&&p.warn(`[CrudifyInitialization] ${c} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(p.warn(`[CrudifyInitialization] HIGH priority request from ${c} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),o&&p.debug(`[CrudifyInitialization] ${c} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=c,this.initializationPromise=this.performInitialization(t,s,o);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=s,this.state.error=null,o&&p.info(`[CrudifyInitialization] Successfully initialized by ${c} (${e} priority)`)}catch(m){throw this.state.status="ERROR",this.state.error=m instanceof Error?m:new Error(String(m)),this.initializationPromise=null,p.error(`[CrudifyInitialization] Initialization failed for ${c}`,m instanceof Error?m:{message:String(m)}),m}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let s=0,o=setInterval(()=>{if(s+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(o),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){s=0;return}s>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(o),i&&p.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let s=ge.getTokenData();if(s&&s.endpoint){t&&p.debug("[CrudifyInitialization] SDK already initialized externally");return}ge.config(e);let o=t?"debug":"none",c=await ge.init(i,o);if(c.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(c.errors||"Unknown error")}`);c.apiEndpointAdmin&&c.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:c.apiEndpointAdmin,apiKey:c.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=ye.getInstance();import{useState as De,useCallback as U,useRef as gi,useMemo as oe}from"react";import he from"@nocios/crudify-browser";var Le=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,yi=r=>{let i=r.lastIndexOf("."),e=i>0?r.substring(i):"",t=Date.now(),s=Math.random().toString(36).substring(2,8);return`${t}_${s}${e}`},Nt=(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:s=0,visibility:o="private",onUploadComplete:c,onUploadError:m,onFileRemoved:w,onFilesChange:I}=r,[T,u]=De([]),[a,l]=De(!1),n=gi(new Map),y=U(()=>{l(!0)},[]),E=U((d,h)=>{u(g=>g.map(A=>A.id===d?{...A,...h}:A))},[]),b=U(d=>{I?.(d)},[I]),C=U(d=>i&&i.length>0&&!i.includes(d.type)?{valid:!1,error:`File type not allowed: ${d.type}`}:d.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),S=U(async(d,h)=>{try{if(!se.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let g=yi(h.name),x=await he.generateSignedUrl({fileName:g,contentType:h.type,visibility:o});if(!x.success||!x.data)throw new Error("Failed to get upload URL");let A=x.data,{uploadUrl:z,s3Key:P,publicUrl:H}=A;if(!z||!P)throw new Error("Incomplete signed URL response");let X=P.indexOf("/"),He=X>0?P.substring(X+1):P;E(d.id,{status:"uploading",progress:0}),await new Promise((le,$)=>{let K=new XMLHttpRequest;K.upload.addEventListener("progress",_=>{if(_.lengthComputable){let Ge=Math.round(_.loaded/_.total*100);E(d.id,{progress:Ge})}}),K.addEventListener("load",()=>{K.status>=200&&K.status<300?le():$(new Error(`Upload failed with status ${K.status}`))}),K.addEventListener("error",()=>{$(new Error("Network error during upload"))}),K.addEventListener("abort",()=>{$(new Error("Upload cancelled"))}),K.open("PUT",z),K.setRequestHeader("Content-Type",h.type),K.send(h)});let Me={status:"completed",progress:100,filePath:He,visibility:o,publicUrl:o==="public"?H:void 0,file:void 0};u(le=>{let $=le.map(_=>_.id===d.id?{..._,...Me}:_);b($);let K=$.find(_=>_.id===d.id);return K&&c?.(K),$})}catch(g){let x=g instanceof Error?g.message:"Unknown error";E(d.id,{status:"error",progress:0,errorMessage:x}),u(A=>{let z=A.find(P=>P.id===d.id);return z&&m?.(z,x),A})}},[E,c,m,o]),D=U(async d=>{let h=Array.from(d),g=[];u(x=>{if(t!==void 0){let P=x.filter(X=>X.status!=="error").length,H=t-P;if(H<=0)return p.warn(`File limit of ${t} already reached`),x;h.length>H&&(h=h.slice(0,H),p.warn(`Only ${H} files will be added to not exceed limit`))}let A=[];for(let P of h){let H=C(P),X={id:Le(),name:P.name,size:P.size,contentType:P.type,status:H.valid?"pending":"error",progress:0,createdAt:Date.now(),file:H.valid?P:void 0,errorMessage:H.error};A.push(X)}g=A;let z=[...x,...A];return b(z),z}),setTimeout(()=>{let x=g.filter(A=>A.status==="pending"&&A.file);for(let A of x)if(A.file){let z=S(A,A.file);n.current.set(A.id,z),z.finally(()=>{n.current.delete(A.id)})}},0)},[t,C,S,b]),F=U(async d=>{let h=T.find(g=>g.id===d);if(!h)return!1;E(d,{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 he.disableFile({filePath:h.filePath})).success)throw new Error("Failed to remove file from server")}return u(g=>{let x=g.filter(A=>A.id!==d);return b(x),x}),w?.(h),!0}catch(g){return E(d,{status:h.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error removing file"}),!1}},[T,E,b,w]),O=U(()=>{u([]),b([])},[b]),k=U(async d=>{let h=T.find(x=>x.id===d);if(!h||h.status!=="error"||!h.file){p.warn("Cannot retry: file not found or no original file");return}E(d,{status:"pending",progress:0,errorMessage:void 0});let g=S(h,h.file);n.current.set(d,g),g.finally(()=>{n.current.delete(d)})},[T,E,S]),W=U(async()=>{let d=Array.from(n.current.values());d.length>0&&await Promise.allSettled(d)},[]),Y=d=>{let h=d.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"},L=U(d=>{let h=d.map(g=>{let A=g.filePath.startsWith("http://")||g.filePath.startsWith("https://")?new URL(g.filePath).pathname:g.filePath,z=A.includes("/public/")||A.startsWith("public/")?"public":"private",P=g.contentType||Y(g.name);return{id:Le(),name:g.name,size:g.size||0,contentType:P,status:"completed",progress:100,filePath:g.filePath,visibility:z,createdAt:Date.now()}});u(h),b(h)},[b]),ae=U(async d=>{let h=T.find(g=>g.id===d);if(!h||!h.filePath)return null;if(h.visibility==="public"&&h.publicUrl)return h.publicUrl;try{if(!se.isInitialized())return null;let g=await he.getFileUrl({filePath:h.filePath,expiresIn:3600}),x=g.data;return g.success&&x?.url?x.url:null}catch{return null}},[T]),Fe=oe(()=>T.some(d=>d.status==="uploading"||d.status==="pending"),[T]),ze=oe(()=>T.filter(d=>d.status==="uploading"||d.status==="pending").length,[T]),Ke=oe(()=>T.filter(d=>d.status==="completed"&&d.filePath).map(d=>d.filePath),[T]),{isValid:Ue,validationError:Oe}=oe(()=>{let d=T.filter(g=>g.status==="completed").length;return d<s?{isValid:!1,validationError:s===1?"At least one file is required":`At least ${s} files are required`}:t!==void 0&&d>t?{isValid:!1,validationError:`Maximum ${t} files allowed`}:T.some(g=>g.status==="error")?{isValid:!1,validationError:"Some files have errors"}:{isValid:!0,validationError:null}},[T,s,t]);return{files:T,isUploading:Fe,pendingCount:ze,addFiles:D,removeFile:F,clearFiles:O,retryUpload:k,isValid:Ue,validationError:Oe,waitForUploads:W,completedFilePaths:Ke,initializeFiles:L,isTouched:a,markAsTouched:y,getPreviewUrl:ae}};export{j as a,Ie as b,ke as c,v as d,Q as e,be as f,de as g,we as h,ct as i,li as j,ut as k,ht as l,vt as m,ye as n,se as o,Nt as p};
|
package/dist/chunk-GCH3QGKL.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var b=[/password[^:]*[:=]\s*[^\s,}]+/gi,/token[^:]*[:=]\s*[^\s,}]+/gi,/key[^:]*[:=]\s*["']?[^\s,}"']+/gi,/secret[^:]*[:=]\s*[^\s,}]+/gi,/authorization[^:]*[:=]\s*[^\s,}]+/gi,/mongodb(\+srv)?:\/\/[^\s]+/gi,/postgres:\/\/[^\s]+/gi,/mysql:\/\/[^\s]+/gi];function S(n){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp("(^|;)\\s*"+n+"=([^;]+)"));return e?e[2]:null}function w(){if(typeof window<"u"&&window.__CRUDIFY_ENV__)return window.__CRUDIFY_ENV__;let n=S("environment");return n&&["dev","stg","api","prod"].includes(n)?n:"prod"}var N=null,O="CrudifyUI",v=class{constructor(){this.explicitEnv=null;this.explicitEnv=N,this.prefix=O}getEffectiveEnv(){return this.explicitEnv!==null?this.explicitEnv:w()}sanitize(e){let t=e;for(let o of b)t=t.replace(o,"[REDACTED]");return t}sanitizeContext(e){let t={};for(let[o,r]of Object.entries(e))if(r!=null)if(o==="userId"&&typeof r=="string")t[o]=r.length>8?`${r.substring(0,8)}***`:r;else if(o==="email"&&typeof r=="string"){let[a,u]=r.split("@");t[o]=a&&u?`${a.substring(0,3)}***@${u}`:"[REDACTED]"}else typeof r=="string"?t[o]=this.sanitize(r):typeof r=="object"&&r!==null?t[o]=this.sanitizeContext(r):t[o]=r;return t}shouldLog(e){let t=this.getEffectiveEnv();return!((t==="prod"||t==="production"||t==="api")&&e!=="error")}log(e,t,o){if(!this.shouldLog(e))return;let r=this.sanitize(t),a=o?this.sanitizeContext(o):void 0,u={timestamp:new Date().toISOString(),level:e,environment:this.getEffectiveEnv(),service:this.prefix,message:r,...a&&Object.keys(a).length>0&&{context:a}},l=JSON.stringify(u);switch(e){case"error":console.error(l);break;case"warn":console.warn(l);break;case"info":console.info(l);break;case"debug":console.log(l);break}}error(e,t){let o;t instanceof Error?o={errorName:t.name,errorMessage:t.message,stack:t.stack}:o=t,this.log("error",e,o)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}getEnvironment(){return this.getEffectiveEnv()}setEnvironment(e){this.explicitEnv=e,N=e,typeof window<"u"&&(window.__CRUDIFY_ENV__=e)}isExplicitlyConfigured(){return this.explicitEnv!==null}},i=new v;var f=n=>{let e=document.cookie.match(new RegExp("(^|;)\\s*"+n+"=([^;]+)"));return e?e[2]:null};function _(n={}){let{publicApiKey:e,env:t,appName:o,logo:r,loginActions:a,featureKeys:u,enableDebug:l=!1}=n,s={configSource:"none"};l&&i.info("[ConfigResolver] Resolving configuration...",{propsApiKey:e?`${e.substring(0,10)}...`:void 0,propsEnv:t,hasPropsAppName:!!o,hasPropsLogo:!!r,propsLoginActions:a,propsFeatureKeys:u});let d=f("publicApiKey");if(l&&i.info("[ConfigResolver] Cookie check:",{hasCookieApiKey:!!d,cookieApiKey:d?`${d.substring(0,10)}...`:null,allCookies:typeof document<"u"?document.cookie:"N/A"}),d){let c=f("environment"),p=f("appName"),y=f("logo"),R=f("loginActions"),C=f("featureKeys"),A=f("theme");return s={publicApiKey:decodeURIComponent(d),env:c&&["dev","stg","api","prod"].includes(c)?c:"prod",appName:p?decodeURIComponent(p):void 0,logo:y?decodeURIComponent(y):void 0,loginActions:R?decodeURIComponent(R).split(",").map(E=>E.trim()).filter(Boolean):void 0,featureKeys:C?decodeURIComponent(C).split(",").map(E=>E.trim()).filter(Boolean):void 0,theme:A?(()=>{try{return JSON.parse(decodeURIComponent(A))}catch(E){l&&i.warn("[ConfigResolver] Failed to parse theme cookie",E instanceof Error?{errorMessage:E.message}:{message:String(E)});return}})():void 0,configSource:"cookies"},l&&(i.info("[ConfigResolver] \u2705 Using COOKIES configuration",{env:s.env,hasAppName:!!s.appName,hasLogo:!!s.logo,loginActionsCount:s.loginActions?.length,featureKeysCount:s.featureKeys?.length}),typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s}return e?(s={publicApiKey:e,env:t||"prod",appName:o,logo:r,loginActions:a,featureKeys:u,configSource:"props"},l&&(i.info("[ConfigResolver] \u2705 Using PROPS configuration (fallback - no cookies found)",{env:s.env,hasAppName:!!s.appName,hasLogo:!!s.logo,loginActionsCount:s.loginActions?.length,featureKeysCount:s.featureKeys?.length}),typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s):(l&&i.error("[ConfigResolver] \u274C No configuration found! Neither cookies nor props have publicApiKey",{hasCookies:!!d,hasProps:!!e}),s)}function M(n={}){return _(n)}var k=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],D={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},L={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function h(n,e){let{translateFn:t,currentLanguage:o,enableDebug:r}=e;r&&i.debug(`[ErrorTranslation] Translating error code: ${n} (lang: ${o||"unknown"})`);let a=n.toUpperCase(),u=D[a],l=k.map(c=>c.replace("{category}",u||"general").replace("{code}",a));r&&i.debug("[ErrorTranslation] Searching keys:",{translationKeys:l});for(let c of l){let p=t(c);if(r&&i.debug(`[ErrorTranslation] Checking key: "${c}" -> result: "${p}" (same as key: ${p===c})`),p&&p!==c)return r&&i.debug(`[ErrorTranslation] Found translation at key: ${c} = "${p}"`),p}let s=L[a];if(s)return r&&i.debug(`[ErrorTranslation] Using default message: "${s}"`),s;let d=a.replace(/_/g," ").toLowerCase().replace(/\b\w/g,c=>c.toUpperCase());return r&&i.debug(`[ErrorTranslation] No translation found, using friendly code: "${d}"`),d}function U(n,e){return n.map(t=>h(t,e))}function x(n,e){let{enableDebug:t}=e;t&&i.debug("[ErrorTranslation] Translating error:",{error:n});let o=h(n.code,e);return o!==n.code.toUpperCase()&&o!==n.code?(t&&i.debug(`[ErrorTranslation] Using hierarchical translation: "${o}"`),n.field?`${n.field}: ${o}`:o):n.message&&!n.message.includes("Error:")&&n.message.length>0&&n.message!==n.code?(t&&i.debug(`[ErrorTranslation] No hierarchical translation found, using API message: "${n.message}"`),n.message):(t&&i.debug(`[ErrorTranslation] Using final fallback: "${o}"`),n.field?`${n.field}: ${o}`:o)}function H(n,e={}){let t={translateFn:n,currentLanguage:e.currentLanguage,enableDebug:e.enableDebug||!1};return{translateErrorCode:o=>h(o,t),translateErrorCodes:o=>U(o,t),translateError:o=>x(o,t),translateApiError:o=>o?.data?.response?.status?h(o.data.response.status,t):o?.status?h(o.status,t):o?.code?h(o.code,t):"Unknown error"}}var m=class n{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return n.instance||(n.instance=new n),n.instance}emit(e,t){let o=Date.now();if(this.isHandlingAuthError&&this.lastEventType===e&&o-this.lastErrorTime<this.DEBOUNCE_TIME){i.debug(`AuthEventBus: Ignoring duplicate ${e} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=o,this.lastEventType=e,i.debug(`AuthEventBus: Emitting ${e} event`,t?{details:t}:void 0);let r={type:e,details:t,timestamp:o};this.listeners.forEach(a=>{try{a(r)}catch(u){i.error("AuthEventBus: Error in listener",u instanceof Error?u:{message:String(u)})}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},J=m.getInstance();var g=class g{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return g.instance||(g.instance=new g),g.instance}subscribe(e){return this.listeners.add(e),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(e)}}unsubscribe(e){this.listeners.delete(e),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let e=this;window.history.pushState=function(...t){let o=e.originalPushState.apply(this,t);return e.notifyListeners(),o},window.history.replaceState=function(...t){let o=e.originalReplaceState.apply(this,t);return e.notifyListeners(),o},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(e=>{try{e()}catch(t){i.error("NavigationTracker: Error in navigation listener",t instanceof Error?t:{message:String(t)})}})}static reset(){g.instance?.isPatched&&g.instance.removePatches(),g.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};g.instance=null;var I=g;var T=n=>{try{let e=n.split(".");if(e.length!==3)return i.warn("Invalid JWT format: token must have 3 parts"),null;let t=e[1],o=t+"=".repeat((4-t.length%4)%4);return JSON.parse(atob(o))}catch(e){return i.warn("Failed to decode JWT token",e instanceof Error?{errorMessage:e.message}:{message:String(e)}),null}},j=()=>{try{let n=null;if(n=sessionStorage.getItem("authToken"),n||(n=sessionStorage.getItem("token")),n||(n=localStorage.getItem("authToken")||localStorage.getItem("token")),!n)return null;let e=T(n);return e&&(e.email||e["cognito:username"])||null}catch(n){return i.warn("Failed to get current user email",n instanceof Error?{errorMessage:n.message}:{message:String(n)}),null}},q=n=>{try{let e=T(n);if(!e||!e.exp)return!0;let t=Math.floor(Date.now()/1e3);return e.exp<t}catch{return!0}};export{i as a,f as b,_ as c,M as d,h as e,U as f,x as g,H as h,J as i,I as j,T as k,j as l,q as m};
|
package/dist/chunk-GNGIFVA4.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var b=[/password[^:]*[:=]\s*[^\s,}]+/gi,/token[^:]*[:=]\s*[^\s,}]+/gi,/key[^:]*[:=]\s*["']?[^\s,}"']+/gi,/secret[^:]*[:=]\s*[^\s,}]+/gi,/authorization[^:]*[:=]\s*[^\s,}]+/gi,/mongodb(\+srv)?:\/\/[^\s]+/gi,/postgres:\/\/[^\s]+/gi,/mysql:\/\/[^\s]+/gi];function S(n){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp("(^|;)\\s*"+n+"=([^;]+)"));return e?e[2]:null}function w(){if(typeof window<"u"&&window.__CRUDIFY_ENV__)return window.__CRUDIFY_ENV__;let n=S("environment");return n&&["dev","stg","api","prod"].includes(n)?n:"prod"}var N=null,O="CrudifyUI",v=class{constructor(){this.explicitEnv=null;this.explicitEnv=N,this.prefix=O}getEffectiveEnv(){return this.explicitEnv!==null?this.explicitEnv:w()}sanitize(e){let t=e;for(let o of b)t=t.replace(o,"[REDACTED]");return t}sanitizeContext(e){let t={};for(let[o,r]of Object.entries(e))if(r!=null)if(o==="userId"&&typeof r=="string")t[o]=r.length>8?`${r.substring(0,8)}***`:r;else if(o==="email"&&typeof r=="string"){let[a,u]=r.split("@");t[o]=a&&u?`${a.substring(0,3)}***@${u}`:"[REDACTED]"}else typeof r=="string"?t[o]=this.sanitize(r):typeof r=="object"&&r!==null?t[o]=this.sanitizeContext(r):t[o]=r;return t}shouldLog(e){let t=this.getEffectiveEnv();return!((t==="prod"||t==="production"||t==="api")&&e!=="error")}log(e,t,o){if(!this.shouldLog(e))return;let r=this.sanitize(t),a=o?this.sanitizeContext(o):void 0,u={timestamp:new Date().toISOString(),level:e,environment:this.getEffectiveEnv(),service:this.prefix,message:r,...a&&Object.keys(a).length>0&&{context:a}},l=JSON.stringify(u);switch(e){case"error":console.error(l);break;case"warn":console.warn(l);break;case"info":console.info(l);break;case"debug":console.log(l);break}}error(e,t){let o;t instanceof Error?o={errorName:t.name,errorMessage:t.message,stack:t.stack}:o=t,this.log("error",e,o)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}getEnvironment(){return this.getEffectiveEnv()}setEnvironment(e){this.explicitEnv=e,N=e,typeof window<"u"&&(window.__CRUDIFY_ENV__=e)}isExplicitlyConfigured(){return this.explicitEnv!==null}},i= exports.a =new v;var f=n=>{let e=document.cookie.match(new RegExp("(^|;)\\s*"+n+"=([^;]+)"));return e?e[2]:null};function _(n={}){let{publicApiKey:e,env:t,appName:o,logo:r,loginActions:a,featureKeys:u,enableDebug:l=!1}=n,s={configSource:"none"};l&&i.info("[ConfigResolver] Resolving configuration...",{propsApiKey:e?`${e.substring(0,10)}...`:void 0,propsEnv:t,hasPropsAppName:!!o,hasPropsLogo:!!r,propsLoginActions:a,propsFeatureKeys:u});let d=f("publicApiKey");if(l&&i.info("[ConfigResolver] Cookie check:",{hasCookieApiKey:!!d,cookieApiKey:d?`${d.substring(0,10)}...`:null,allCookies:typeof document<"u"?document.cookie:"N/A"}),d){let c=f("environment"),p=f("appName"),y=f("logo"),R=f("loginActions"),C=f("featureKeys"),A=f("theme");return s={publicApiKey:decodeURIComponent(d),env:c&&["dev","stg","api","prod"].includes(c)?c:"prod",appName:p?decodeURIComponent(p):void 0,logo:y?decodeURIComponent(y):void 0,loginActions:R?decodeURIComponent(R).split(",").map(E=>E.trim()).filter(Boolean):void 0,featureKeys:C?decodeURIComponent(C).split(",").map(E=>E.trim()).filter(Boolean):void 0,theme:A?(()=>{try{return JSON.parse(decodeURIComponent(A))}catch(E){l&&i.warn("[ConfigResolver] Failed to parse theme cookie",E instanceof Error?{errorMessage:E.message}:{message:String(E)});return}})():void 0,configSource:"cookies"},l&&(i.info("[ConfigResolver] \u2705 Using COOKIES configuration",{env:s.env,hasAppName:!!s.appName,hasLogo:!!s.logo,loginActionsCount:_optionalChain([s, 'access', _2 => _2.loginActions, 'optionalAccess', _3 => _3.length]),featureKeysCount:_optionalChain([s, 'access', _4 => _4.featureKeys, 'optionalAccess', _5 => _5.length])}),typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s}return e?(s={publicApiKey:e,env:t||"prod",appName:o,logo:r,loginActions:a,featureKeys:u,configSource:"props"},l&&(i.info("[ConfigResolver] \u2705 Using PROPS configuration (fallback - no cookies found)",{env:s.env,hasAppName:!!s.appName,hasLogo:!!s.logo,loginActionsCount:_optionalChain([s, 'access', _6 => _6.loginActions, 'optionalAccess', _7 => _7.length]),featureKeysCount:_optionalChain([s, 'access', _8 => _8.featureKeys, 'optionalAccess', _9 => _9.length])}),typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s):(l&&i.error("[ConfigResolver] \u274C No configuration found! Neither cookies nor props have publicApiKey",{hasCookies:!!d,hasProps:!!e}),s)}function M(n={}){return _(n)}var k=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],D={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},L={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function h(n,e){let{translateFn:t,currentLanguage:o,enableDebug:r}=e;r&&i.debug(`[ErrorTranslation] Translating error code: ${n} (lang: ${o||"unknown"})`);let a=n.toUpperCase(),u=D[a],l=k.map(c=>c.replace("{category}",u||"general").replace("{code}",a));r&&i.debug("[ErrorTranslation] Searching keys:",{translationKeys:l});for(let c of l){let p=t(c);if(r&&i.debug(`[ErrorTranslation] Checking key: "${c}" -> result: "${p}" (same as key: ${p===c})`),p&&p!==c)return r&&i.debug(`[ErrorTranslation] Found translation at key: ${c} = "${p}"`),p}let s=L[a];if(s)return r&&i.debug(`[ErrorTranslation] Using default message: "${s}"`),s;let d=a.replace(/_/g," ").toLowerCase().replace(/\b\w/g,c=>c.toUpperCase());return r&&i.debug(`[ErrorTranslation] No translation found, using friendly code: "${d}"`),d}function U(n,e){return n.map(t=>h(t,e))}function x(n,e){let{enableDebug:t}=e;t&&i.debug("[ErrorTranslation] Translating error:",{error:n});let o=h(n.code,e);return o!==n.code.toUpperCase()&&o!==n.code?(t&&i.debug(`[ErrorTranslation] Using hierarchical translation: "${o}"`),n.field?`${n.field}: ${o}`:o):n.message&&!n.message.includes("Error:")&&n.message.length>0&&n.message!==n.code?(t&&i.debug(`[ErrorTranslation] No hierarchical translation found, using API message: "${n.message}"`),n.message):(t&&i.debug(`[ErrorTranslation] Using final fallback: "${o}"`),n.field?`${n.field}: ${o}`:o)}function H(n,e={}){let t={translateFn:n,currentLanguage:e.currentLanguage,enableDebug:e.enableDebug||!1};return{translateErrorCode:o=>h(o,t),translateErrorCodes:o=>U(o,t),translateError:o=>x(o,t),translateApiError:o=>_optionalChain([o, 'optionalAccess', _10 => _10.data, 'optionalAccess', _11 => _11.response, 'optionalAccess', _12 => _12.status])?h(o.data.response.status,t):_optionalChain([o, 'optionalAccess', _13 => _13.status])?h(o.status,t):_optionalChain([o, 'optionalAccess', _14 => _14.code])?h(o.code,t):"Unknown error"}}var m=class n{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return n.instance||(n.instance=new n),n.instance}emit(e,t){let o=Date.now();if(this.isHandlingAuthError&&this.lastEventType===e&&o-this.lastErrorTime<this.DEBOUNCE_TIME){i.debug(`AuthEventBus: Ignoring duplicate ${e} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=o,this.lastEventType=e,i.debug(`AuthEventBus: Emitting ${e} event`,t?{details:t}:void 0);let r={type:e,details:t,timestamp:o};this.listeners.forEach(a=>{try{a(r)}catch(u){i.error("AuthEventBus: Error in listener",u instanceof Error?u:{message:String(u)})}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},J= exports.i =m.getInstance();var g=class g{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return g.instance||(g.instance=new g),g.instance}subscribe(e){return this.listeners.add(e),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(e)}}unsubscribe(e){this.listeners.delete(e),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let e=this;window.history.pushState=function(...t){let o=e.originalPushState.apply(this,t);return e.notifyListeners(),o},window.history.replaceState=function(...t){let o=e.originalReplaceState.apply(this,t);return e.notifyListeners(),o},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(e=>{try{e()}catch(t){i.error("NavigationTracker: Error in navigation listener",t instanceof Error?t:{message:String(t)})}})}static reset(){_optionalChain([g, 'access', _15 => _15.instance, 'optionalAccess', _16 => _16.isPatched])&&g.instance.removePatches(),g.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};g.instance=null;var I=g;var T=n=>{try{let e=n.split(".");if(e.length!==3)return i.warn("Invalid JWT format: token must have 3 parts"),null;let t=e[1],o=t+"=".repeat((4-t.length%4)%4);return JSON.parse(atob(o))}catch(e){return i.warn("Failed to decode JWT token",e instanceof Error?{errorMessage:e.message}:{message:String(e)}),null}},j= exports.l =()=>{try{let n=null;if(n=sessionStorage.getItem("authToken"),n||(n=sessionStorage.getItem("token")),n||(n=localStorage.getItem("authToken")||localStorage.getItem("token")),!n)return null;let e=T(n);return e&&(e.email||e["cognito:username"])||null}catch(n){return i.warn("Failed to get current user email",n instanceof Error?{errorMessage:n.message}:{message:String(n)}),null}},q= exports.m =n=>{try{let e=T(n);if(!e||!e.exp)return!0;let t=Math.floor(Date.now()/1e3);return e.exp<t}catch (e2){return!0}};exports.a = i; exports.b = f; exports.c = _; exports.d = M; exports.e = h; exports.f = U; exports.g = x; exports.h = H; exports.i = J; exports.j = I; exports.k = T; exports.l = j; exports.m = q;
|
package/dist/chunk-IYTXJHKO.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkGNGIFVA4js = require('./chunk-GNGIFVA4.js');var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var ue=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){_chunkGNGIFVA4js.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 =ue.getInstance();var _jsxruntime = require('react/jsx-runtime');var Ae=_react.createContext.call(void 0, void 0),Ie= exports.b =({config:r,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[s,o]=_react.useState.call(void 0, null),[c,m]=_react.useState.call(void 0, !1),[w,I]=_react.useState.call(void 0, ""),[T,u]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){o("No publicApiKey provided"),t(!1),m(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===w&&c){t(!1);return}(async()=>{t(!0),o(null),m(!1);try{_crudifybrowser2.default.config(r.env||"prod");let y=await _crudifybrowser2.default.init(r.publicApiKey,"none");if(u(y),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")m(!0),I(l),y.apiEndpointAdmin&&y.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:y.apiEndpointAdmin,apiKey:y.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(y){let E=y instanceof Error?y.message:"Failed to initialize Crudify";_chunkGNGIFVA4js.a.error("[CrudifyProvider] Initialization error",y instanceof Error?y:{message:String(y)}),o(E),m(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,w,c]);let a={crudify:c?_crudifybrowser2.default:null,isLoading:e,error:s,isInitialized:c,adminCredentials:T};return _jsxruntime.jsx.call(void 0, Ae.Provider,{value:a,children:i})},ke= exports.c =()=>{let r=_react.useContext.call(void 0, Ae);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var 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 _chunkGNGIFVA4js.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]:(_chunkGNGIFVA4js.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 _chunkGNGIFVA4js.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 _chunkGNGIFVA4js.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()},s=f.encrypt(JSON.stringify(t));e.setItem(f.TOKEN_KEY,s),_chunkGNGIFVA4js.a.debug("Crudify: Tokens saved successfully")}catch(t){_chunkGNGIFVA4js.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),s=JSON.parse(t);return!s.accessToken||!s.refreshToken||!s.expiresAt||!s.refreshExpiresAt?(_chunkGNGIFVA4js.a.warn("Crudify: Incomplete token data found, clearing storage"),f.clearTokens(),null):Date.now()>=s.refreshExpiresAt?(_chunkGNGIFVA4js.a.info("Crudify: Refresh token expired, clearing storage"),f.clearTokens(),null):{accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt}}catch(e){return _chunkGNGIFVA4js.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),_chunkGNGIFVA4js.a.debug("Crudify: Tokens cleared from storage")}catch(e){_chunkGNGIFVA4js.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),_chunkGNGIFVA4js.a.info("Crudify: Encryption key rotated successfully")}catch(i){_chunkGNGIFVA4js.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){_chunkGNGIFVA4js.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){_chunkGNGIFVA4js.a.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){_chunkGNGIFVA4js.a.debug("Crudify: Tokens updated in another tab");let s=f.getTokens();i(s)}}};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 Q=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},v.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkGNGIFVA4js.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&&await this.restoreSession(),this.initialized=!0}}async login(i,e){try{let t=await _crudifybrowser2.default.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let s=v.getTokens(),o=t.data,c={accessToken:o.token,refreshToken:o.refreshToken,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt,apiEndpointAdmin:_optionalChain([s, 'optionalAccess', _2 => _2.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([s, 'optionalAccess', _3 => _3.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return v.saveTokens(c),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.onLoginSuccess, 'optionalCall', _6 => _6(c)]),{success:!0,tokens:c,data:o}}catch(t){return _chunkGNGIFVA4js.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 s=v.getTokens();return s&&_optionalChain([this, 'access', _10 => _10.config, 'access', _11 => _11.onSessionRestored, 'optionalCall', _12 => _12(s)]),!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"),_chunkGNGIFVA4js.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"),_chunkGNGIFVA4js.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"),_chunkGNGIFVA4js.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(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=_crudifybrowser2.default.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";_crudifybrowser2.default.config(e);let t=this.config.publicApiKey,s=this.config.enableLogging?"debug":"none",o=await _crudifybrowser2.default.init(t,s);if(o&&o.success===!1&&o.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(o.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw _chunkGNGIFVA4js.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(s=>s.errorType==="Unauthorized"||_optionalChain([s, 'access', _30 => _30.message, 'optionalAccess', _31 => _31.includes, 'call', _32 => _32("Unauthorized")])||_optionalChain([s, 'access', _33 => _33.message, 'optionalAccess', _34 => _34.includes, 'call', _35 => _35("Not Authorized")])||_optionalChain([s, 'access', _36 => _36.message, 'optionalAccess', _37 => _37.includes, 'call', _38 => _38("NOT_AUTHORIZED")])||_optionalChain([s, 'access', _39 => _39.message, 'optionalAccess', _40 => _40.includes, 'call', _41 => _41("Token")])||_optionalChain([s, 'access', _42 => _42.message, 'optionalAccess', _43 => _43.includes, 'call', _44 => _44("TOKEN")])||_optionalChain([s, 'access', _45 => _45.message, 'optionalAccess', _46 => _46.includes, 'call', _47 => _47("Authentication")])||_optionalChain([s, 'access', _48 => _48.message, 'optionalAccess', _49 => _49.includes, 'call', _50 => _50("UNAUTHENTICATED")])||_optionalChain([s, 'access', _51 => _51.extensions, 'optionalAccess', _52 => _52.code])==="UNAUTHENTICATED"||_optionalChain([s, 'access', _53 => _53.extensions, 'optionalAccess', _54 => _54.code])==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(_optionalChain([t, 'access', _55 => _55.message, 'optionalAccess', _56 => _56.includes, 'call', _57 => _57("TOKEN")])||_optionalChain([t, 'access', _58 => _58.message, 'optionalAccess', _59 => _59.includes, 'call', _60 => _60("Token")]))&&(e.isTokenExpired=!0),_optionalChain([t, 'access', _61 => _61.extensions, 'optionalAccess', _62 => _62.code])==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let s=Object.values(i.errors).flat().find(o=>typeof o=="string"&&(o.includes("NOT_AUTHORIZED")||o.includes("TOKEN_REFRESH_FAILED")||o.includes("TOKEN_HAS_EXPIRED")||o.includes("PLEASE_LOGIN")||o.includes("Unauthorized")||o.includes("UNAUTHENTICATED")||o.includes("SESSION_EXPIRED")||o.includes("INVALID_TOKEN")));s&&typeof s=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,s.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):s.includes("TOKEN_HAS_EXPIRED")||s.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):s.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&_optionalChain([i, 'access', _63 => _63.data, 'optionalAccess', _64 => _64.response, 'optionalAccess', _65 => _65.status])){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&_optionalChain([i, 'access', _66 => _66.data, 'optionalAccess', _67 => _67.response, 'optionalAccess', _68 => _68.data]))try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch (e4){}if(!e.isAuthError&&i.errorCode){let t=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?_chunkGNGIFVA4js.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 be(r={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=Q.getInstance(),s=_react.useCallback.call(void 0, async()=>{try{e(n=>({...n,isLoading:!0,error:null}));let u={autoRestore:_nullishCoalesce(r.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(r.enableLogging, () => (!1)),showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([r, 'access', _69 => _69.onSessionExpired, 'optionalCall', _70 => _70()])},onSessionRestored:n=>{e(y=>({...y,isAuthenticated:!0,tokens:n,error:null})),_optionalChain([r, 'access', _71 => _71.onSessionRestored, 'optionalCall', _72 => _72(n)])},onLoginSuccess:n=>{e(y=>({...y,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(u),t.setupResponseInterceptor();let a=t.isAuthenticated(),l=t.getTokenInfo();e(n=>({...n,isAuthenticated:a,isInitialized:!0,isLoading:!1,tokens:l.crudifyTokens.accessToken?{accessToken:l.crudifyTokens.accessToken,refreshToken:l.crudifyTokens.refreshToken,expiresAt:l.crudifyTokens.expiresAt,refreshExpiresAt:l.crudifyTokens.refreshExpiresAt}:null}))}catch(u){let a=u instanceof Error?u.message:"Initialization failed";e(l=>({...l,isLoading:!1,isInitialized:!0,error:a}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),o=_react.useCallback.call(void 0, async(u,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(u,a);return l.success&&l.tokens?e(n=>({...n,isAuthenticated:!0,tokens:l.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),l}catch(l){let n=l instanceof Error?l.message:"Login failed",y=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(E=>({...E,isAuthenticated:!1,tokens:null,isLoading:!1,error:y?null:n})),{success:!1,error:n}}},[t]),c=_react.useCallback.call(void 0, async()=>{e(u=>({...u,isLoading:!0}));try{await t.logout(),e(u=>({...u,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(u){e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:u instanceof Error?u.message:"Logout error"}))}},[t]),m=_react.useCallback.call(void 0, async()=>{try{let u=await t.refreshTokens();if(u){let a=t.getTokenInfo();e(l=>({...l,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return u}catch(u){return e(a=>({...a,isAuthenticated:!1,tokens:null,error:u instanceof Error?u.message:"Token refresh failed"})),!1}},[t]),w=_react.useCallback.call(void 0, ()=>{e(u=>({...u,error:null}))},[]),I=_react.useCallback.call(void 0, ()=>t.getTokenInfo(),[t]);_react.useEffect.call(void 0, ()=>{s()},[s]),_react.useEffect.call(void 0, ()=>{if(!i.isAuthenticated||!i.tokens)return;let u=_chunkGNGIFVA4js.j.getInstance(),a=()=>{t.updateLastActivity()},l=u.subscribe(a);window.addEventListener("popstate",a);let n=()=>{let C=t.getTokenInfo().crudifyTokens.expiresIn||0;return C<300*1e3?30*1e3:C<1800*1e3?60*1e3:120*1e3},y,E=()=>{let b=n();y=setTimeout(async()=>{if(t.isRefreshing()){E();return}let C=t.getTokenInfo(),S=C.crudifyTokens.expiresIn||0,O=((C.crudifyTokens.expiresAt||0)-(Date.now()-S))*.5;if(S>0&&S<=O)if(e(L=>({...L,isLoading:!0})),await t.refreshTokens()){let L=t.getTokenInfo();e(ae=>({...ae,isLoading:!1,tokens:L.crudifyTokens.accessToken?{accessToken:L.crudifyTokens.accessToken,refreshToken:L.crudifyTokens.refreshToken,expiresAt:L.crudifyTokens.expiresAt,refreshExpiresAt:L.crudifyTokens.refreshExpiresAt}:null}))}else e(L=>({...L,isLoading:!1,isAuthenticated:!1,tokens:null}));let k=t.getTimeSinceLastActivity(),W=1800*1e3;k>W?await c():E()},b)};return E(),()=>{clearTimeout(y),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,c]),_react.useEffect.call(void 0, ()=>{let u=_chunkGNGIFVA4js.i.subscribe(async a=>{if(a.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;e(l=>({...l,isLoading:!0}));try{if(await t.refreshTokens()){let n=t.getTokenInfo();e(y=>({...y,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else _chunkGNGIFVA4js.i.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){_chunkGNGIFVA4js.i.emit("SESSION_EXPIRED",{message:l instanceof Error?l.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(a.type==="SESSION_EXPIRED"||a.type==="TOKEN_REFRESH_FAILED")&&(e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([a, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.message])||"Session expired"})),_optionalChain([r, 'access', _75 => _75.onSessionExpired, 'optionalCall', _76 => _76()]))});return()=>u()},[r.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{let u=v.subscribeToChanges(a=>{a?e(l=>({...l,tokens:a,isAuthenticated:!0})):(e(l=>({...l,isAuthenticated:!1,tokens:null})),_chunkGNGIFVA4js.i.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>u()},[]);let T=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]);return{...i,login:o,logout:c,refreshTokens:m,clearError:w,getTokenInfo:I,updateActivity:T,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var Se=_react.createContext.call(void 0, null),ti=r=>_dompurify2.default.sanitize(r,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),de= exports.g =({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:s=!1,allowHtml:o=!1})=>{let[c,m]=_react.useState.call(void 0, []),w=_react.useCallback.call(void 0, (a,l="info",n)=>{if(!s)return"";if(!a||typeof a!="string")return _chunkGNGIFVA4js.a.warn("GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(_chunkGNGIFVA4js.a.warn("GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let y=_uuid.v4.call(void 0, ),E={id:y,message:a,severity:l,autoHideDuration:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _77 => _77.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _78 => _78.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _79 => _79.allowHtml]), () => (o))};return m(b=>[...b.length>=i?b.slice(-(i-1)):b,E]),y},[i,e,s,o]),I=_react.useCallback.call(void 0, a=>{m(l=>l.filter(n=>n.id!==a))},[]),T=_react.useCallback.call(void 0, ()=>{m([])},[]),u={showNotification:w,hideNotification:I,clearAllNotifications:T};return _jsxruntime.jsxs.call(void 0, Se.Provider,{value:u,children:[r,s&&_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:c.map(a=>_jsxruntime.jsx.call(void 0, ri,{notification:a,onClose:()=>I(a.id)},a.id))})})]})},ri=({notification:r,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),s=_react.useCallback.call(void 0, (o,c)=>{c!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let o=setTimeout(()=>{s()},r.autoHideDuration);return()=>clearTimeout(o)}},[r.autoHideDuration,r.persistent,s]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:e,onClose:s,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:r.severity,onClose:s,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:ti(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},we= exports.h =()=>{let r=_react.useContext.call(void 0, Se);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var Re=_react.createContext.call(void 0, void 0);function Pe({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:s={}}){let o;try{let{showNotification:n}=we();o=n}catch (e5){}let c={};try{let n=ke();n.isInitialized&&n.adminCredentials&&(c=n.adminCredentials)}catch (e6){}let m=_react.useMemo.call(void 0, ()=>{let n=_chunkGNGIFVA4js.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _80 => _80.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _81 => _81.env]),enableDebug:_optionalChain([i, 'optionalAccess', _82 => _82.enableLogging])});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,_optionalChain([i, 'optionalAccess', _83 => _83.enableLogging])]),w=_react2.default.useMemo(()=>({...i,showNotification:o,apiEndpointAdmin:c.apiEndpointAdmin,apiKeyEndpointAdmin:c.apiKeyEndpointAdmin,publicApiKey:m.publicApiKey,env:m.env,onSessionExpired:()=>{_optionalChain([i, 'access', _84 => _84.onSessionExpired, 'optionalCall', _85 => _85()])}}),[i,o,c.apiEndpointAdmin,c.apiKeyEndpointAdmin,m]),I=be(w),T=_react.useMemo.call(void 0, ()=>{let n=_chunkGNGIFVA4js.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _86 => _86.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _87 => _87.env]),appName:_optionalChain([e, 'optionalAccess', _88 => _88.appName]),logo:_optionalChain([e, 'optionalAccess', _89 => _89.logo]),loginActions:_optionalChain([e, 'optionalAccess', _90 => _90.loginActions]),enableDebug:_optionalChain([i, 'optionalAccess', _91 => _91.enableLogging])});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,_optionalChain([i, 'optionalAccess', _92 => _92.enableLogging])]),u=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([I, 'access', _93 => _93.tokens, 'optionalAccess', _94 => _94.accessToken])||!I.isAuthenticated)return null;try{let n=_chunkGNGIFVA4js.k.call(void 0, I.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let y={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(E=>{["sub","email","subscriber"].includes(E)||(y[E]=n[E])}),y}}catch(n){_chunkGNGIFVA4js.a.error("Error decoding JWT token for sessionData",n instanceof Error?n:{message:String(n)})}return null},[_optionalChain([I, 'access', _95 => _95.tokens, 'optionalAccess', _96 => _96.accessToken]),I.isAuthenticated]),a={...I,sessionData:u,config:T},l={enabled:t,maxNotifications:s.maxNotifications||5,defaultAutoHideDuration:s.defaultAutoHideDuration||6e3,position:s.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, Re.Provider,{value:a,children:r})}function ct(r){let i={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _97 => _97.notificationOptions, 'optionalAccess', _98 => _98.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _99 => _99.notificationOptions, 'optionalAccess', _100 => _100.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _101 => _101.notificationOptions, 'optionalAccess', _102 => _102.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _103 => _103.notificationOptions, 'optionalAccess', _104 => _104.allowHtml])||!1};return _optionalChain([r, 'access', _105 => _105.config, 'optionalAccess', _106 => _106.publicApiKey])?_jsxruntime.jsx.call(void 0, Ie,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:_jsxruntime.jsx.call(void 0, de,{...i,children:_jsxruntime.jsx.call(void 0, Pe,{...r})})}):_jsxruntime.jsx.call(void 0, de,{...i,children:_jsxruntime.jsx.call(void 0, Pe,{...r})})}function li(){let r=_react.useContext.call(void 0, Re);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function ut(){let r=li();return r.isInitialized?_jsxruntime.jsxs.call(void 0, "div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[_jsxruntime.jsx.call(void 0, "h4",{children:"Session Debug Info"}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var ht=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[s,o]=_react.useState.call(void 0, null),[c,m]=_react.useState.call(void 0, !1),[w,I]=_react.useState.call(void 0, null),[T,u]=_react.useState.call(void 0, {}),a=_react.useRef.call(void 0, null),l=_react.useRef.call(void 0, !0),n=_react.useRef.call(void 0, 0),y=_react.useRef.call(void 0, 0),E=_react.useCallback.call(void 0, ()=>{o(null),I(null),m(!1),u({})},[]),b=_react.useCallback.call(void 0, async()=>{let C=_chunkGNGIFVA4js.l.call(void 0, );if(!C){l.current&&(I("No user email available"),m(!1));return}a.current&&a.current.abort();let S=new AbortController;a.current=S;let D=++n.current;try{l.current&&(m(!0),I(null));let F=await _crudifybrowser2.default.readItems("users",{filter:{email:C},pagination:{limit:1}});if(D===n.current&&l.current&&!S.signal.aborted){let O=F.data;if(F.success&&O&&O.length>0){let k=O[0];o(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(Y=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(Y)).reduce((Y,L)=>({...Y,[L]:k[L]}),{})}};u(W),I(null),y.current=0}else I("User profile not found"),o(null),u({})}}catch(F){if(D===n.current&&l.current){let O=F;if(O.name==="AbortError")return;e&&y.current<t&&(_optionalChain([O, 'access', _107 => _107.message, 'optionalAccess', _108 => _108.includes, 'call', _109 => _109("Network Error")])||_optionalChain([O, 'access', _110 => _110.message, 'optionalAccess', _111 => _111.includes, 'call', _112 => _112("Failed to fetch")]))?(y.current++,setTimeout(()=>{l.current&&b()},1e3*y.current)):(I("Failed to load user profile"),o(null),u({}))}}finally{D===n.current&&l.current&&m(!1),a.current===S&&(a.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{i&&b()},[i,b]),_react.useEffect.call(void 0, ()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:s,loading:c,error:w,extendedData:T,refreshProfile:b,clearProfile:E}};var vt=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:s}=i,{prefix:o,padding:c=0,separator:m=""}=r,[w,I]=_react.useState.call(void 0, ""),[T,u]=_react.useState.call(void 0, !1),[a,l]=_react.useState.call(void 0, null),n=_react.useRef.call(void 0, !1),y=_react.useCallback.call(void 0, S=>{let D=String(S).padStart(c,"0");return`${o}${m}${D}`},[o,c,m]),E=_react.useCallback.call(void 0, async()=>{u(!0),l(null);try{let S=await _crudifybrowser2.default.getNextSequence(o),D=S.data;if(S.success&&_optionalChain([D, 'optionalAccess', _113 => _113.value])){let F=y(D.value);I(F),_optionalChain([t, 'optionalCall', _114 => _114(F)])}else{let F=_optionalChain([S, 'access', _115 => _115.errors, 'optionalAccess', _116 => _116._error, 'optionalAccess', _117 => _117[0]])||"Failed to generate code";l(F),_optionalChain([s, 'optionalCall', _118 => _118(F)])}}catch(S){let D=S instanceof Error?S.message:"Unknown error";l(D),_optionalChain([s, 'optionalCall', _119 => _119(D)])}finally{u(!1)}},[o,y,t,s]),b=_react.useCallback.call(void 0, async()=>{await E()},[E]),C=_react.useCallback.call(void 0, ()=>{l(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!w&&!n.current&&(n.current=!0,E())},[e,w,E]),{value:w,loading:T,error:a,regenerate:b,clearError:C}};var ye=class r{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 r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:s,enableLogging:o,requestedBy:c}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&_chunkGNGIFVA4js.a.warn(`[CrudifyInitialization] ${c} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _120 => _120.state, 'access', _121 => _121.publicApiKey, 'optionalAccess', _122 => _122.slice, 'call', _123 => _123(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return o&&_chunkGNGIFVA4js.a.debug(`[CrudifyInitialization] ${c} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(o&&_chunkGNGIFVA4js.a.debug(`[CrudifyInitialization] ${c} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(c),await this.waitForHighPriorityOrTimeout(o),this.waitingForHighPriority.delete(c),this.getState().status==="INITIALIZED"){o&&_chunkGNGIFVA4js.a.debug(`[CrudifyInitialization] ${c} found initialization completed by HIGH priority`);return}o&&_chunkGNGIFVA4js.a.warn(`[CrudifyInitialization] ${c} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(_chunkGNGIFVA4js.a.warn(`[CrudifyInitialization] HIGH priority request from ${c} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),o&&_chunkGNGIFVA4js.a.debug(`[CrudifyInitialization] ${c} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=c,this.initializationPromise=this.performInitialization(t,s,o);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=s,this.state.error=null,o&&_chunkGNGIFVA4js.a.info(`[CrudifyInitialization] Successfully initialized by ${c} (${e} priority)`)}catch(m){throw this.state.status="ERROR",this.state.error=m instanceof Error?m:new Error(String(m)),this.initializationPromise=null,_chunkGNGIFVA4js.a.error(`[CrudifyInitialization] Initialization failed for ${c}`,m instanceof Error?m:{message:String(m)}),m}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let s=0,o=setInterval(()=>{if(s+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(o),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){s=0;return}s>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(o),i&&_chunkGNGIFVA4js.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let s=_crudifybrowser2.default.getTokenData();if(s&&s.endpoint){t&&_chunkGNGIFVA4js.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifybrowser2.default.config(e);let o=t?"debug":"none",c=await _crudifybrowser2.default.init(i,o);if(c.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(c.errors||"Unknown error")}`);c.apiEndpointAdmin&&c.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:c.apiEndpointAdmin,apiKey:c.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 =ye.getInstance();var Le=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,yi=r=>{let i=r.lastIndexOf("."),e=i>0?r.substring(i):"",t=Date.now(),s=Math.random().toString(36).substring(2,8);return`${t}_${s}${e}`},Nt= exports.p =(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:s=0,visibility:o="private",onUploadComplete:c,onUploadError:m,onFileRemoved:w,onFilesChange:I}=r,[T,u]=_react.useState.call(void 0, []),[a,l]=_react.useState.call(void 0, !1),n=_react.useRef.call(void 0, new Map),y=_react.useCallback.call(void 0, ()=>{l(!0)},[]),E=_react.useCallback.call(void 0, (d,h)=>{u(g=>g.map(A=>A.id===d?{...A,...h}:A))},[]),b=_react.useCallback.call(void 0, d=>{_optionalChain([I, 'optionalCall', _124 => _124(d)])},[I]),C=_react.useCallback.call(void 0, d=>i&&i.length>0&&!i.includes(d.type)?{valid:!1,error:`File type not allowed: ${d.type}`}:d.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(d,h)=>{try{if(!se.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let g=yi(h.name),x=await _crudifybrowser2.default.generateSignedUrl({fileName:g,contentType:h.type,visibility:o});if(!x.success||!x.data)throw new Error("Failed to get upload URL");let A=x.data,{uploadUrl:z,s3Key:P,publicUrl:H}=A;if(!z||!P)throw new Error("Incomplete signed URL response");let X=P.indexOf("/"),He=X>0?P.substring(X+1):P;E(d.id,{status:"uploading",progress:0}),await new Promise((le,$)=>{let K=new XMLHttpRequest;K.upload.addEventListener("progress",_=>{if(_.lengthComputable){let Ge=Math.round(_.loaded/_.total*100);E(d.id,{progress:Ge})}}),K.addEventListener("load",()=>{K.status>=200&&K.status<300?le():$(new Error(`Upload failed with status ${K.status}`))}),K.addEventListener("error",()=>{$(new Error("Network error during upload"))}),K.addEventListener("abort",()=>{$(new Error("Upload cancelled"))}),K.open("PUT",z),K.setRequestHeader("Content-Type",h.type),K.send(h)});let Me={status:"completed",progress:100,filePath:He,visibility:o,publicUrl:o==="public"?H:void 0,file:void 0};u(le=>{let $=le.map(_=>_.id===d.id?{..._,...Me}:_);b($);let K=$.find(_=>_.id===d.id);return K&&_optionalChain([c, 'optionalCall', _125 => _125(K)]),$})}catch(g){let x=g instanceof Error?g.message:"Unknown error";E(d.id,{status:"error",progress:0,errorMessage:x}),u(A=>{let z=A.find(P=>P.id===d.id);return z&&_optionalChain([m, 'optionalCall', _126 => _126(z,x)]),A})}},[E,c,m,o]),D=_react.useCallback.call(void 0, async d=>{let h=Array.from(d),g=[];u(x=>{if(t!==void 0){let P=x.filter(X=>X.status!=="error").length,H=t-P;if(H<=0)return _chunkGNGIFVA4js.a.warn(`File limit of ${t} already reached`),x;h.length>H&&(h=h.slice(0,H),_chunkGNGIFVA4js.a.warn(`Only ${H} files will be added to not exceed limit`))}let A=[];for(let P of h){let H=C(P),X={id:Le(),name:P.name,size:P.size,contentType:P.type,status:H.valid?"pending":"error",progress:0,createdAt:Date.now(),file:H.valid?P:void 0,errorMessage:H.error};A.push(X)}g=A;let z=[...x,...A];return b(z),z}),setTimeout(()=>{let x=g.filter(A=>A.status==="pending"&&A.file);for(let A of x)if(A.file){let z=S(A,A.file);n.current.set(A.id,z),z.finally(()=>{n.current.delete(A.id)})}},0)},[t,C,S,b]),F=_react.useCallback.call(void 0, async d=>{let h=T.find(g=>g.id===d);if(!h)return!1;E(d,{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 u(g=>{let x=g.filter(A=>A.id!==d);return b(x),x}),_optionalChain([w, 'optionalCall', _127 => _127(h)]),!0}catch(g){return E(d,{status:h.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error removing file"}),!1}},[T,E,b,w]),O=_react.useCallback.call(void 0, ()=>{u([]),b([])},[b]),k=_react.useCallback.call(void 0, async d=>{let h=T.find(x=>x.id===d);if(!h||h.status!=="error"||!h.file){_chunkGNGIFVA4js.a.warn("Cannot retry: file not found or no original file");return}E(d,{status:"pending",progress:0,errorMessage:void 0});let g=S(h,h.file);n.current.set(d,g),g.finally(()=>{n.current.delete(d)})},[T,E,S]),W=_react.useCallback.call(void 0, async()=>{let d=Array.from(n.current.values());d.length>0&&await Promise.allSettled(d)},[]),Y=d=>{let h=_optionalChain([d, 'access', _128 => _128.split, 'call', _129 => _129("."), 'access', _130 => _130.pop, 'call', _131 => _131(), 'optionalAccess', _132 => _132.toLowerCase, 'call', _133 => _133()])||"";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"},L=_react.useCallback.call(void 0, d=>{let h=d.map(g=>{let A=g.filePath.startsWith("http://")||g.filePath.startsWith("https://")?new URL(g.filePath).pathname:g.filePath,z=A.includes("/public/")||A.startsWith("public/")?"public":"private",P=g.contentType||Y(g.name);return{id:Le(),name:g.name,size:g.size||0,contentType:P,status:"completed",progress:100,filePath:g.filePath,visibility:z,createdAt:Date.now()}});u(h),b(h)},[b]),ae=_react.useCallback.call(void 0, async d=>{let h=T.find(g=>g.id===d);if(!h||!h.filePath)return null;if(h.visibility==="public"&&h.publicUrl)return h.publicUrl;try{if(!se.isInitialized())return null;let g=await _crudifybrowser2.default.getFileUrl({filePath:h.filePath,expiresIn:3600}),x=g.data;return g.success&&_optionalChain([x, 'optionalAccess', _134 => _134.url])?x.url:null}catch (e7){return null}},[T]),Fe=_react.useMemo.call(void 0, ()=>T.some(d=>d.status==="uploading"||d.status==="pending"),[T]),ze=_react.useMemo.call(void 0, ()=>T.filter(d=>d.status==="uploading"||d.status==="pending").length,[T]),Ke=_react.useMemo.call(void 0, ()=>T.filter(d=>d.status==="completed"&&d.filePath).map(d=>d.filePath),[T]),{isValid:Ue,validationError:Oe}=_react.useMemo.call(void 0, ()=>{let d=T.filter(g=>g.status==="completed").length;return d<s?{isValid:!1,validationError:s===1?"At least one file is required":`At least ${s} files are required`}:t!==void 0&&d>t?{isValid:!1,validationError:`Maximum ${t} files allowed`}:T.some(g=>g.status==="error")?{isValid:!1,validationError:"Some files have errors"}:{isValid:!0,validationError:null}},[T,s,t]);return{files:T,isUploading:Fe,pendingCount:ze,addFiles:D,removeFile:F,clearFiles:O,retryUpload:k,isValid:Ue,validationError:Oe,waitForUploads:W,completedFilePaths:Ke,initializeFiles:L,isTouched:a,markAsTouched:y,getPreviewUrl:ae}};exports.a = j; exports.b = Ie; exports.c = ke; exports.d = v; exports.e = Q; exports.f = be; exports.g = de; exports.h = we; exports.i = ct; exports.j = li; exports.k = ut; exports.l = ht; exports.m = vt; exports.n = ye; exports.o = se; exports.p = Nt;
|