@nocios/crudify-ui 4.4.52 → 4.4.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkJUJPXET6js = require('./chunk-JUJPXET6.js');var _chunk46F72M7Fjs = require('./chunk-46F72M7F.js');require('./chunk-YIIUEOXC.js');require('./chunk-FC7HOMNQ.js');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');function B({showBelowMinutes:f=5,position:c="bottom-right",colorNormal:m="#ed6c02",colorCritical:x="#d32f2f",style:u,className:g}={}){let{isAuthenticated:o,tokens:t}=_chunk46F72M7Fjs.f.call(void 0, ),[i,y]=_react.useState.call(void 0, 0),[h,S]=_react.useState.call(void 0, 100);if(_react.useEffect.call(void 0, ()=>{if(!o||!t)return;let v=setInterval(()=>{let P=Date.now(),p=t.expiresAt-P,w=900*1e3;y(Math.max(0,p)),S(Math.max(0,p/w*100))},1e3);return()=>clearInterval(v)},[o,t]),!o||i<=0)return null;let e=Math.floor(i/6e4),b=Math.floor(i%6e4/1e3);if(e>=f)return null;let s=e<2,a=s?x:m,C={"top-left":{top:"16px",left:"16px"},"top-right":{top:"16px",right:"16px"},"bottom-left":{bottom:"16px",left:"16px"},"bottom-right":{bottom:"16px",right:"16px"}}[c];return _jsxruntime.jsxs.call(void 0, "div",{className:g,style:{position:"fixed",...C,padding:"12px 16px",backgroundColor:"white",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",minWidth:"200px",zIndex:9999,fontFamily:"system-ui, -apple-system, sans-serif",...u},children:[_jsxruntime.jsxs.call(void 0, "div",{style:{marginBottom:"8px"},children:[_jsxruntime.jsx.call(void 0, "div",{style:{fontSize:"12px",fontWeight:600,color:a,marginBottom:"4px"},children:s?"\u26A0\uFE0F Sesi\xF3n expirando":"\u23F0 Sesi\xF3n por expirar"}),_jsxruntime.jsxs.call(void 0, "div",{style:{fontSize:"14px",color:"#333",fontWeight:500},children:[e,":",b.toString().padStart(2,"0")]})]}),_jsxruntime.jsx.call(void 0, "div",{style:{width:"100%",height:"6px",backgroundColor:"#e0e0e0",borderRadius:"3px",overflow:"hidden"},children:_jsxruntime.jsx.call(void 0, "div",{style:{width:`${h}%`,height:"100%",backgroundColor:a,transition:"width 1s linear"}})})]})}exports.CrudiaAutoGenerate = _chunkJUJPXET6js.o; exports.CrudiaFileField = _chunkJUJPXET6js.p; exports.CrudifyLogin = _chunkJUJPXET6js.h; exports.GlobalNotificationProvider = _chunk46F72M7Fjs.g; exports.LoginComponent = _chunkJUJPXET6js.m; exports.Policies = _chunkJUJPXET6js.l; exports.SessionStatus = _chunkJUJPXET6js.n; exports.SessionTimeIndicator = B; exports.UserProfileDisplay = _chunkJUJPXET6js.i; exports.useGlobalNotification = _chunk46F72M7Fjs.h;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunk7ICLHPYKjs = require('./chunk-7ICLHPYK.js');var _chunkATKMGMGSjs = require('./chunk-ATKMGMGS.js');require('./chunk-YIIUEOXC.js');require('./chunk-FC7HOMNQ.js');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');function z({showBelowMinutes:f=5,position:m="bottom-right",colorNormal:c="#ed6c02",colorCritical:x="#d32f2f",style:u,className:g}={}){let{isAuthenticated:o,tokens:t}=_chunkATKMGMGSjs.f.call(void 0, ),[i,y]=_react.useState.call(void 0, 0),[h,C]=_react.useState.call(void 0, 100);if(_react.useEffect.call(void 0, ()=>{if(!o||!t)return;let v=setInterval(()=>{let P=Date.now(),p=t.expiresAt-P,w=900*1e3;y(Math.max(0,p)),C(Math.max(0,p/w*100))},1e3);return()=>clearInterval(v)},[o,t]),!o||i<=0)return null;let e=Math.floor(i/6e4),S=Math.floor(i%6e4/1e3);if(e>=f)return null;let s=e<2,a=s?x:c,b={"top-left":{top:"16px",left:"16px"},"top-right":{top:"16px",right:"16px"},"bottom-left":{bottom:"16px",left:"16px"},"bottom-right":{bottom:"16px",right:"16px"}}[m];return _jsxruntime.jsxs.call(void 0, "div",{className:g,style:{position:"fixed",...b,padding:"12px 16px",backgroundColor:"white",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",minWidth:"200px",zIndex:9999,fontFamily:"system-ui, -apple-system, sans-serif",...u},children:[_jsxruntime.jsxs.call(void 0, "div",{style:{marginBottom:"8px"},children:[_jsxruntime.jsx.call(void 0, "div",{style:{fontSize:"12px",fontWeight:600,color:a,marginBottom:"4px"},children:s?"\u26A0\uFE0F Sesi\xF3n expirando":"\u23F0 Sesi\xF3n por expirar"}),_jsxruntime.jsxs.call(void 0, "div",{style:{fontSize:"14px",color:"#333",fontWeight:500},children:[e,":",S.toString().padStart(2,"0")]})]}),_jsxruntime.jsx.call(void 0, "div",{style:{width:"100%",height:"6px",backgroundColor:"#e0e0e0",borderRadius:"3px",overflow:"hidden"},children:_jsxruntime.jsx.call(void 0, "div",{style:{width:`${h}%`,height:"100%",backgroundColor:a,transition:"width 1s linear"}})})]})}exports.CrudiaAutoGenerate = _chunk7ICLHPYKjs.o; exports.CrudiaFileField = _chunk7ICLHPYKjs.p; exports.CrudiaMarkdownField = _chunk7ICLHPYKjs.q; exports.CrudifyLogin = _chunk7ICLHPYKjs.h; exports.GlobalNotificationProvider = _chunkATKMGMGSjs.g; exports.LoginComponent = _chunk7ICLHPYKjs.m; exports.Policies = _chunk7ICLHPYKjs.l; exports.SessionStatus = _chunk7ICLHPYKjs.n; exports.SessionTimeIndicator = z; exports.UserProfileDisplay = _chunk7ICLHPYKjs.i; exports.useGlobalNotification = _chunkATKMGMGSjs.h;
@@ -1 +1 @@
1
- import{h as T,i as F,l as G,m as L,n as A,o as M,p as R}from"./chunk-MZIP5WX6.mjs";import{f as l,g as I,h as N}from"./chunk-MU7DIUCZ.mjs";import"./chunk-BJ6PIVZR.mjs";import"./chunk-6GPSBDW6.mjs";import{useEffect as k,useState as d}from"react";import{jsx as r,jsxs as n}from"react/jsx-runtime";function B({showBelowMinutes:f=5,position:c="bottom-right",colorNormal:m="#ed6c02",colorCritical:x="#d32f2f",style:u,className:g}={}){let{isAuthenticated:o,tokens:t}=l(),[i,y]=d(0),[h,S]=d(100);if(k(()=>{if(!o||!t)return;let v=setInterval(()=>{let P=Date.now(),p=t.expiresAt-P,w=900*1e3;y(Math.max(0,p)),S(Math.max(0,p/w*100))},1e3);return()=>clearInterval(v)},[o,t]),!o||i<=0)return null;let e=Math.floor(i/6e4),b=Math.floor(i%6e4/1e3);if(e>=f)return null;let s=e<2,a=s?x:m,C={"top-left":{top:"16px",left:"16px"},"top-right":{top:"16px",right:"16px"},"bottom-left":{bottom:"16px",left:"16px"},"bottom-right":{bottom:"16px",right:"16px"}}[c];return n("div",{className:g,style:{position:"fixed",...C,padding:"12px 16px",backgroundColor:"white",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",minWidth:"200px",zIndex:9999,fontFamily:"system-ui, -apple-system, sans-serif",...u},children:[n("div",{style:{marginBottom:"8px"},children:[r("div",{style:{fontSize:"12px",fontWeight:600,color:a,marginBottom:"4px"},children:s?"\u26A0\uFE0F Sesi\xF3n expirando":"\u23F0 Sesi\xF3n por expirar"}),n("div",{style:{fontSize:"14px",color:"#333",fontWeight:500},children:[e,":",b.toString().padStart(2,"0")]})]}),r("div",{style:{width:"100%",height:"6px",backgroundColor:"#e0e0e0",borderRadius:"3px",overflow:"hidden"},children:r("div",{style:{width:`${h}%`,height:"100%",backgroundColor:a,transition:"width 1s linear"}})})]})}export{M as CrudiaAutoGenerate,R as CrudiaFileField,T as CrudifyLogin,I as GlobalNotificationProvider,L as LoginComponent,G as Policies,A as SessionStatus,B as SessionTimeIndicator,F as UserProfileDisplay,N as useGlobalNotification};
1
+ import{h as N,i as T,l as M,m as k,n as G,o as L,p as A,q as R}from"./chunk-W46IJS4Y.mjs";import{f as d,g as F,h as I}from"./chunk-5PKTOZAY.mjs";import"./chunk-BJ6PIVZR.mjs";import"./chunk-6GPSBDW6.mjs";import{useEffect as B,useState as l}from"react";import{jsx as r,jsxs as n}from"react/jsx-runtime";function z({showBelowMinutes:f=5,position:m="bottom-right",colorNormal:c="#ed6c02",colorCritical:x="#d32f2f",style:u,className:g}={}){let{isAuthenticated:o,tokens:t}=d(),[i,y]=l(0),[h,C]=l(100);if(B(()=>{if(!o||!t)return;let v=setInterval(()=>{let P=Date.now(),p=t.expiresAt-P,w=900*1e3;y(Math.max(0,p)),C(Math.max(0,p/w*100))},1e3);return()=>clearInterval(v)},[o,t]),!o||i<=0)return null;let e=Math.floor(i/6e4),S=Math.floor(i%6e4/1e3);if(e>=f)return null;let s=e<2,a=s?x:c,b={"top-left":{top:"16px",left:"16px"},"top-right":{top:"16px",right:"16px"},"bottom-left":{bottom:"16px",left:"16px"},"bottom-right":{bottom:"16px",right:"16px"}}[m];return n("div",{className:g,style:{position:"fixed",...b,padding:"12px 16px",backgroundColor:"white",borderRadius:"8px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",minWidth:"200px",zIndex:9999,fontFamily:"system-ui, -apple-system, sans-serif",...u},children:[n("div",{style:{marginBottom:"8px"},children:[r("div",{style:{fontSize:"12px",fontWeight:600,color:a,marginBottom:"4px"},children:s?"\u26A0\uFE0F Sesi\xF3n expirando":"\u23F0 Sesi\xF3n por expirar"}),n("div",{style:{fontSize:"14px",color:"#333",fontWeight:500},children:[e,":",S.toString().padStart(2,"0")]})]}),r("div",{style:{width:"100%",height:"6px",backgroundColor:"#e0e0e0",borderRadius:"3px",overflow:"hidden"},children:r("div",{style:{width:`${h}%`,height:"100%",backgroundColor:a,transition:"width 1s linear"}})})]})}export{L as CrudiaAutoGenerate,A as CrudiaFileField,R as CrudiaMarkdownField,N as CrudifyLogin,F as GlobalNotificationProvider,k as LoginComponent,M as Policies,G as SessionStatus,z as SessionTimeIndicator,T as UserProfileDisplay,I as useGlobalNotification};
package/dist/hooks.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkPB6RBTAUjs = require('./chunk-PB6RBTAU.js');var _chunk46F72M7Fjs = require('./chunk-46F72M7F.js');require('./chunk-FC7HOMNQ.js');exports.useAuth = _chunkPB6RBTAUjs.b; exports.useAutoGenerate = _chunk46F72M7Fjs.m; exports.useCrudifyWithNotifications = _chunkPB6RBTAUjs.d; exports.useData = _chunkPB6RBTAUjs.c; exports.useFileUpload = _chunk46F72M7Fjs.p; exports.useSession = _chunk46F72M7Fjs.f; exports.useUserData = _chunkPB6RBTAUjs.a; exports.useUserProfile = _chunk46F72M7Fjs.l;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkEMNHA2HKjs = require('./chunk-EMNHA2HK.js');var _chunkATKMGMGSjs = require('./chunk-ATKMGMGS.js');require('./chunk-FC7HOMNQ.js');exports.useAuth = _chunkEMNHA2HKjs.b; exports.useAutoGenerate = _chunkATKMGMGSjs.m; exports.useCrudifyWithNotifications = _chunkEMNHA2HKjs.d; exports.useData = _chunkEMNHA2HKjs.c; exports.useFileUpload = _chunkATKMGMGSjs.p; exports.useSession = _chunkATKMGMGSjs.f; exports.useUserData = _chunkEMNHA2HKjs.a; exports.useUserProfile = _chunkATKMGMGSjs.l;
package/dist/hooks.mjs CHANGED
@@ -1 +1 @@
1
- import{a as s,b as u,c as a,d as p}from"./chunk-ZSBJYELA.mjs";import{f as e,l as t,m as o,p as r}from"./chunk-MU7DIUCZ.mjs";import"./chunk-6GPSBDW6.mjs";export{u as useAuth,o as useAutoGenerate,p as useCrudifyWithNotifications,a as useData,r as useFileUpload,e as useSession,s as useUserData,t as useUserProfile};
1
+ import{a as s,b as u,c as a,d as p}from"./chunk-6RZTP6DV.mjs";import{f as e,l as t,m as o,p as r}from"./chunk-5PKTOZAY.mjs";import"./chunk-6GPSBDW6.mjs";export{u as useAuth,o as useAutoGenerate,p as useCrudifyWithNotifications,a as useData,r as useFileUpload,e as useSession,s as useUserData,t as useUserProfile};
package/dist/index.d.mts CHANGED
@@ -1,8 +1,8 @@
1
1
  import crudify__default from '@nocios/crudify-browser';
2
2
  export * from '@nocios/crudify-browser';
3
3
  export { default as crudify } from '@nocios/crudify-browser';
4
- import { c as CrudifyLoginConfig } from './CrudiaFileField-DJjiFRYH.mjs';
5
- export { B as BoxScreenType, a as CrudiaAutoGenerate, h as CrudiaAutoGenerateProps, b as CrudiaFileField, i as CrudiaFileFieldProps, C as CrudifyLogin, d as CrudifyLoginProps, e as CrudifyLoginTranslations, L as LoginComponent, j as POLICY_ACTIONS, k as PREFERRED_POLICY_ORDER, P as Policies, g as PolicyAction, S as SessionStatus, f as UserLoginData, U as UserProfileDisplay } from './CrudiaFileField-DJjiFRYH.mjs';
4
+ import { d as CrudifyLoginConfig } from './CrudiaMarkdownField-DolyQn1x.mjs';
5
+ export { B as BoxScreenType, a as CrudiaAutoGenerate, i as CrudiaAutoGenerateProps, b as CrudiaFileField, j as CrudiaFileFieldProps, c as CrudiaMarkdownField, k as CrudiaMarkdownFieldProps, C as CrudifyLogin, e as CrudifyLoginProps, f as CrudifyLoginTranslations, L as LoginComponent, l as POLICY_ACTIONS, m as PREFERRED_POLICY_ORDER, P as Policies, h as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './CrudiaMarkdownField-DolyQn1x.mjs';
6
6
  import React, { ReactNode } from 'react';
7
7
  export { A as ApiError, C as CrudifyApiResponse, a as CrudifyTransactionResponse, F as ForgotPasswordRequest, J as JwtPayload, b as LoginRequest, L as LoginResponse, R as ResetPasswordRequest, T as TransactionResponseData, U as UserProfile, V as ValidateCodeRequest, c as ValidationError } from './api-Djqihi4n.mjs';
8
8
  import { U as UseSessionOptions, T as TokenData, L as LoginResult } from './index-CQnAzvOE.mjs';
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import crudify__default from '@nocios/crudify-browser';
2
2
  export * from '@nocios/crudify-browser';
3
3
  export { default as crudify } from '@nocios/crudify-browser';
4
- import { c as CrudifyLoginConfig } from './CrudiaFileField-DyJ5U71w.js';
5
- export { B as BoxScreenType, a as CrudiaAutoGenerate, h as CrudiaAutoGenerateProps, b as CrudiaFileField, i as CrudiaFileFieldProps, C as CrudifyLogin, d as CrudifyLoginProps, e as CrudifyLoginTranslations, L as LoginComponent, j as POLICY_ACTIONS, k as PREFERRED_POLICY_ORDER, P as Policies, g as PolicyAction, S as SessionStatus, f as UserLoginData, U as UserProfileDisplay } from './CrudiaFileField-DyJ5U71w.js';
4
+ import { d as CrudifyLoginConfig } from './CrudiaMarkdownField-BB1lfJl2.js';
5
+ export { B as BoxScreenType, a as CrudiaAutoGenerate, i as CrudiaAutoGenerateProps, b as CrudiaFileField, j as CrudiaFileFieldProps, c as CrudiaMarkdownField, k as CrudiaMarkdownFieldProps, C as CrudifyLogin, e as CrudifyLoginProps, f as CrudifyLoginTranslations, L as LoginComponent, l as POLICY_ACTIONS, m as PREFERRED_POLICY_ORDER, P as Policies, h as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './CrudiaMarkdownField-BB1lfJl2.js';
6
6
  import React, { ReactNode } from 'react';
7
7
  export { A as ApiError, C as CrudifyApiResponse, a as CrudifyTransactionResponse, F as ForgotPasswordRequest, J as JwtPayload, b as LoginRequest, L as LoginResponse, R as ResetPasswordRequest, T as TransactionResponseData, U as UserProfile, V as ValidateCodeRequest, c as ValidationError } from './api-Djqihi4n.js';
8
8
  import { U as UseSessionOptions, T as TokenData, L as LoginResult } from './index-BVT7flO5.js';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createStarExport(obj) { Object.keys(obj) .filter((key) => key !== "default" && key !== "__esModule") .forEach((key) => { if (exports.hasOwnProperty(key)) { return; } Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]}); }); } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkJUJPXET6js = require('./chunk-JUJPXET6.js');var _chunkPB6RBTAUjs = require('./chunk-PB6RBTAU.js');var _chunk46F72M7Fjs = require('./chunk-46F72M7F.js');var _chunkNNY4A73Vjs = require('./chunk-NNY4A73V.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunkFC7HOMNQjs = require('./chunk-FC7HOMNQ.js');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser); _createStarExport(_crudifybrowser);var _react = require('react');var _material = require('@mui/material');var _jsxruntime = require('react/jsx-runtime');var De=(e={})=>{try{let r=_chunkFC7HOMNQjs.a.call(void 0, "theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){console.warn("Error parsing theme from cookie:",r)}return e};function Ge({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=_react.useMemo.call(void 0, ()=>{let s=De(r);return _material.createTheme.call(void 0, s)},[r]);return _jsxruntime.jsxs.call(void 0, _material.ThemeProvider,{theme:t,children:[!o&&_jsxruntime.jsx.call(void 0, _material.CssBaseline,{}),e]})}var _reactrouterdom = require('react-router-dom');var _e={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},Be=()=>_jsxruntime.jsx.call(void 0, "style",{children:`
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createStarExport(obj) { Object.keys(obj) .filter((key) => key !== "default" && key !== "__esModule") .forEach((key) => { if (exports.hasOwnProperty(key)) { return; } Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]}); }); } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk7ICLHPYKjs = require('./chunk-7ICLHPYK.js');var _chunkEMNHA2HKjs = require('./chunk-EMNHA2HK.js');var _chunkATKMGMGSjs = require('./chunk-ATKMGMGS.js');var _chunkNNY4A73Vjs = require('./chunk-NNY4A73V.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunkFC7HOMNQjs = require('./chunk-FC7HOMNQ.js');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser); _createStarExport(_crudifybrowser);var _react = require('react');var _material = require('@mui/material');var _jsxruntime = require('react/jsx-runtime');var Ge=(e={})=>{try{let r=_chunkFC7HOMNQjs.a.call(void 0, "theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){console.warn("Error parsing theme from cookie:",r)}return e};function Ke({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=_react.useMemo.call(void 0, ()=>{let s=Ge(r);return _material.createTheme.call(void 0, s)},[r]);return _jsxruntime.jsxs.call(void 0, _material.ThemeProvider,{theme:t,children:[!o&&_jsxruntime.jsx.call(void 0, _material.CssBaseline,{}),e]})}var _reactrouterdom = require('react-router-dom');var Be={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},He=()=>_jsxruntime.jsx.call(void 0, "style",{children:`
2
2
  @keyframes spin {
3
3
  0% { transform: rotate(0deg); }
4
4
  100% { transform: rotate(360deg); }
5
5
  }
6
- `});function S({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, Be,{}),_jsxruntime.jsxs.call(void 0, "div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[_jsxruntime.jsx.call(void 0, "div",{style:_e}),_jsxruntime.jsx.call(void 0, "p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:t})]})]})}var qe=/^[a-zA-Z0-9\-_./\?=&%#]+$/,We=[/^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]/,/\\/],C= exports.validateInternalRedirect =(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return console.warn("\u{1F6A8} Open redirect blocked (relative path):",e),r;if(!qe.test(o))return console.warn("\u{1F6A8} Open redirect blocked (invalid characters):",e),r;let t=o.toLowerCase();for(let a of We)if(a.test(t))return console.warn("\u{1F6A8} Open redirect blocked (dangerous pattern):",e),r;let s=o.split("?")[0].split("/").filter(Boolean);if(s.length===0)return o;for(let a of s)if(a===".."||a.includes(":")||a.length>100)return console.warn("\u{1F6A8} Open redirect blocked (suspicious path part):",a),r;return o},v= exports.extractSafeRedirectFromUrl =(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let s=decodeURIComponent(t);return C(s,r)}catch(o){return console.warn("\u{1F6A8} Error parsing redirect parameter:",o),r}};function U({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:s,isInitialized:a,tokens:p,error:g}=_chunk46F72M7Fjs.j.call(void 0, ),l=_reactrouterdom.useLocation.call(void 0, );if(!a||s)return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:r||_jsxruntime.jsx.call(void 0, S,{stage:"validating-session"})});let d=t&&_optionalChain([p, 'optionalAccess', _2 => _2.accessToken])&&p.accessToken.length>0;if(g||!t||!d){p&&(!p.accessToken||p.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let y=l.pathname+l.search,A=C(y),x=encodeURIComponent(A);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:`${o}?redirect=${x}`,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function w({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=_chunk46F72M7Fjs.j.call(void 0, ),t=_reactrouterdom.useLocation.call(void 0, );if(o){let s=new URLSearchParams(t.search),a=v(s,r);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:a,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}var N=_react.createContext.call(void 0, void 0),rr= exports.CrudifyInitializer =({config:e,children:r,fallback:o=null,onInitialized:t,onError:s})=>{let[a,p]=_react.useState.call(void 0, !1),[g,l]=_react.useState.call(void 0, !1),[d,y]=_react.useState.call(void 0, null),A=_react.useRef.call(void 0, !1),x=_react.useRef.call(void 0, !1);_react.useEffect.call(void 0, ()=>{A.current||(_chunk46F72M7Fjs.o.registerHighPriorityInitializer(),A.current=!0),x.current||(x.current=!0,(async()=>{l(!0),y(null);try{let c=_chunkFC7HOMNQjs.b.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _3 => _3.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _4 => _4.env]),enableDebug:_optionalChain([e, 'optionalAccess', _5 => _5.enableLogging])});if(!c.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");await _chunk46F72M7Fjs.o.initialize({priority:"HIGH",publicApiKey:c.publicApiKey,env:c.env||"prod",enableLogging:_optionalChain([e, 'optionalAccess', _6 => _6.enableLogging]),requestedBy:"CrudifyInitializer"}),p(!0),l(!1),t&&t()}catch(c){let z=c instanceof Error?c:new Error(String(c));y(z),l(!1),s&&s(z)}})())},[_optionalChain([e, 'optionalAccess', _7 => _7.publicApiKey]),_optionalChain([e, 'optionalAccess', _8 => _8.env]),_optionalChain([e, 'optionalAccess', _9 => _9.enableLogging]),t,s]);let G={isInitialized:a,isInitializing:g,error:d};return g&&o?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:o}):(d&&console.error("[CrudifyInitializer] Initialization failed:",d),_jsxruntime.jsx.call(void 0, N.Provider,{value:G,children:r}))},or= exports.useCrudifyInitializer =()=>{let e=_react.useContext.call(void 0, N);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};var _crudifyadmin = require('@nocios/crudify-admin'); var _crudifyadmin2 = _interopRequireDefault(_crudifyadmin);var D=!1,m=null;async function ir(){let r=_chunk46F72M7Fjs.e.getInstance().getTokenInfo(),o=_optionalChain([r, 'optionalAccess', _10 => _10.apiEndpointAdmin]),t=_optionalChain([r, 'optionalAccess', _11 => _11.apiKeyEndpointAdmin]);return o&&t?{apiUrl:o,apiKey:t}:_chunk46F72M7Fjs.a.waitForCredentials()}async function nr(){if(!D)return m||(m=(async()=>{try{let e=_chunk46F72M7Fjs.e.getInstance(),{apiUrl:r,apiKey:o}=await ir();_crudifyadmin2.default.init({url:r,apiKey:o,getAdditionalHeaders:()=>{let t=e.getTokenInfo();return _optionalChain([t, 'optionalAccess', _12 => _12.crudifyTokens, 'optionalAccess', _13 => _13.accessToken])?{Authorization:`Bearer ${t.crudifyTokens.accessToken}`}:{}}}),D=!0}catch(e){throw m=null,console.error("[crudifyAdminWrapper] Initialization failed:",e),e}})(),m)}async function n(e){try{await nr();let r=await e();return!r.success&&_optionalChain([r, 'access', _14 => _14.errors, 'optionalAccess', _15 => _15.includes, 'call', _16 => _16("401")])?await _chunk46F72M7Fjs.e.getInstance().refreshTokens()?await e():(console.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),r):r}catch(r){return console.error("[crudifyAdmin] Operation error:",r),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var sr={listModules:()=>n(()=>_crudifyadmin2.default.listModules()),getModule:e=>n(()=>_crudifyadmin2.default.getModule(e)),createModule:e=>n(()=>_crudifyadmin2.default.createModule(e)),editModule:(e,r)=>n(()=>_crudifyadmin2.default.editModule(e,r)),deleteModule:e=>n(()=>_crudifyadmin2.default.deleteModule(e)),activateModule:e=>n(()=>_crudifyadmin2.default.activateModule(e)),deactivateModule:e=>n(()=>_crudifyadmin2.default.deactivateModule(e)),getModuleVersions:e=>n(()=>_crudifyadmin2.default.getModuleVersions(e)),listActions:e=>n(()=>_crudifyadmin2.default.listActions(e)),getAction:e=>n(()=>_crudifyadmin2.default.getAction(e)),createAction:e=>n(()=>_crudifyadmin2.default.createAction(e)),editAction:(e,r)=>n(()=>_crudifyadmin2.default.editAction(e,r)),deleteAction:e=>n(()=>_crudifyadmin2.default.deleteAction(e)),activateAction:e=>n(()=>_crudifyadmin2.default.activateAction(e)),deactivateAction:e=>n(()=>_crudifyadmin2.default.deactivateAction(e)),getActionVersions:e=>n(()=>_crudifyadmin2.default.getActionVersions(e)),getActionsByProfile:e=>n(()=>_crudifyadmin2.default.getActionsByProfile(e)),updateActionsProfiles:e=>n(()=>_crudifyadmin2.default.updateActionsProfiles(e))};exports.AuthRoute = w; exports.CRITICAL_TRANSLATIONS = _chunkJUJPXET6js.a; exports.CrudiaAutoGenerate = _chunkJUJPXET6js.o; exports.CrudiaFileField = _chunkJUJPXET6js.p; exports.CrudifyInitializationManager = _chunk46F72M7Fjs.n; exports.CrudifyInitializer = rr; exports.CrudifyLogin = _chunkJUJPXET6js.h; exports.CrudifyProvider = _chunk46F72M7Fjs.b; exports.CrudifyThemeProvider = Ge; exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.GlobalNotificationProvider = _chunk46F72M7Fjs.g; exports.LoginComponent = _chunkJUJPXET6js.m; exports.POLICY_ACTIONS = _chunkJUJPXET6js.j; exports.PREFERRED_POLICY_ORDER = _chunkJUJPXET6js.k; exports.Policies = _chunkJUJPXET6js.l; exports.ProtectedRoute = U; exports.SessionDebugInfo = _chunk46F72M7Fjs.k; exports.SessionLoadingScreen = S; exports.SessionManager = _chunk46F72M7Fjs.e; exports.SessionProvider = _chunk46F72M7Fjs.i; exports.SessionStatus = _chunkJUJPXET6js.n; exports.TokenStorage = _chunk46F72M7Fjs.d; exports.TranslationService = _chunkJUJPXET6js.d; exports.TranslationsProvider = _chunkJUJPXET6js.f; exports.UserProfileDisplay = _chunkJUJPXET6js.i; exports.createErrorTranslator = _chunkFC7HOMNQjs.g; exports.crudify = _crudifybrowser2.default; exports.crudifyAdmin = sr; exports.crudifyInitManager = _chunk46F72M7Fjs.o; exports.decodeJwtSafely = _chunkFC7HOMNQjs.j; exports.extractSafeRedirectFromUrl = v; exports.getCookie = _chunkFC7HOMNQjs.a; exports.getCriticalLanguages = _chunkJUJPXET6js.b; exports.getCriticalTranslations = _chunkJUJPXET6js.c; exports.getCurrentUserEmail = _chunkFC7HOMNQjs.k; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunkFC7HOMNQjs.l; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.secureLocalStorage = _chunkNNY4A73Vjs.b; exports.secureSessionStorage = _chunkNNY4A73Vjs.a; exports.translateError = _chunkFC7HOMNQjs.f; exports.translateErrorCode = _chunkFC7HOMNQjs.d; exports.translateErrorCodes = _chunkFC7HOMNQjs.e; exports.translationService = _chunkJUJPXET6js.e; exports.useAuth = _chunkPB6RBTAUjs.b; exports.useAutoGenerate = _chunk46F72M7Fjs.m; exports.useCrudify = _chunk46F72M7Fjs.c; exports.useCrudifyInitializer = or; exports.useCrudifyWithNotifications = _chunkPB6RBTAUjs.d; exports.useData = _chunkPB6RBTAUjs.c; exports.useFileUpload = _chunk46F72M7Fjs.p; exports.useGlobalNotification = _chunk46F72M7Fjs.h; exports.useSession = _chunk46F72M7Fjs.f; exports.useSessionContext = _chunk46F72M7Fjs.j; exports.useTranslations = _chunkJUJPXET6js.g; exports.useUserData = _chunkPB6RBTAUjs.a; exports.useUserProfile = _chunk46F72M7Fjs.l; exports.validateInternalRedirect = C;
6
+ `});function S({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, He,{}),_jsxruntime.jsxs.call(void 0, "div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[_jsxruntime.jsx.call(void 0, "div",{style:Be}),_jsxruntime.jsx.call(void 0, "p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:t})]})]})}var We=/^[a-zA-Z0-9\-_./\?=&%#]+$/,Je=[/^https?:\/\//i,/^ftp:\/\//i,/^\/\//,/javascript:/i,/data:/i,/vbscript:/i,/about:/i,/\.\.\//,/\.\.\\/,/%2e%2e%2f/i,/%2e%2e%5c/i,/%2f%2f/i,/%5c%5c/i,/[\x00-\x1f\x7f-\x9f]/,/\\/],P= exports.validateInternalRedirect =(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return console.warn("\u{1F6A8} Open redirect blocked (relative path):",e),r;if(!We.test(o))return console.warn("\u{1F6A8} Open redirect blocked (invalid characters):",e),r;let t=o.toLowerCase();for(let a of Je)if(a.test(t))return console.warn("\u{1F6A8} Open redirect blocked (dangerous pattern):",e),r;let s=o.split("?")[0].split("/").filter(Boolean);if(s.length===0)return o;for(let a of s)if(a===".."||a.includes(":")||a.length>100)return console.warn("\u{1F6A8} Open redirect blocked (suspicious path part):",a),r;return o},v= exports.extractSafeRedirectFromUrl =(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let s=decodeURIComponent(t);return P(s,r)}catch(o){return console.warn("\u{1F6A8} Error parsing redirect parameter:",o),r}};function U({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:s,isInitialized:a,tokens:p,error:g}=_chunkATKMGMGSjs.j.call(void 0, ),d=_reactrouterdom.useLocation.call(void 0, );if(!a||s)return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:r||_jsxruntime.jsx.call(void 0, S,{stage:"validating-session"})});let l=t&&_optionalChain([p, 'optionalAccess', _2 => _2.accessToken])&&p.accessToken.length>0;if(g||!t||!l){p&&(!p.accessToken||p.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let y=d.pathname+d.search,A=P(y),x=encodeURIComponent(A);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:`${o}?redirect=${x}`,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function w({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=_chunkATKMGMGSjs.j.call(void 0, ),t=_reactrouterdom.useLocation.call(void 0, );if(o){let s=new URLSearchParams(t.search),a=v(s,r);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:a,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}var N=_react.createContext.call(void 0, void 0),or= exports.CrudifyInitializer =({config:e,children:r,fallback:o=null,onInitialized:t,onError:s})=>{let[a,p]=_react.useState.call(void 0, !1),[g,d]=_react.useState.call(void 0, !1),[l,y]=_react.useState.call(void 0, null),A=_react.useRef.call(void 0, !1),x=_react.useRef.call(void 0, !1);_react.useEffect.call(void 0, ()=>{A.current||(_chunkATKMGMGSjs.o.registerHighPriorityInitializer(),A.current=!0),x.current||(x.current=!0,(async()=>{d(!0),y(null);try{let c=_chunkFC7HOMNQjs.b.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _3 => _3.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _4 => _4.env]),enableDebug:_optionalChain([e, 'optionalAccess', _5 => _5.enableLogging])});if(!c.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");await _chunkATKMGMGSjs.o.initialize({priority:"HIGH",publicApiKey:c.publicApiKey,env:c.env||"prod",enableLogging:_optionalChain([e, 'optionalAccess', _6 => _6.enableLogging]),requestedBy:"CrudifyInitializer"}),p(!0),d(!1),t&&t()}catch(c){let M=c instanceof Error?c:new Error(String(c));y(M),d(!1),s&&s(M)}})())},[_optionalChain([e, 'optionalAccess', _7 => _7.publicApiKey]),_optionalChain([e, 'optionalAccess', _8 => _8.env]),_optionalChain([e, 'optionalAccess', _9 => _9.enableLogging]),t,s]);let G={isInitialized:a,isInitializing:g,error:l};return g&&o?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:o}):(l&&console.error("[CrudifyInitializer] Initialization failed:",l),_jsxruntime.jsx.call(void 0, N.Provider,{value:G,children:r}))},tr= exports.useCrudifyInitializer =()=>{let e=_react.useContext.call(void 0, N);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};var _crudifyadmin = require('@nocios/crudify-admin'); var _crudifyadmin2 = _interopRequireDefault(_crudifyadmin);var D=!1,m=null;async function nr(){let r=_chunkATKMGMGSjs.e.getInstance().getTokenInfo(),o=_optionalChain([r, 'optionalAccess', _10 => _10.apiEndpointAdmin]),t=_optionalChain([r, 'optionalAccess', _11 => _11.apiKeyEndpointAdmin]);return o&&t?{apiUrl:o,apiKey:t}:_chunkATKMGMGSjs.a.waitForCredentials()}async function sr(){if(!D)return m||(m=(async()=>{try{let e=_chunkATKMGMGSjs.e.getInstance(),{apiUrl:r,apiKey:o}=await nr();_crudifyadmin2.default.init({url:r,apiKey:o,getAdditionalHeaders:()=>{let t=e.getTokenInfo();return _optionalChain([t, 'optionalAccess', _12 => _12.crudifyTokens, 'optionalAccess', _13 => _13.accessToken])?{Authorization:`Bearer ${t.crudifyTokens.accessToken}`}:{}}}),D=!0}catch(e){throw m=null,console.error("[crudifyAdminWrapper] Initialization failed:",e),e}})(),m)}async function n(e){try{await sr();let r=await e();return!r.success&&_optionalChain([r, 'access', _14 => _14.errors, 'optionalAccess', _15 => _15.includes, 'call', _16 => _16("401")])?await _chunkATKMGMGSjs.e.getInstance().refreshTokens()?await e():(console.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),r):r}catch(r){return console.error("[crudifyAdmin] Operation error:",r),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var ar={listModules:()=>n(()=>_crudifyadmin2.default.listModules()),getModule:e=>n(()=>_crudifyadmin2.default.getModule(e)),createModule:e=>n(()=>_crudifyadmin2.default.createModule(e)),editModule:(e,r)=>n(()=>_crudifyadmin2.default.editModule(e,r)),deleteModule:e=>n(()=>_crudifyadmin2.default.deleteModule(e)),activateModule:e=>n(()=>_crudifyadmin2.default.activateModule(e)),deactivateModule:e=>n(()=>_crudifyadmin2.default.deactivateModule(e)),getModuleVersions:e=>n(()=>_crudifyadmin2.default.getModuleVersions(e)),listActions:e=>n(()=>_crudifyadmin2.default.listActions(e)),getAction:e=>n(()=>_crudifyadmin2.default.getAction(e)),createAction:e=>n(()=>_crudifyadmin2.default.createAction(e)),editAction:(e,r)=>n(()=>_crudifyadmin2.default.editAction(e,r)),deleteAction:e=>n(()=>_crudifyadmin2.default.deleteAction(e)),activateAction:e=>n(()=>_crudifyadmin2.default.activateAction(e)),deactivateAction:e=>n(()=>_crudifyadmin2.default.deactivateAction(e)),getActionVersions:e=>n(()=>_crudifyadmin2.default.getActionVersions(e)),getActionsByProfile:e=>n(()=>_crudifyadmin2.default.getActionsByProfile(e)),updateActionsProfiles:e=>n(()=>_crudifyadmin2.default.updateActionsProfiles(e))};exports.AuthRoute = w; exports.CRITICAL_TRANSLATIONS = _chunk7ICLHPYKjs.a; exports.CrudiaAutoGenerate = _chunk7ICLHPYKjs.o; exports.CrudiaFileField = _chunk7ICLHPYKjs.p; exports.CrudiaMarkdownField = _chunk7ICLHPYKjs.q; exports.CrudifyInitializationManager = _chunkATKMGMGSjs.n; exports.CrudifyInitializer = or; exports.CrudifyLogin = _chunk7ICLHPYKjs.h; exports.CrudifyProvider = _chunkATKMGMGSjs.b; exports.CrudifyThemeProvider = Ke; exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.GlobalNotificationProvider = _chunkATKMGMGSjs.g; exports.LoginComponent = _chunk7ICLHPYKjs.m; exports.POLICY_ACTIONS = _chunk7ICLHPYKjs.j; exports.PREFERRED_POLICY_ORDER = _chunk7ICLHPYKjs.k; exports.Policies = _chunk7ICLHPYKjs.l; exports.ProtectedRoute = U; exports.SessionDebugInfo = _chunkATKMGMGSjs.k; exports.SessionLoadingScreen = S; exports.SessionManager = _chunkATKMGMGSjs.e; exports.SessionProvider = _chunkATKMGMGSjs.i; exports.SessionStatus = _chunk7ICLHPYKjs.n; exports.TokenStorage = _chunkATKMGMGSjs.d; exports.TranslationService = _chunk7ICLHPYKjs.d; exports.TranslationsProvider = _chunk7ICLHPYKjs.f; exports.UserProfileDisplay = _chunk7ICLHPYKjs.i; exports.createErrorTranslator = _chunkFC7HOMNQjs.g; exports.crudify = _crudifybrowser2.default; exports.crudifyAdmin = ar; exports.crudifyInitManager = _chunkATKMGMGSjs.o; exports.decodeJwtSafely = _chunkFC7HOMNQjs.j; exports.extractSafeRedirectFromUrl = v; exports.getCookie = _chunkFC7HOMNQjs.a; exports.getCriticalLanguages = _chunk7ICLHPYKjs.b; exports.getCriticalTranslations = _chunk7ICLHPYKjs.c; exports.getCurrentUserEmail = _chunkFC7HOMNQjs.k; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunkFC7HOMNQjs.l; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.secureLocalStorage = _chunkNNY4A73Vjs.b; exports.secureSessionStorage = _chunkNNY4A73Vjs.a; exports.translateError = _chunkFC7HOMNQjs.f; exports.translateErrorCode = _chunkFC7HOMNQjs.d; exports.translateErrorCodes = _chunkFC7HOMNQjs.e; exports.translationService = _chunk7ICLHPYKjs.e; exports.useAuth = _chunkEMNHA2HKjs.b; exports.useAutoGenerate = _chunkATKMGMGSjs.m; exports.useCrudify = _chunkATKMGMGSjs.c; exports.useCrudifyInitializer = tr; exports.useCrudifyWithNotifications = _chunkEMNHA2HKjs.d; exports.useData = _chunkEMNHA2HKjs.c; exports.useFileUpload = _chunkATKMGMGSjs.p; exports.useGlobalNotification = _chunkATKMGMGSjs.h; exports.useSession = _chunkATKMGMGSjs.f; exports.useSessionContext = _chunkATKMGMGSjs.j; exports.useTranslations = _chunk7ICLHPYKjs.g; exports.useUserData = _chunkEMNHA2HKjs.a; exports.useUserProfile = _chunkATKMGMGSjs.l; exports.validateInternalRedirect = P;
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import{a as K,b as V,c as _,d as B,e as H,f as q,g as W,h as ge,i as Ae,j as xe,k as Re,l as Pe,m as Ce,n as Ie,o as Se,p as ze}from"./chunk-MZIP5WX6.mjs";import{a as Ee,b as Me,c as be,d as ke}from"./chunk-ZSBJYELA.mjs";import{a as M,b as J,c as $,d as Y,e as u,f as ee,g as ie,h as ne,i as se,j as f,k as ae,l as ye,m as he,n as ve,o as R,p as Te}from"./chunk-MU7DIUCZ.mjs";import{a as Le,b as Ue}from"./chunk-T2CPA46I.mjs";import{a as pe,b as ce,c as le,d as de,e as ue,f as fe,g as me}from"./chunk-BJ6PIVZR.mjs";import{a as h,b as E,d as Z,e as Q,f as X,g as j,j as re,k as oe,l as te}from"./chunk-6GPSBDW6.mjs";import{default as qr}from"@nocios/crudify-browser";export*from"@nocios/crudify-browser";import{useMemo as we}from"react";import{ThemeProvider as Oe,createTheme as Fe,CssBaseline as Ne}from"@mui/material";import{jsx as Ke,jsxs as Ve}from"react/jsx-runtime";var De=(e={})=>{try{let r=h("theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){console.warn("Error parsing theme from cookie:",r)}return e};function Ge({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=we(()=>{let s=De(r);return Fe(s)},[r]);return Ve(Oe,{theme:t,children:[!o&&Ke(Ne,{}),e]})}import{Navigate as Je,useLocation as $e}from"react-router-dom";import{Fragment as He,jsx as P,jsxs as b}from"react/jsx-runtime";var _e={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},Be=()=>P("style",{children:`
1
+ import{a as K,b as V,c as _,d as B,e as H,f as q,g as W,h as ge,i as Ae,j as xe,k as Re,l as Ce,m as Pe,n as Ie,o as Se,p as Me,q as ze}from"./chunk-W46IJS4Y.mjs";import{a as Ee,b as be,c as Le,d as we}from"./chunk-6RZTP6DV.mjs";import{a as E,b as J,c as $,d as Y,e as u,f as ee,g as ie,h as ne,i as se,j as f,k as ae,l as ye,m as he,n as ve,o as R,p as Te}from"./chunk-5PKTOZAY.mjs";import{a as Ue,b as ke}from"./chunk-T2CPA46I.mjs";import{a as pe,b as ce,c as de,d as le,e as ue,f as fe,g as me}from"./chunk-BJ6PIVZR.mjs";import{a as h,b as z,d as Z,e as Q,f as X,g as j,j as re,k as oe,l as te}from"./chunk-6GPSBDW6.mjs";import{default as Wr}from"@nocios/crudify-browser";export*from"@nocios/crudify-browser";import{useMemo as Fe}from"react";import{ThemeProvider as Oe,createTheme as Ne,CssBaseline as De}from"@mui/material";import{jsx as Ve,jsxs as _e}from"react/jsx-runtime";var Ge=(e={})=>{try{let r=h("theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){console.warn("Error parsing theme from cookie:",r)}return e};function Ke({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=Fe(()=>{let s=Ge(r);return Ne(s)},[r]);return _e(Oe,{theme:t,children:[!o&&Ve(De,{}),e]})}import{Navigate as $e,useLocation as Ye}from"react-router-dom";import{Fragment as qe,jsx as C,jsxs as b}from"react/jsx-runtime";var Be={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},He=()=>C("style",{children:`
2
2
  @keyframes spin {
3
3
  0% { transform: rotate(0deg); }
4
4
  100% { transform: rotate(360deg); }
5
5
  }
6
- `});function S({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return b(He,{children:[P(Be,{}),b("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:[P("div",{style:_e}),P("p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:t})]})]})}var qe=/^[a-zA-Z0-9\-_./\?=&%#]+$/,We=[/^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]/,/\\/],C=(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return console.warn("\u{1F6A8} Open redirect blocked (relative path):",e),r;if(!qe.test(o))return console.warn("\u{1F6A8} Open redirect blocked (invalid characters):",e),r;let t=o.toLowerCase();for(let a of We)if(a.test(t))return console.warn("\u{1F6A8} Open redirect blocked (dangerous pattern):",e),r;let s=o.split("?")[0].split("/").filter(Boolean);if(s.length===0)return o;for(let a of s)if(a===".."||a.includes(":")||a.length>100)return console.warn("\u{1F6A8} Open redirect blocked (suspicious path part):",a),r;return o},v=(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let s=decodeURIComponent(t);return C(s,r)}catch(o){return console.warn("\u{1F6A8} Error parsing redirect parameter:",o),r}};import{Fragment as L,jsx as I}from"react/jsx-runtime";function U({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:s,isInitialized:a,tokens:p,error:g}=f(),l=$e();if(!a||s)return I(L,{children:r||I(S,{stage:"validating-session"})});let d=t&&p?.accessToken&&p.accessToken.length>0;if(g||!t||!d){p&&(!p.accessToken||p.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let y=l.pathname+l.search,A=C(y),x=encodeURIComponent(A);return I(Je,{to:`${o}?redirect=${x}`,replace:!0})}return I(L,{children:e})}import{Navigate as Ye,useLocation as Ze}from"react-router-dom";import{Fragment as Qe,jsx as k}from"react/jsx-runtime";function w({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=f(),t=Ze();if(o){let s=new URLSearchParams(t.search),a=v(s,r);return k(Ye,{to:a,replace:!0})}return k(Qe,{children:e})}import{createContext as Xe,useContext as je,useEffect as er,useRef as O,useState as T}from"react";import{Fragment as tr,jsx as F}from"react/jsx-runtime";var N=Xe(void 0),rr=({config:e,children:r,fallback:o=null,onInitialized:t,onError:s})=>{let[a,p]=T(!1),[g,l]=T(!1),[d,y]=T(null),A=O(!1),x=O(!1);er(()=>{A.current||(R.registerHighPriorityInitializer(),A.current=!0),x.current||(x.current=!0,(async()=>{l(!0),y(null);try{let c=E({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:e?.enableLogging});if(!c.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");await R.initialize({priority:"HIGH",publicApiKey:c.publicApiKey,env:c.env||"prod",enableLogging:e?.enableLogging,requestedBy:"CrudifyInitializer"}),p(!0),l(!1),t&&t()}catch(c){let z=c instanceof Error?c:new Error(String(c));y(z),l(!1),s&&s(z)}})())},[e?.publicApiKey,e?.env,e?.enableLogging,t,s]);let G={isInitialized:a,isInitializing:g,error:d};return g&&o?F(tr,{children:o}):(d&&console.error("[CrudifyInitializer] Initialization failed:",d),F(N.Provider,{value:G,children:r}))},or=()=>{let e=je(N);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};import i from"@nocios/crudify-admin";var D=!1,m=null;async function ir(){let r=u.getInstance().getTokenInfo(),o=r?.apiEndpointAdmin,t=r?.apiKeyEndpointAdmin;return o&&t?{apiUrl:o,apiKey:t}:M.waitForCredentials()}async function nr(){if(!D)return m||(m=(async()=>{try{let e=u.getInstance(),{apiUrl:r,apiKey:o}=await ir();i.init({url:r,apiKey:o,getAdditionalHeaders:()=>{let t=e.getTokenInfo();return t?.crudifyTokens?.accessToken?{Authorization:`Bearer ${t.crudifyTokens.accessToken}`}:{}}}),D=!0}catch(e){throw m=null,console.error("[crudifyAdminWrapper] Initialization failed:",e),e}})(),m)}async function n(e){try{await nr();let r=await e();return!r.success&&r.errors?.includes("401")?await u.getInstance().refreshTokens()?await e():(console.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),r):r}catch(r){return console.error("[crudifyAdmin] Operation error:",r),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var sr={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{w as AuthRoute,K as CRITICAL_TRANSLATIONS,Se as CrudiaAutoGenerate,ze as CrudiaFileField,ve as CrudifyInitializationManager,rr as CrudifyInitializer,ge as CrudifyLogin,J as CrudifyProvider,Ge as CrudifyThemeProvider,pe as ERROR_CODES,ce as ERROR_SEVERITY_MAP,ie as GlobalNotificationProvider,Ce as LoginComponent,xe as POLICY_ACTIONS,Re as PREFERRED_POLICY_ORDER,Pe as Policies,U as ProtectedRoute,ae as SessionDebugInfo,S as SessionLoadingScreen,u as SessionManager,se as SessionProvider,Ie as SessionStatus,Y as TokenStorage,B as TranslationService,q as TranslationsProvider,Ae as UserProfileDisplay,j as createErrorTranslator,qr as crudify,sr as crudifyAdmin,R as crudifyInitManager,re as decodeJwtSafely,v as extractSafeRedirectFromUrl,h as getCookie,V as getCriticalLanguages,_ as getCriticalTranslations,oe as getCurrentUserEmail,ue as getErrorMessage,me as handleCrudifyError,te as isTokenExpired,le as parseApiError,fe as parseJavaScriptError,de as parseTransactionError,Ue as secureLocalStorage,Le as secureSessionStorage,X as translateError,Z as translateErrorCode,Q as translateErrorCodes,H as translationService,Me as useAuth,he as useAutoGenerate,$ as useCrudify,or as useCrudifyInitializer,ke as useCrudifyWithNotifications,be as useData,Te as useFileUpload,ne as useGlobalNotification,ee as useSession,f as useSessionContext,W as useTranslations,Ee as useUserData,ye as useUserProfile,C as validateInternalRedirect};
6
+ `});function S({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return b(qe,{children:[C(He,{}),b("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:[C("div",{style:Be}),C("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]/,/\\/],P=(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return console.warn("\u{1F6A8} Open redirect blocked (relative path):",e),r;if(!We.test(o))return console.warn("\u{1F6A8} Open redirect blocked (invalid characters):",e),r;let t=o.toLowerCase();for(let a of Je)if(a.test(t))return console.warn("\u{1F6A8} Open redirect blocked (dangerous pattern):",e),r;let s=o.split("?")[0].split("/").filter(Boolean);if(s.length===0)return o;for(let a of s)if(a===".."||a.includes(":")||a.length>100)return console.warn("\u{1F6A8} Open redirect blocked (suspicious path part):",a),r;return o},v=(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let s=decodeURIComponent(t);return P(s,r)}catch(o){return console.warn("\u{1F6A8} Error parsing redirect parameter:",o),r}};import{Fragment as L,jsx as I}from"react/jsx-runtime";function U({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:s,isInitialized:a,tokens:p,error:g}=f(),d=Ye();if(!a||s)return I(L,{children:r||I(S,{stage:"validating-session"})});let l=t&&p?.accessToken&&p.accessToken.length>0;if(g||!t||!l){p&&(!p.accessToken||p.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let y=d.pathname+d.search,A=P(y),x=encodeURIComponent(A);return I($e,{to:`${o}?redirect=${x}`,replace:!0})}return I(L,{children:e})}import{Navigate as Ze,useLocation as Qe}from"react-router-dom";import{Fragment as Xe,jsx as k}from"react/jsx-runtime";function w({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=f(),t=Qe();if(o){let s=new URLSearchParams(t.search),a=v(s,r);return k(Ze,{to:a,replace:!0})}return k(Xe,{children:e})}import{createContext as je,useContext as er,useEffect as rr,useRef as F,useState as T}from"react";import{Fragment as ir,jsx as O}from"react/jsx-runtime";var N=je(void 0),or=({config:e,children:r,fallback:o=null,onInitialized:t,onError:s})=>{let[a,p]=T(!1),[g,d]=T(!1),[l,y]=T(null),A=F(!1),x=F(!1);rr(()=>{A.current||(R.registerHighPriorityInitializer(),A.current=!0),x.current||(x.current=!0,(async()=>{d(!0),y(null);try{let c=z({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:e?.enableLogging});if(!c.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");await R.initialize({priority:"HIGH",publicApiKey:c.publicApiKey,env:c.env||"prod",enableLogging:e?.enableLogging,requestedBy:"CrudifyInitializer"}),p(!0),d(!1),t&&t()}catch(c){let M=c instanceof Error?c:new Error(String(c));y(M),d(!1),s&&s(M)}})())},[e?.publicApiKey,e?.env,e?.enableLogging,t,s]);let G={isInitialized:a,isInitializing:g,error:l};return g&&o?O(ir,{children:o}):(l&&console.error("[CrudifyInitializer] Initialization failed:",l),O(N.Provider,{value:G,children:r}))},tr=()=>{let e=er(N);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};import i from"@nocios/crudify-admin";var D=!1,m=null;async function nr(){let r=u.getInstance().getTokenInfo(),o=r?.apiEndpointAdmin,t=r?.apiKeyEndpointAdmin;return o&&t?{apiUrl:o,apiKey:t}:E.waitForCredentials()}async function sr(){if(!D)return m||(m=(async()=>{try{let e=u.getInstance(),{apiUrl:r,apiKey:o}=await nr();i.init({url:r,apiKey:o,getAdditionalHeaders:()=>{let t=e.getTokenInfo();return t?.crudifyTokens?.accessToken?{Authorization:`Bearer ${t.crudifyTokens.accessToken}`}:{}}}),D=!0}catch(e){throw m=null,console.error("[crudifyAdminWrapper] Initialization failed:",e),e}})(),m)}async function n(e){try{await sr();let r=await e();return!r.success&&r.errors?.includes("401")?await u.getInstance().refreshTokens()?await e():(console.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),r):r}catch(r){return console.error("[crudifyAdmin] Operation error:",r),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var ar={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{w as AuthRoute,K as CRITICAL_TRANSLATIONS,Se as CrudiaAutoGenerate,Me as CrudiaFileField,ze as CrudiaMarkdownField,ve as CrudifyInitializationManager,or as CrudifyInitializer,ge as CrudifyLogin,J as CrudifyProvider,Ke as CrudifyThemeProvider,pe as ERROR_CODES,ce as ERROR_SEVERITY_MAP,ie as GlobalNotificationProvider,Pe as LoginComponent,xe as POLICY_ACTIONS,Re as PREFERRED_POLICY_ORDER,Ce as Policies,U as ProtectedRoute,ae as SessionDebugInfo,S as SessionLoadingScreen,u as SessionManager,se as SessionProvider,Ie as SessionStatus,Y as TokenStorage,B as TranslationService,q as TranslationsProvider,Ae as UserProfileDisplay,j as createErrorTranslator,Wr as crudify,ar as crudifyAdmin,R as crudifyInitManager,re as decodeJwtSafely,v as extractSafeRedirectFromUrl,h as getCookie,V as getCriticalLanguages,_ as getCriticalTranslations,oe as getCurrentUserEmail,ue as getErrorMessage,me as handleCrudifyError,te as isTokenExpired,de as parseApiError,fe as parseJavaScriptError,le as parseTransactionError,ke as secureLocalStorage,Ue as secureSessionStorage,X as translateError,Z as translateErrorCode,Q as translateErrorCodes,H as translationService,be as useAuth,he as useAutoGenerate,$ as useCrudify,tr as useCrudifyInitializer,we as useCrudifyWithNotifications,Le as useData,Te as useFileUpload,ne as useGlobalNotification,ee as useSession,f as useSessionContext,W as useTranslations,Ee as useUserData,ye as useUserProfile,P as validateInternalRedirect};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nocios/crudify-ui",
3
- "version": "4.4.52",
3
+ "version": "4.4.56",
4
4
  "description": "Biblioteca de componentes UI para Crudify",
5
5
  "author": "Nocios",
6
6
  "license": "MIT",
@@ -39,6 +39,7 @@
39
39
  "prepublishOnly": "npm run build"
40
40
  },
41
41
  "dependencies": {
42
+ "@mdxeditor/editor": "^3.52.0",
42
43
  "@nocios/crudify-admin": "^2.2.0",
43
44
  "@nocios/crudify-browser": "^4.1.12",
44
45
  "crypto-js": "^4.2.0",
@@ -1 +0,0 @@
1
- import{b as se,d as he,h as K,i as me,j as Ee,k as Te}from"./chunk-6GPSBDW6.mjs";import{createContext as He,useContext as Me,useEffect as Ge,useState as X}from"react";import Y from"@nocios/crudify-browser";var ae=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){console.error("[CredentialsEventBus] Error in listener:",t)}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},Z=ae.getInstance();import{jsx as $e}from"react/jsx-runtime";var ve=He(void 0),Ae=({config:r,children:i})=>{let[e,t]=X(!0),[n,s]=X(null),[d,h]=X(!1),[S,I]=X(""),[m,c]=X();Ge(()=>{if(!r.publicApiKey){s("No publicApiKey provided"),t(!1),h(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===S&&d){t(!1);return}(async()=>{t(!0),s(null),h(!1);try{Y.config(r.env||"prod");let p=await Y.init(r.publicApiKey,"none");if(c(p),typeof Y.transaction=="function"&&typeof Y.login=="function")h(!0),I(l),p.apiEndpointAdmin&&p.apiKeyEndpointAdmin&&Z.notifyCredentialsReady({apiUrl:p.apiEndpointAdmin,apiKey:p.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(p){let E=p instanceof Error?p.message:"Failed to initialize Crudify";console.error("[CrudifyProvider] Initialization error:",p),s(E),h(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,S,d]);let a={crudify:d?Y:null,isLoading:e,error:n,isInitialized:d,adminCredentials:m};return $e(ve.Provider,{value:a,children:i})},Ie=()=>{let r=Me(ve);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import W 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 W.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 console.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]:(console.warn(`Crudify: ${f.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=f.getEncryptionKey();return W.AES.encrypt(i,e).toString()}catch(e){return console.error("Crudify: Encryption failed",e),i}}static decrypt(i){try{let e=f.getEncryptionKey();return W.AES.decrypt(i,e).toString(W.enc.Utf8)||i}catch(e){return console.error("Crudify: Decryption failed",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()},n=f.encrypt(JSON.stringify(t));e.setItem(f.TOKEN_KEY,n),console.debug("Crudify: Tokens saved successfully")}catch(t){console.error("Crudify: Failed to save tokens",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),n=JSON.parse(t);return!n.accessToken||!n.refreshToken||!n.expiresAt||!n.refreshExpiresAt?(console.warn("Crudify: Incomplete token data found, clearing storage"),f.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(console.info("Crudify: Refresh token expired, clearing storage"),f.clearTokens(),null):{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,refreshExpiresAt:n.refreshExpiresAt}}catch(e){return console.error("Crudify: Failed to retrieve tokens",e),f.clearTokens(),null}}static clearTokens(){let i=f.getStorage();if(i)try{i.removeItem(f.TOKEN_KEY),console.debug("Crudify: Tokens cleared from storage")}catch(e){console.error("Crudify: Failed to clear tokens",e)}}static rotateEncryptionKey(){try{f.clearTokens(),f.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(f.ENCRYPTION_KEY_STORAGE),console.info("Crudify: Encryption key rotated successfully")}catch(i){console.error("Crudify: Failed to rotate encryption key",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){console.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){console.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){console.debug("Crudify: Tokens updated in another tab");let n=f.getTokens();i(n)}}};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 A=f;import R 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},A.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),R.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),K.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=A.getTokens();e?A.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):A.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 R.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let n=A.getTokens(),s={accessToken:t.data.token,refreshToken:t.data.refreshToken,expiresAt:t.data.expiresAt,refreshExpiresAt:t.data.refreshExpiresAt,apiEndpointAdmin:n?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:n?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return A.saveTokens(s),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(s),{success:!0,tokens:s,data:t.data}}catch(t){return console.error("[SessionManager] Login error:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await R.logout(),A.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),A.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=A.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"),A.clearTokens(),!1;if(R.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),R.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 n=A.getTokens();return n&&this.config.onSessionRestored?.(n),!0}return A.clearTokens(),await R.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),A.clearTokens(),await R.logout(),!1}}isAuthenticated(){return R.isLogin()||A.hasValidTokens()}getTokenInfo(){let i=R.getTokenData(),e=A.getExpirationInfo(),t=A.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:A.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 R.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),A.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e={accessToken:i.data.token,refreshToken:i.data.refreshToken,expiresAt:i.data.expiresAt,refreshExpiresAt:i.data.refreshExpiresAt};return A.saveTokens(e),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),A.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){R.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"),K.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(A.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),K.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"),K.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=R.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";R.config(e);let t=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await R.init(t,n);if(s&&s.success===!1&&s.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw console.error("[SessionManager] Failed to initialize crudify:",i),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(n=>n.errorType==="Unauthorized"||n.message?.includes("Unauthorized")||n.message?.includes("Not Authorized")||n.message?.includes("NOT_AUTHORIZED")||n.message?.includes("Token")||n.message?.includes("TOKEN")||n.message?.includes("Authentication")||n.message?.includes("UNAUTHENTICATED")||n.extensions?.code==="UNAUTHENTICATED"||n.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 n=Object.values(i.errors).flat().find(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.includes("INVALID_TOKEN")));n&&typeof n=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,n.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."):n.includes("TOKEN_HAS_EXPIRED")||n.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.status){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&i.data?.response?.data)try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch{}if(!e.isAuthError&&i.errorCode){let t=i.errorCode.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let i=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){A.clearTokens(),R.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?he("SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().join(", "):"Authentication failed":"Unknown error"}};import{useState as _e,useEffect as J,useCallback as $}from"react";function be(r={}){let[i,e]=_e({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=q.getInstance(),n=$(async()=>{console.log("\u{1F535} [useSession] initialize() CALLED"),console.log("\u{1F50D} [useSession] options received:",{autoRestore:r.autoRestore,enableLogging:r.enableLogging,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin});try{e(o=>({...o,isLoading:!0,error:null}));let c={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(o=>({...o,isAuthenticated:!1,tokens:null,error:"Session expired"})),r.onSessionExpired?.()},onSessionRestored:o=>{e(p=>({...p,isAuthenticated:!0,tokens:o,error:null})),r.onSessionRestored?.(o)},onLoginSuccess:o=>{e(p=>({...p,isAuthenticated:!0,tokens:o,error:null}))},onLogout:()=>{e(o=>({...o,isAuthenticated:!1,tokens:null,error:null}))}};console.log("\u{1F50D} [useSession] Calling sessionManager.initialize() with config:",c),await t.initialize(c),console.log("\u2705 [useSession] sessionManager.initialize() completed"),t.setupResponseInterceptor();let a=t.isAuthenticated(),l=t.getTokenInfo();console.log("\u{1F50D} [useSession] After initialize, isAuth:",a),console.log("\u{1F50D} [useSession] After initialize, tokenInfo:",l),e(o=>({...o,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(c){let a=c instanceof Error?c.message:"Initialization failed";e(l=>({...l,isLoading:!1,isInitialized:!0,error:a}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),s=$(async(c,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(c,a);return l.success&&l.tokens?e(o=>({...o,isAuthenticated:!0,tokens:l.tokens,isLoading:!1,error:null})):e(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),l}catch(l){let o=l instanceof Error?l.message:"Login failed",p=o.includes("INVALID_CREDENTIALS")||o.includes("Invalid email")||o.includes("Invalid password")||o.includes("credentials");return e(E=>({...E,isAuthenticated:!1,tokens:null,isLoading:!1,error:p?null:o})),{success:!1,error:o}}},[t]),d=$(async()=>{e(c=>({...c,isLoading:!0}));try{await t.logout(),e(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[t]),h=$(async()=>{try{let c=await t.refreshTokens();if(c){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 c}catch(c){return e(a=>({...a,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[t]),S=$(()=>{e(c=>({...c,error:null}))},[]),I=$(()=>t.getTokenInfo(),[t]);J(()=>{n()},[n]),J(()=>{if(!i.isAuthenticated||!i.tokens)return;let c=me.getInstance(),a=()=>{t.updateLastActivity(),r.enableLogging&&console.log("\u{1F4CD} User navigating - activity updated")},l=c.subscribe(a);window.addEventListener("popstate",a);let o=()=>{let C=t.getTokenInfo().crudifyTokens.expiresIn||0;return C<300*1e3?30*1e3:C<1800*1e3?60*1e3:120*1e3},p,E=()=>{let k=o();p=setTimeout(async()=>{if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh in progress, rescheduling check"),E();return}let C=t.getTokenInfo(),b=C.crudifyTokens.expiresIn||0,z=(C.crudifyTokens.expiresAt||0)-(Date.now()-b),v=z*.5;if(b>0&&b<=v){let B=Math.round(b/z*100);if(r.enableLogging&&console.log(`\u{1F504} Token at ${B}% of TTL (${Math.round(b/6e4)}min remaining), refreshing...`),e(F=>({...F,isLoading:!0})),await t.refreshTokens()){let F=t.getTokenInfo();e(ne=>({...ne,isLoading:!1,tokens:F.crudifyTokens.accessToken?{accessToken:F.crudifyTokens.accessToken,refreshToken:F.crudifyTokens.refreshToken,expiresAt:F.crudifyTokens.expiresAt,refreshExpiresAt:F.crudifyTokens.refreshExpiresAt}:null}))}else e(F=>({...F,isLoading:!1,isAuthenticated:!1,tokens:null}))}let V=t.getTimeSinceLastActivity(),H=1800*1e3;V>H?(r.enableLogging&&console.log("\u23F1\uFE0F Inactivity timeout (30min) - logging out"),await d()):E()},k)};return E(),()=>{clearTimeout(p),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,d]),J(()=>{let c=K.subscribe(async a=>{if(r.enableLogging&&console.log(`\u{1F4E2} useSession: Received auth event: ${a.type}`),a.type==="TOKEN_EXPIRED"){if(t.isRefreshing()){r.enableLogging&&console.log("\u23F8\uFE0F Refresh already in progress, skipping TOKEN_EXPIRED handler");return}r.enableLogging&&console.log("\u{1F504} Token expired, attempting refresh..."),e(l=>({...l,isLoading:!0}));try{if(await t.refreshTokens()){r.enableLogging&&console.log("\u2705 Token refreshed successfully");let o=t.getTokenInfo();e(p=>({...p,isLoading:!1,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null}))}else r.enableLogging&&console.log("\u274C Token refresh failed, session expired"),K.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){r.enableLogging&&console.error("\u274C Error during token refresh:",l),K.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")&&(r.enableLogging&&console.log(`\u{1F534} Session expired (${a.type}), logging out...`),e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:a.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>c()},[r.enableLogging,r.onSessionExpired,t]),J(()=>{let c=A.subscribeToChanges(a=>{a?(r.enableLogging&&console.log("\u{1F504} Tokens updated in another tab"),e(l=>({...l,tokens:a,isAuthenticated:!0}))):(r.enableLogging&&console.log("\u{1F504} Logout detected in another tab"),e(l=>({...l,isAuthenticated:!1,tokens:null})),K.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>c()},[r.enableLogging]);let m=$(()=>{t.updateLastActivity()},[t]);return{...i,login:s,logout:d,refreshTokens:h,clearError:S,getTokenInfo:I,updateActivity:m,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 ke,createContext as Ve,useContext as Be,useCallback as j,useEffect as Xe}from"react";import{Snackbar as Ye,Alert as Ze,Box as We,Portal as qe}from"@mui/material";import{v4 as Je}from"uuid";import je from"dompurify";import{jsx as _,jsxs as ii}from"react/jsx-runtime";var xe=Ve(null),Qe=r=>je.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}),le=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[d,h]=ke([]),S=j((a,l="info",o)=>{if(!n)return"";if(!a||typeof a!="string")return console.warn("\u26A0\uFE0F GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(console.warn("\u26A0\uFE0F GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let p=Je(),E={id:p,message:a,severity:l,autoHideDuration:o?.autoHideDuration??e,persistent:o?.persistent??!1,allowHtml:o?.allowHtml??s};return h(k=>[...k.length>=i?k.slice(-(i-1)):k,E]),p},[i,e,n,s]),I=j(a=>{h(l=>l.filter(o=>o.id!==a))},[]),m=j(()=>{h([])},[]),c={showNotification:S,hideNotification:I,clearAllNotifications:m};return ii(xe.Provider,{value:c,children:[r,n&&_(qe,{children:_(We,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:d.map(a=>_(ei,{notification:a,onClose:()=>I(a.id)},a.id))})})]})},ei=({notification:r,onClose:i})=>{let[e,t]=ke(!0),n=j((s,d)=>{d!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return Xe(()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,n]),_(Ye,{open:e,onClose:n,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_(Ze,{variant:"filled",severity:r.severity,onClose:n,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_("span",{dangerouslySetInnerHTML:{__html:Qe(r.message)}}):_("span",{children:r.message})})})},Se=()=>{let r=Be(xe);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import ti,{createContext as ri,useContext as ni,useMemo as ce}from"react";import{Fragment as si,jsx as w,jsxs as U}from"react/jsx-runtime";var Ne=ri(void 0);function Pe({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:n={}}){let s;try{let{showNotification:o}=Se();s=o}catch{}let d={};try{let o=Ie();o.isInitialized&&o.adminCredentials&&(d=o.adminCredentials)}catch{}let h=ce(()=>{let o=se({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:i?.enableLogging});return{publicApiKey:o.publicApiKey,env:o.env||"prod"}},[e,i?.enableLogging]),S=ti.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:d.apiEndpointAdmin,apiKeyEndpointAdmin:d.apiKeyEndpointAdmin,publicApiKey:h.publicApiKey,env:h.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,s,d.apiEndpointAdmin,d.apiKeyEndpointAdmin,h]),I=be(S),m=ce(()=>{let o=se({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:i?.enableLogging});return{publicApiKey:o.publicApiKey,env:o.env,appName:o.appName,loginActions:o.loginActions,logo:o.logo}},[e,i?.enableLogging]),c=ce(()=>{if(!I.tokens?.accessToken||!I.isAuthenticated)return null;try{let o=Ee(I.tokens.accessToken);if(o&&o.sub&&o.email&&o.subscriber){let p={_id:o.sub,email:o.email,subscriberKey:o.subscriber};return Object.keys(o).forEach(E=>{["sub","email","subscriber"].includes(E)||(p[E]=o[E])}),p}}catch(o){console.error("Error decoding JWT token for sessionData:",o)}return null},[I.tokens?.accessToken,I.isAuthenticated]),a={...I,sessionData:c,config:m},l={enabled:t,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return w(Ne.Provider,{value:a,children:r})}function et(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?w(Ae,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:w(le,{...i,children:w(Pe,{...r})})}):w(le,{...i,children:w(Pe,{...r})})}function oi(){let r=ni(Ne);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function it(){let r=oi();return r.isInitialized?U("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[w("h4",{children:"Session Debug Info"}),U("div",{children:[w("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),U("div",{children:[w("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),U("div",{children:[w("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&U(si,{children:[U("div",{children:[w("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),U("div",{children:[w("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),U("div",{children:[w("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),U("div",{children:[w("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),U("div",{children:[w("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):w("div",{children:"Session not initialized"})}import{useState as Q,useEffect as we,useCallback as Re,useRef as ee}from"react";import ai from"@nocios/crudify-browser";var at=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[n,s]=Q(null),[d,h]=Q(!1),[S,I]=Q(null),[m,c]=Q({}),a=ee(null),l=ee(!0),o=ee(0),p=ee(0),E=Re(()=>{s(null),I(null),h(!1),c({})},[]),k=Re(async()=>{let C=Te();if(!C){l.current&&(I("No user email available"),h(!1));return}a.current&&a.current.abort();let b=new AbortController;a.current=b;let P=++o.current;try{l.current&&(h(!0),I(null));let z=await ai.readItems("users",{filter:{email:C},pagination:{limit:1}});if(P===o.current&&l.current&&!b.signal.aborted)if(z.success&&z.data&&z.data.length>0){let v=z.data[0];s(v);let V={fullProfile:v,totalFields:Object.keys(v).length,displayData:{id:v.id,email:v.email,username:v.username,firstName:v.firstName,lastName:v.lastName,fullName:v.fullName||`${v.firstName||""} ${v.lastName||""}`.trim(),role:v.role,permissions:v.permissions||[],isActive:v.isActive,lastLogin:v.lastLogin,createdAt:v.createdAt,updatedAt:v.updatedAt,...Object.keys(v).filter(H=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(H)).reduce((H,B)=>({...H,[B]:v[B]}),{})}};c(V),I(null),p.current=0}else I("User profile not found"),s(null),c({})}catch(z){if(P===o.current&&l.current){let v=z;if(v.name==="AbortError")return;e&&p.current<t&&(v.message?.includes("Network Error")||v.message?.includes("Failed to fetch"))?(p.current++,setTimeout(()=>{l.current&&k()},1e3*p.current)):(I("Failed to load user profile"),s(null),c({}))}}finally{P===o.current&&l.current&&h(!1),a.current===b&&(a.current=null)}},[e,t]);return we(()=>{i&&k()},[i,k]),we(()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:n,loading:d,error:S,extendedData:m,refreshProfile:k,clearProfile:E}};import{useState as ue,useEffect as li,useCallback as ie,useRef as ci}from"react";import ui from"@nocios/crudify-browser";var dt=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:n}=i,{prefix:s,padding:d=0,separator:h=""}=r,[S,I]=ue(""),[m,c]=ue(!1),[a,l]=ue(null),o=ci(!1),p=ie(b=>{let P=String(b).padStart(d,"0");return`${s}${h}${P}`},[s,d,h]),E=ie(async()=>{c(!0),l(null);try{let b=await ui.getNextSequence(s);if(b.success&&b.data?.value){let P=p(b.data.value);I(P),t?.(P)}else{let P=b.errors?._error?.[0]||"Failed to generate code";l(P),n?.(P)}}catch(b){let P=b instanceof Error?b.message:"Unknown error";l(P),n?.(P)}finally{c(!1)}},[s,p,t,n]),k=ie(async()=>{await E()},[E]),C=ie(()=>{l(null)},[]);return li(()=>{e&&!S&&!o.current&&(o.current=!0,E())},[e,S,E]),{value:S,loading:m,error:a,regenerate:k,clearError:C}};import de from"@nocios/crudify-browser";var fe=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:n,enableLogging:s,requestedBy:d}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&console.warn(`[CrudifyInitialization] ${d} attempted to initialize with different key. Already initialized with key: ${this.state.publicApiKey?.slice(0,10)}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&console.log(`[CrudifyInitialization] ${d} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&console.log(`[CrudifyInitialization] ${d} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(d),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(d),this.getState().status==="INITIALIZED"){s&&console.log(`[CrudifyInitialization] ${d} found initialization completed by HIGH priority`);return}s&&console.warn(`[CrudifyInitialization] ${d} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(console.warn(`[CrudifyInitialization] HIGH priority request from ${d} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&console.log(`[CrudifyInitialization] ${d} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=d,this.initializationPromise=this.performInitialization(t,n,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=n,this.state.error=null,s&&console.log(`[CrudifyInitialization] \u2705 Successfully initialized by ${d} (${e} priority)`)}catch(h){throw this.state.status="ERROR",this.state.error=h instanceof Error?h:new Error(String(h)),this.initializationPromise=null,console.error(`[CrudifyInitialization] \u274C Initialization failed for ${d}:`,h),h}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let n=0,s=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),i&&console.log(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let n=de.getTokenData();if(n&&n.endpoint){t&&console.log("[CrudifyInitialization] SDK already initialized externally");return}de.config(e);let s=t?"debug":"none",d=await de.init(i,s);if(d.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(d.errors||"Unknown error")}`);d.apiEndpointAdmin&&d.apiKeyEndpointAdmin&&Z.notifyCredentialsReady({apiUrl:d.apiEndpointAdmin,apiKey:d.apiKeyEndpointAdmin})}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},te=fe.getInstance();import{useState as Ce,useCallback as D,useRef as di,useMemo as re}from"react";import ge from"@nocios/crudify-browser";var Le=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,fi=r=>{let i=r.lastIndexOf("."),e=i>0?r.substring(i):"",t=Date.now(),n=Math.random().toString(36).substring(2,8);return`${t}_${n}${e}`},Tt=(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:n=0,visibility:s="private",onUploadComplete:d,onUploadError:h,onFileRemoved:S,onFilesChange:I}=r,[m,c]=Ce([]),[a,l]=Ce(!1),o=di(new Map),p=D(()=>{l(!0)},[]),E=D((u,y)=>{c(g=>g.map(T=>T.id===u?{...T,...y}:T))},[]),k=D(u=>{I?.(u)},[I]),C=D(u=>i&&i.length>0&&!i.includes(u.type)?{valid:!1,error:`File type not allowed: ${u.type}`}:u.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),b=D(async(u,y)=>{try{if(!te.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let g=fi(y.name),N=await ge.generateSignedUrl({fileName:g,contentType:y.type,visibility:s});if(!N.success||!N.data)throw new Error("Failed to get upload URL");let{uploadUrl:T,s3Key:x,publicUrl:M}=N.data;if(!T||!x)throw new Error("Incomplete signed URL response");let ye=x.indexOf("/"),Ke=ye>0?x.substring(ye+1):x;E(u.id,{status:"uploading",progress:0}),await new Promise((oe,G)=>{let L=new XMLHttpRequest;L.upload.addEventListener("progress",O=>{if(O.lengthComputable){let Oe=Math.round(O.loaded/O.total*100);E(u.id,{progress:Oe})}}),L.addEventListener("load",()=>{L.status>=200&&L.status<300?oe():G(new Error(`Upload failed with status ${L.status}`))}),L.addEventListener("error",()=>{G(new Error("Network error during upload"))}),L.addEventListener("abort",()=>{G(new Error("Upload cancelled"))}),L.open("PUT",T),L.setRequestHeader("Content-Type",y.type),L.send(y)});let Ue={status:"completed",progress:100,filePath:Ke,visibility:s,publicUrl:s==="public"?M:void 0,file:void 0};c(oe=>{let G=oe.map(O=>O.id===u.id?{...O,...Ue}:O);k(G);let L=G.find(O=>O.id===u.id);return L&&d?.(L),G})}catch(g){let N=g instanceof Error?g.message:"Unknown error";E(u.id,{status:"error",progress:0,errorMessage:N}),c(T=>{let x=T.find(M=>M.id===u.id);return x&&h?.(x,N),T})}},[E,d,h,s]),P=D(async u=>{let y=Array.from(u);if(t!==void 0){let T=m.filter(M=>M.status!=="error").length,x=t-T;if(x<=0){console.warn(`File limit of ${t} already reached`);return}y.length>x&&(y.splice(x),console.warn(`Only ${x} files will be added to not exceed limit`))}let g=[];for(let T of y){let x=C(T),M={id:Le(),name:T.name,size:T.size,contentType:T.type,status:x.valid?"pending":"error",progress:0,createdAt:Date.now(),file:x.valid?T:void 0,errorMessage:x.error};g.push(M)}c(T=>{let x=[...T,...g];return k(x),x});let N=g.filter(T=>T.status==="pending"&&T.file);for(let T of N)if(T.file){let x=b(T,T.file);o.current.set(T.id,x),x.finally(()=>{o.current.delete(T.id)})}},[m,t,C,b,k]),z=D(async u=>{let y=m.find(g=>g.id===u);if(!y)return!1;E(u,{status:"removing"});try{if(y.filePath){if(!te.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");if(!(await ge.disableFile({filePath:y.filePath})).success)throw new Error("Failed to remove file from server")}return c(g=>{let N=g.filter(T=>T.id!==u);return k(N),N}),S?.(y),!0}catch(g){return E(u,{status:y.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error removing file"}),!1}},[m,E,k,S]),v=D(()=>{c([]),k([])},[k]),V=D(async u=>{let y=m.find(N=>N.id===u);if(!y||y.status!=="error"||!y.file){console.warn("Cannot retry: file not found or no original file");return}E(u,{status:"pending",progress:0,errorMessage:void 0});let g=b(y,y.file);o.current.set(u,g),g.finally(()=>{o.current.delete(u)})},[m,E,b]),H=D(async()=>{let u=Array.from(o.current.values());u.length>0&&await Promise.allSettled(u)},[]),B=D(u=>{let y=u.map(g=>{let N=g.filePath.startsWith("public/")?"public":"private";return{id:Le(),name:g.name,size:g.size||0,contentType:g.contentType||"application/octet-stream",status:"completed",progress:100,filePath:g.filePath,visibility:N,createdAt:Date.now()}});c(y),k(y)},[k]),pe=D(async u=>{let y=m.find(g=>g.id===u);if(!y||!y.filePath)return null;if(y.visibility==="public"&&y.publicUrl)return y.publicUrl;try{if(!te.isInitialized())return null;let g=await ge.getFileUrl({filePath:y.filePath,expiresIn:3600});return g.success&&g.data?.url?g.data.url:null}catch{return null}},[m]),F=re(()=>m.some(u=>u.status==="uploading"||u.status==="pending"),[m]),ne=re(()=>m.filter(u=>u.status==="uploading"||u.status==="pending").length,[m]),De=re(()=>m.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[m]),{isValid:ze,validationError:Fe}=re(()=>{let u=m.filter(g=>g.status==="completed").length;return u<n?{isValid:!1,validationError:n===1?"At least one file is required":`At least ${n} files are required`}:t!==void 0&&u>t?{isValid:!1,validationError:`Maximum ${t} files allowed`}:m.some(g=>g.status==="error")?{isValid:!1,validationError:"Some files have errors"}:{isValid:!0,validationError:null}},[m,n,t]);return{files:m,isUploading:F,pendingCount:ne,addFiles:P,removeFile:z,clearFiles:v,retryUpload:V,isValid:ze,validationError:Fe,waitForUploads:H,completedFilePaths:De,initializeFiles:B,isTouched:a,markAsTouched:p,getPreviewUrl:pe}};export{Z as a,Ae as b,Ie as c,A as d,q as e,be as f,le as g,Se as h,et as i,oi as j,it as k,at as l,dt as m,fe as n,te as o,Tt as p};
@@ -1 +0,0 @@
1
- import{b as Pr,c as te,h as vr,j as ue,l as Tr,m as Er,p as Rr}from"./chunk-MU7DIUCZ.mjs";import{g as $}from"./chunk-BJ6PIVZR.mjs";import{a as wr,b as xr,g as Cr}from"./chunk-6GPSBDW6.mjs";var le={es:{"checkCode.codeLabel":"C\xF3digo de Verificaci\xF3n","checkCode.codePlaceholder":"Ingresa el c\xF3digo de 6 d\xEDgitos","checkCode.codeRequired":"El c\xF3digo es obligatorio","checkCode.emailLabel":"Correo Electr\xF3nico","checkCode.emailPlaceholder":"Ingresa tu correo electr\xF3nico","checkCode.emailRequired":"El correo electr\xF3nico es obligatorio","checkCode.instructions":"Ingresa el c\xF3digo de 6 d\xEDgitos que enviamos a tu correo electr\xF3nico.","checkCode.invalidEmail":"Ingresa un correo electr\xF3nico v\xE1lido","checkCode.resendCodeLink":"Reenviar c\xF3digo","checkCode.title":"Verificar C\xF3digo","checkCode.verifyButton":"Verificar C\xF3digo","common.back":"Volver","common.backToLogin":"Volver","error.app.config":"Error de Configuraci\xF3n: {{message}}","error.app.initialization":"Error durante la inicializaci\xF3n final de la aplicaci\xF3n.","error.transaction":"Error en la operaci\xF3n","error.unknown":"Ocurri\xF3 un error desconocido.","errors.DUPLICATE":"El campo <b>{{field}}</b> debe ser \xFAnico.","errors.FOREIGN_KEY_NOT_FOUND":"El campo <b>{{field}}</b> debe referenciar un \xEDtem existente.","errors.INVALID_EMAIL":"El campo <b>{{field}}</b> debe ser un correo electr\xF3nico v\xE1lido.","errors.INVALID_OBJECT_ID":"El campo <b>{{field}}</b> debe ser un valor v\xE1lido.","errors.IN_USE":"El \xEDtem est\xE1 en uso y no puede ser eliminado.","errors.MAX_LENGTH":"El campo <b>{{field}}</b> no debe exceder los <b>{{length}}</b> caracteres.","errors.MIN_LENGTH":"El campo <b>{{field}}</b> debe tener al menos <b>{{length}}</b> caracteres.","errors.MUST_NOT_BE_EMAIL":"El campo <b>{{field}}</b> no debe ser un correo electr\xF3nico.","errors.NO_PERMISSION":"No tienes permiso para realizar esta acci\xF3n.","errors.NO_SPACES":"El campo <b>{{field}}</b> no debe contener espacios.","errors.ONE_OR_MORE_OPERATIONS_FAILED":"Error en la operaci\xF3n","errors.REQUIRED":"El campo <b>{{field}}</b> es obligatorio.","errors.TOKEN_HAS_EXPIRED":"La sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.","errors.TOO_MANY_REQUESTS":"L\xEDmite de solicitudes alcanzado. Por favor intenta m\xE1s tarde.","errors.UNAUTHORIZED":"No est\xE1s autorizado para realizar esta acci\xF3n.","errors.all_password_fields_required":"Todos los campos de contrase\xF1a son obligatorios","errors.auth.INVALID_API_KEY":"Clave de API inv\xE1lida","errors.auth.INVALID_CREDENTIALS":"Usuario y/o contrase\xF1a incorrectos","errors.auth.NO_PERMISSION":"No tienes permisos suficientes","errors.auth.SESSION_EXPIRED":"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.","errors.auth.TOO_MANY_REQUESTS":"Demasiados intentos. Por favor espera 15 minutos e intenta nuevamente","errors.auth.UNAUTHORIZED":"No tienes permisos para realizar esta acci\xF3n","errors.auth.USER_NOT_ACTIVE":"Usuario no activo","errors.auth.USER_NOT_FOUND":"Usuario no encontrado","errors.data.BAD_REQUEST":"Solicitud inv\xE1lida","errors.data.FIELD_ERROR":"Error en los datos ingresados","errors.data.IN_USE":"El elemento est\xE1 en uso y no puede ser eliminado","errors.data.ITEM_NOT_FOUND":"El elemento solicitado no fue encontrado","errors.data.NOT_FOUND":"No se encontr\xF3 lo solicitado","errors.internal_error_changing_password":"Error interno al cambiar la contrase\xF1a. Intenta nuevamente","errors.password_min_length":"La contrase\xF1a debe tener al menos 8 caracteres","errors.password_mismatch":"Las contrase\xF1as no coinciden","errors.password_must_be_different":"La nueva contrase\xF1a debe ser diferente a la actual","errors.system.DATABASE_CONNECTION_ERROR":"Error de conexi\xF3n. Verifica tu conexi\xF3n a internet.","errors.system.INTERNAL_SERVER_ERROR":"Error interno del servidor. Intenta nuevamente.","errors.system.INVALID_CONFIGURATION":"Error de configuraci\xF3n del sistema","errors.system.TOO_MANY_REQUESTS":"Demasiadas solicitudes. Por favor espera un momento e intenta nuevamente","errors.system.UNKNOWN_OPERATION":"Operaci\xF3n no reconocida","errors.users_module_not_configured":"M\xF3dulo de usuarios no configurado","footer.copyright":"Nocios S.R.L. Todos los derechos reservados.","footer.version":"Versi\xF3n","forgotPassword.checkEmailInstructions":"Revisa tu bandeja de entrada para el c\xF3digo de verificaci\xF3n","forgotPassword.codeAlreadyExistsMessage":"Ya se envi\xF3 un c\xF3digo y a\xFAn es v\xE1lido","forgotPassword.emailLabel":"Correo Electr\xF3nico","forgotPassword.emailPlaceholder":"Ingresa tu correo electr\xF3nico","forgotPassword.emailRequired":"El correo electr\xF3nico es obligatorio","forgotPassword.emailSentMessage":"C\xF3digo enviado exitosamente","forgotPassword.enterCodeLink":"Ingresar C\xF3digo","forgotPassword.instructions":"Ingresa tu correo electr\xF3nico y te enviaremos un c\xF3digo para restablecer tu contrase\xF1a.","forgotPassword.invalidEmail":"Ingresa un correo electr\xF3nico v\xE1lido","forgotPassword.sendCodeButton":"Enviar C\xF3digo","forgotPassword.title":"Recuperar Contrase\xF1a","loading.app.configInitial":"Cargando configuraci\xF3n inicial...","loading.app.generic":"Cargando...","loading.app.starting":"Iniciando aplicaci\xF3n...","loading.app.themeSetup":"Generando tema...","loading.app.validatingSession":"Validando sesi\xF3n...","login.alreadyHaveCodeLink":"\xBFYa tienes un c\xF3digo?","login.forgotPasswordLink":"\xBFOlvidaste tu contrase\xF1a?","login.initializationError":"Error de inicializaci\xF3n","login.initializing":"Inicializando...","login.loginButton":"Iniciar Sesi\xF3n","login.logoAlt":"Logotipo","login.noAccountPrompt":"\xBFNo tienes una cuenta?","login.notInitialized":"Sistema no inicializado","login.passwordLabel":"Contrase\xF1a","login.passwordPlaceholder":"Ingresa tu contrase\xF1a","login.passwordRequired":"Contrase\xF1a es obligatoria","login.signUpLink":"Reg\xEDstrate","login.usernameOrEmailLabel":"Correo Electr\xF3nico","login.usernameOrEmailPlaceholder":"Ingresa tu correo electr\xF3nico","login.usernameRequired":"Correo electr\xF3nico es obligatorio","resetPassword.codeExpiredOrInvalid":"El c\xF3digo ha expirado o es inv\xE1lido","resetPassword.confirmPasswordLabel":"Confirmar Contrase\xF1a","resetPassword.confirmPasswordPlaceholder":"Confirma tu nueva contrase\xF1a","resetPassword.confirmPasswordRequired":"Confirma tu contrase\xF1a","resetPassword.goToLoginButton":"Ir al Login","resetPassword.instructions":"Ingresa tu nueva contrase\xF1a.","resetPassword.invalidCode":"El c\xF3digo de verificaci\xF3n es inv\xE1lido. Por favor, verifica el enlace o solicita uno nuevo.","resetPassword.missingParameters":"Faltan par\xE1metros obligatorios","resetPassword.newPasswordLabel":"Nueva Contrase\xF1a","resetPassword.newPasswordPlaceholder":"Ingresa tu nueva contrase\xF1a","resetPassword.newPasswordRequired":"La nueva contrase\xF1a es obligatoria","resetPassword.passwordTooShort":"La contrase\xF1a debe tener al menos 8 caracteres","resetPassword.passwordsDoNotMatch":"Las contrase\xF1as no coinciden","resetPassword.requestNewCodeButton":"Solicitar Nuevo C\xF3digo","resetPassword.resetPasswordButton":"Restablecer Contrase\xF1a","resetPassword.successInstructions":"Ahora puedes iniciar sesi\xF3n con tu nueva contrase\xF1a","resetPassword.successMessage":"Contrase\xF1a restablecida exitosamente","resetPassword.title":"Nueva Contrase\xF1a","resetPassword.validatingCode":"Validando c\xF3digo...","modules.form.publicPolicies.fields.conditions.customEdit":"Edici\xF3n personalizada"},en:{"checkCode.codeLabel":"Verification Code","checkCode.codePlaceholder":"Enter 6-digit code","checkCode.codeRequired":"Code is required","checkCode.emailLabel":"Email Address","checkCode.emailPlaceholder":"Enter your email address","checkCode.emailRequired":"Email address is required","checkCode.instructions":"Enter the 6-digit code we sent to your email address.","checkCode.invalidEmail":"Enter a valid email address","checkCode.resendCodeLink":"Resend code","checkCode.title":"Verify Code","checkCode.verifyButton":"Verify Code","common.back":"Back","common.backToLogin":"Back to Login","error.app.config":"Configuration Error: {{message}}","error.app.initialization":"Error during final application initialization.","error.transaction":"Operation error","error.unknown":"An unknown error occurred.","errors.DUPLICATE":"The field <b>{{field}}</b> must be unique.","errors.FOREIGN_KEY_NOT_FOUND":"The field <b>{{field}}</b> must reference an existing item.","errors.INVALID_EMAIL":"The field <b>{{field}}</b> must be a valid email address.","errors.INVALID_OBJECT_ID":"The field <b>{{field}}</b> must be a valid value.","errors.IN_USE":"The item is currently in use and cannot be deleted.","errors.MAX_LENGTH":"The field <b>{{field}}</b> must not exceed <b>{{maxLength}}</b> characters.","errors.MIN_LENGTH":"The field <b>{{field}}</b> must have at least <b>{{minLength}}</b> characters.","errors.MUST_NOT_BE_EMAIL":"The field <b>{{field}}</b> must not be an email address.","errors.NO_PERMISSION":"You do not have permission to perform this action.","errors.NO_SPACES":"The field <b>{{field}}</b> must not contain spaces.","errors.ONE_OR_MORE_OPERATIONS_FAILED":"Operation error","errors.REQUIRED":"The field <b>{{field}}</b> is required.","errors.TOKEN_HAS_EXPIRED":"Your session has expired, please log in again.","errors.TOO_MANY_REQUESTS":"Request limit reached. Please try again later.","errors.UNAUTHORIZED":"You are not authorized to perform this action.","errors.all_password_fields_required":"All password fields are required","errors.auth.INVALID_API_KEY":"Invalid API key","errors.auth.INVALID_CREDENTIALS":"Incorrect username and/or password","errors.auth.NO_PERMISSION":"Insufficient permissions","errors.auth.SESSION_EXPIRED":"Your session has expired. Please log in again.","errors.auth.TOO_MANY_REQUESTS":"Too many attempts. Please wait 15 minutes and try again","errors.auth.UNAUTHORIZED":"You don't have permission to perform this action","errors.auth.USER_NOT_ACTIVE":"User account is not active","errors.auth.USER_NOT_FOUND":"User not found","errors.data.BAD_REQUEST":"Invalid request","errors.data.FIELD_ERROR":"Error in the provided data","errors.data.IN_USE":"The item is in use and cannot be deleted","errors.data.ITEM_NOT_FOUND":"The requested item was not found","errors.data.NOT_FOUND":"The requested resource was not found","errors.internal_error_changing_password":"Internal error changing password. Please try again","errors.password_min_length":"Password must be at least 8 characters","errors.password_mismatch":"Passwords do not match","errors.password_must_be_different":"New password must be different from current password","errors.system.DATABASE_CONNECTION_ERROR":"Connection error. Please check your internet connection.","errors.system.INTERNAL_SERVER_ERROR":"Internal server error. Please try again.","errors.system.INVALID_CONFIGURATION":"System configuration error","errors.system.TOO_MANY_REQUESTS":"Too many requests. Please wait a moment and try again","errors.system.UNKNOWN_OPERATION":"Unrecognized operation","errors.users_module_not_configured":"Users module not configured","footer.copyright":"Nocios S.R.L. All Rights Reserved.","footer.version":"Version","forgotPassword.checkEmailInstructions":"Check your inbox for the verification code","forgotPassword.codeAlreadyExistsMessage":"A code was already sent and is still valid","forgotPassword.emailLabel":"Email Address","forgotPassword.emailPlaceholder":"Enter your email address","forgotPassword.emailRequired":"Email address is required","forgotPassword.emailSentMessage":"Code sent successfully","forgotPassword.enterCodeLink":"Enter Code","forgotPassword.instructions":"Enter your email address and we'll send you a code to reset your password.","forgotPassword.invalidEmail":"Enter a valid email address","forgotPassword.sendCodeButton":"Send Code","forgotPassword.title":"Reset Password","loading.app.configInitial":"Loading initial configuration...","loading.app.generic":"Loading...","loading.app.starting":"Starting application...","loading.app.themeSetup":"Generating theme...","loading.app.validatingSession":"Validating session...","login.alreadyHaveCodeLink":"Already have a code?","login.forgotPasswordLink":"Forgot Password?","login.initializationError":"Initialization error","login.initializing":"Initializing...","login.loginButton":"Log In","login.logoAlt":"Logo","login.noAccountPrompt":"Don't have an account?","login.notInitialized":"System not initialized","login.passwordLabel":"Password","login.passwordPlaceholder":"Enter your password","login.passwordRequired":"Password is required","login.signUpLink":"Sign up","login.usernameOrEmailLabel":"Username or Email","login.usernameOrEmailPlaceholder":"Enter your username or email","login.usernameRequired":"Username or email is required","resetPassword.codeExpiredOrInvalid":"Code expired or invalid","resetPassword.confirmPasswordLabel":"Confirm Password","resetPassword.confirmPasswordPlaceholder":"Confirm your new password","resetPassword.confirmPasswordRequired":"Confirm your password","resetPassword.goToLoginButton":"Go to Login","resetPassword.instructions":"Enter your new password.","resetPassword.invalidCode":"The verification code is invalid. Please check the link or request a new one.","resetPassword.missingParameters":"Missing required parameters","resetPassword.newPasswordLabel":"New Password","resetPassword.newPasswordPlaceholder":"Enter your new password","resetPassword.newPasswordRequired":"New password is required","resetPassword.passwordTooShort":"Password must be at least 8 characters","resetPassword.passwordsDoNotMatch":"Passwords do not match","resetPassword.requestNewCodeButton":"Request New Code","resetPassword.resetPasswordButton":"Reset Password","resetPassword.successInstructions":"You can now log in with your new password","resetPassword.successMessage":"Password reset successfully","resetPassword.title":"New Password","resetPassword.validatingCode":"Validating code...","modules.form.publicPolicies.fields.conditions.customEdit":"Custom Edit"}},Hn=()=>Object.keys(le),jn=e=>le[e]||le.es;import Me from"@nocios/crudify-browser";var Ir="crudify_translations_",Eo=3600*1e3;function Sr(e){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return Math.abs(r).toString(36)}var Ze=class e{constructor(){this.enableDebug=!1;this.initializationPromise=null;this.isInitialized=!1}static getInstance(){return e.instance||(e.instance=new e),e.instance}setDebug(r){this.enableDebug=r}async ensureCrudifyInitialized(r,o){if(!this.isInitialized)return this.initializationPromise?(this.enableDebug&&console.log("[TranslationService] Waiting for crudify initialization..."),this.initializationPromise):(this.enableDebug&&console.log("[TranslationService] Initializing crudify SDK..."),this.initializationPromise=(async()=>{try{let t=Me.getTokenData();if(t&&t.endpoint){this.enableDebug&&console.log("[TranslationService] Crudify already initialized"),this.isInitialized=!0;return}Me.config(o);let a=await Me.init(r,this.enableDebug?"debug":"none");if(a.success===!1)throw new Error(`Failed to initialize crudify: ${JSON.stringify(a.errors||"Unknown error")}`);this.isInitialized=!0,this.enableDebug&&console.log("[TranslationService] Crudify SDK initialized successfully")}catch(t){throw console.error("[TranslationService] Failed to initialize crudify:",t),this.initializationPromise=null,t}})(),this.initializationPromise)}async fetchTranslations(r){let{apiKey:o,featureKeys:t,crudifyEnv:a="stg",urlTranslations:n}=r;this.enableDebug&&console.log("[TranslationService] fetchTranslations called with:",{apiKeyHash:Sr(o),crudifyEnv:a,featureKeys:t,hasUrlTranslations:!!n});let s=this.getFromCache(o),l=s?this.isCacheExpired(s):!0;if(s&&!l)return this.enableDebug&&console.log("[TranslationService] Using cached translations"),this.mergeWithUrlTranslations(s.data.translations,n);try{await this.ensureCrudifyInitialized(o,a)}catch(d){return console.error("[TranslationService] \u274C Failed to initialize crudify:",d),s?(console.warn("[TranslationService] \u26A0\uFE0F Using expired cache (init failed)"),this.mergeWithUrlTranslations(s.data.translations,n)):(console.warn("[TranslationService] \u26A0\uFE0F Using critical bundle (init failed)"),this.getCriticalTranslationsOnly())}try{this.enableDebug&&console.log("[TranslationService] Fetching from API via crudify SDK");let d=await this.fetchFromAPI(t);this.hasDataChanged(s,d)||!s?this.saveToCache(o,d):this.refreshCacheTimestamp(o);let u=this.mergeWithUrlTranslations(d.translations,n);return this.enableDebug&&console.log("[TranslationService] Translations loaded:",{languages:Object.keys(u),keysCount:u[Object.keys(u)[0]]?Object.keys(u[Object.keys(u)[0]]).length:0}),u}catch(d){return console.error("[TranslationService] \u274C API fetch failed:",d),s?(console.warn("[TranslationService] \u26A0\uFE0F Using expired cache as fallback"),this.mergeWithUrlTranslations(s.data.translations,n)):(console.warn("[TranslationService] \u26A0\uFE0F Using critical bundle translations"),this.getCriticalTranslationsOnly())}}async fetchFromAPI(r){let o=await Me.getTranslation(r);if(!o.success)throw new Error(`Crudify API error: ${o.errors?JSON.stringify(o.errors):"Unknown error"}`);if(!o.data)throw new Error("No translation data in response");return o.data}mergeWithUrlTranslations(r,o){if(!o||Object.keys(o).length===0)return r;let t={};return Object.keys(r).forEach(a=>{t[a]={...r[a],...o}}),t}hasDataChanged(r,o){if(!r||r.data.timestamp!==o.timestamp)return!0;let t=this.hashData(o.translations);return r.dataHash!==t}hashData(r){let o=JSON.stringify(r),t=0;for(let a=0;a<o.length;a++){let n=o.charCodeAt(a);t=(t<<5)-t+n,t=t&t}return t.toString(36)}saveToCache(r,o){try{let t=this.getCacheKey(r),a={data:o,cachedAt:Date.now(),dataHash:this.hashData(o.translations)};localStorage.setItem(t,JSON.stringify(a)),this.enableDebug&&console.log("[TranslationService] Saved to cache:",t)}catch(t){console.error("[TranslationService] Failed to save cache:",t)}}getFromCache(r){try{let o=this.getCacheKey(r),t=localStorage.getItem(o);return t?JSON.parse(t):null}catch(o){return console.error("[TranslationService] Failed to read cache:",o),null}}refreshCacheTimestamp(r){try{let o=this.getFromCache(r);if(o){o.cachedAt=Date.now();let t=this.getCacheKey(r);localStorage.setItem(t,JSON.stringify(o))}}catch(o){console.error("[TranslationService] Failed to refresh cache timestamp:",o)}}isCacheExpired(r){return Date.now()-r.cachedAt>Eo}hasValidCache(r){let o=this.getFromCache(r);return o?!this.isCacheExpired(o):!1}getCacheKey(r){return`${Ir}${Sr(r)}`}getCriticalTranslationsOnly(){return le}invalidateCache(r){let o=this.getCacheKey(r);localStorage.removeItem(o),this.enableDebug&&console.log("[TranslationService] Cache invalidated:",o)}async prefetchTranslations(r){try{await this.fetchTranslations(r),this.enableDebug&&console.log("[TranslationService] Prefetch completed")}catch(o){console.error("[TranslationService] Prefetch failed:",o)}}clearAllCaches(){try{let o=Object.keys(localStorage).filter(t=>t.startsWith(Ir));o.forEach(t=>localStorage.removeItem(t)),this.enableDebug&&console.log(`[TranslationService] Cleared ${o.length} cache entries`)}catch(r){console.error("[TranslationService] Failed to clear caches:",r)}}},Ve=Ze.getInstance();import{createContext as Ro,useContext as Io,useEffect as Ar,useState as Re,useMemo as Lr,useCallback as So}from"react";import{Fragment as ko,jsx as He}from"react/jsx-runtime";var We=null,er=!1,Fr=Ro(null);function kr(e,r,o){return{...e,...r,...o||{}}}function Lo(e,r,o,t,a){Ar(()=>{if(!t||!e||!r)return;let n=o||typeof window<"u"&&window.i18next||typeof window<"u"&&window.i18n;if(!n||!n.addResourceBundle){a&&console.log("[TranslationsProvider] i18next not found, skipping auto-sync");return}a&&console.log("[TranslationsProvider] Auto-syncing translations with i18next",{languages:Object.keys(e),currentLanguage:r}),Object.keys(e).forEach(s=>{e[s]&&Object.keys(e[s]).length>0&&(n.addResourceBundle(s,"translation",e[s],!0,!0),a&&console.log(`[TranslationsProvider] Synced ${Object.keys(e[s]).length} keys for language: ${s}`))}),n.language!==r&&(n.changeLanguage(r),a&&console.log(`[TranslationsProvider] Changed i18next language to: ${r}`))},[e,r,o,t,a])}var es=({children:e,apiKey:r,crudifyEnv:o="prod",featureKeys:t,language:a="es",devTranslations:n,translationUrl:s,enableDebug:l=!1,skipAutoInit:d=!0,autoSyncI18n:w=!0,i18nInstance:u,loadingFallback:h,waitForInitialLoad:g=!0})=>{let i=Lr(()=>xr({publicApiKey:r,env:o,featureKeys:t,enableDebug:l}),[r,o,t,l]),c=i.publicApiKey||"",b=i.env||o||"prod",p=i.featureKeys||t,[y,m]=Re({}),[P,R]=Re(!0),[M,x]=Re(!0),[f,C]=Re(null),[k,_]=Re(void 0),[ie,be]=Re(!1),oe=So(async()=>{if(!c){l&&console.log("[TranslationsProvider] No apiKey - skipping translation fetch"),R(!1),x(!1);return}if(ie){l&&console.log("[TranslationsProvider] Skipping reload - using fallback translations");return}if(Ve.hasValidCache(c)&&M&&(l&&console.log("[TranslationsProvider] Valid cache found - not blocking initial render"),x(!1)),er&&We){l&&console.log("[TranslationsProvider] Fetch already in progress, waiting for existing promise");try{let I=await We;m(I),R(!1);return}catch{l&&console.warn("[TranslationsProvider] Global fetch failed, retrying")}}er=!0,R(!0),C(null);let F;if(s)try{l&&console.log(`[TranslationsProvider] Fetching translations from URL: ${s}`);let I=await fetch(s);if(!I.ok)throw new Error(`Failed to fetch translations: ${I.statusText}`);F=await I.json(),_(F),l&&console.log("[TranslationsProvider] URL translations loaded:",{keysCount:F?Object.keys(F).length:0})}catch(I){console.error("[TranslationsProvider] Failed to load URL translations:",I),F=void 0,_(void 0)}let Te=(async()=>{try{Ve.setDebug(l);let I=await Ve.fetchTranslations({apiKey:c,crudifyEnv:b,featureKeys:p,urlTranslations:F}),H={};return Object.keys(I).forEach(v=>{let S=le[v]||{},O=I[v]||{};H[v]=kr(S,O,n)}),l&&console.log("[TranslationsProvider] Loaded translations:",{languages:Object.keys(H),keysCount:Object.keys(H[a]||{}).length}),H}catch(I){console.error("[TranslationsProvider] Failed to load:",I),C(I.message),be(!0);let H={};return Object.keys(le).forEach(v=>{let S=le[v],O=F||k||{};H[v]=kr(S,O,n)}),l&&console.log("[TranslationsProvider] Using fallback translations (critical + URL)"),H}})();We=Te;try{let I=await Te;m(I)}finally{R(!1),x(!1),er=!1,setTimeout(()=>{We=null},1e3)}},[c,b,p,s,n,l,a,ie]);Ar(()=>{oe();let V=setInterval(oe,3600*1e3);return()=>clearInterval(V)},[oe]);let de=Lr(()=>(V,F)=>{let I=(y[a]||{})[V];if(!I){let H=Object.keys(y);for(let v of H)if(y[v][V]){I=y[v][V];break}}return I||(l&&console.warn(`[TranslationsProvider] Missing translation: "${V}"`),I=V),F&&typeof I=="string"&&Object.entries(F).forEach(([H,v])=>{let S=new RegExp(`{{${H}}}`,"g");I=I.replace(S,String(v))}),I},[y,a,l]);Lo(y,a,u,w,l);let A={t:de,language:a,availableLanguages:Object.keys(y),translations:y,isLoading:P,error:f,refreshTranslations:oe};return c?g&&M&&P?h||He("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:He("div",{children:"Loading translations..."})}):He(Fr.Provider,{value:A,children:e}):(l&&console.warn("[TranslationsProvider] No API key available. Skipping translations. Provide apiKey via props or ensure cookies are set by Lambda."),He(ko,{children:e}))},_r=()=>{let e=Io(Fr);if(!e)throw new Error("useTranslations must be used within TranslationsProvider");return e};import{Box as ft,Typography as yt}from"@mui/material";import{createContext as Fo,useContext as _o,useMemo as or}from"react";import{useState as rr,useEffect as Ao}from"react";var Or=(e,r)=>{let[o,t]=rr({}),[a,n]=rr(!1),[s,l]=rr(null);return Ao(()=>{if(console.log("\u{1F527} [I18nProvider] Hybrid translation loading:",{hasProvidedTranslations:!!r&&Object.keys(r).length>0,hasUrl:!!e,providedKeys:r?Object.keys(r).length:0}),r&&Object.keys(r).length>0){console.log("\u2705 [I18nProvider] Using provided translations (highest priority)"),t(r),n(!1),l(null);return}if(!e){console.log("\u26A0\uFE0F [I18nProvider] No translations provided, using empty object (keys will show as-is)"),t({}),n(!1),l(null);return}console.log("\u{1F310} [I18nProvider] Loading translations from URL:",e);let d=!1;return n(!0),l(null),fetch(e).then(w=>{if(!w.ok)throw new Error(`Failed to load translations: ${w.status}`);return w.json()}).then(w=>{d||(console.log("\u2705 [I18nProvider] Translations loaded successfully from URL:",{url:e,keysLoaded:Object.keys(w).length}),t(w),n(!1))}).catch(w=>{d||(console.error("\u274C [I18nProvider] Failed to load translations from URL:",e,w),l(w.message),console.log("\u{1F504} [I18nProvider] Falling back to empty translations (keys will show as-is)"),t({}),n(!1))}),()=>{d=!0}},[e,r]),{translations:o,loading:a,error:s}};import{jsx as Nr}from"react/jsx-runtime";var Br=Fo(null),Oo=()=>{try{return _r()}catch{return null}},No=(e,r)=>{if(r.includes(".")){let o=r.split(".").reduce((t,a)=>t&&typeof t=="object"?t[a]:void 0,e);if(o!==void 0)return o}if(e&&e[r])return e[r]},Dr=({children:e,translations:r,translationsUrl:o,language:t="en"})=>{let n=Oo()?.translations?.[t]||{},{translations:s,loading:l}=Or(o,r),d=or(()=>({...n,...s,...r||{}}),[n,s,r]),w=or(()=>(h,g)=>{let i=No(d,h);return i==null&&(console.log(`\u{1F50D} [I18nProvider] Translation not found for key: "${h}" - showing key as-is`),i=h),g&&typeof i=="string"&&Object.entries(g).forEach(([c,b])=>{i=i.replace(new RegExp(`{{${c}}}`,"g"),b)}),typeof i=="string"?i:h},[d]),u=or(()=>({t:w,language:t}),[w,t]);return l?Nr("div",{children:"Loading translations..."}):Nr(Br.Provider,{value:u,children:e})},Q=()=>{let e=_o(Br);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};import{createContext as Bo,useContext as Do,useReducer as zo,useEffect as zr}from"react";import{jsx as Mo}from"react/jsx-runtime";var Ur={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function Uo(e,r){switch(r.type){case"SET_SCREEN":let o={...e,currentScreen:r.payload.screen,searchParams:r.payload.params||e.searchParams,errors:{global:[]}},t=new URLSearchParams(o.searchParams),a=t.toString()?`?${t.toString()}`:window.location.pathname;try{window.history.replaceState({},"",a)}catch{}return o;case"SET_SEARCH_PARAMS":return{...e,searchParams:r.payload};case"UPDATE_FORM_DATA":return{...e,formData:{...e.formData,...r.payload},errors:{...e.errors,...Object.keys(r.payload).reduce((n,s)=>({...n,[s]:void 0}),{})}};case"SET_LOADING":return{...e,loading:r.payload};case"SET_ERRORS":return{...e,errors:{...e.errors,...r.payload}};case"CLEAR_ERRORS":return{...e,errors:{global:[]}};case"SET_EMAIL_SENT":return{...e,emailSent:r.payload};case"SET_CODE_ALREADY_EXISTS":return{...e,codeAlreadyExists:r.payload};case"SET_CODE_VALIDATED":return{...e,codeValidated:r.payload};case"SET_FROM_CODE_VERIFICATION":return{...e,fromCodeVerification:r.payload};case"RESET_FORM":return{...e,formData:Ur.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...e,config:r.payload};default:return e}}var Mr=Bo(void 0),Vr=({children:e,initialScreen:r="login",config:o,autoReadFromCookies:t=!0})=>{let[a,n]=zo(Uo,{...Ur,currentScreen:r});zr(()=>{n({type:"INIT_CONFIG",payload:(()=>{let i={};if(t)try{let c=wr("logo");if(c){let b=decodeURIComponent(c);b.startsWith("http")&&(i.logo=b)}}catch(c){console.error("Error reading configuration from cookies:",c)}return{publicApiKey:o?.publicApiKey,env:o?.env,appName:o?.appName,logo:o?.logo||i.logo,loginActions:o?.loginActions}})()})},[o,t]),zr(()=>{let g=new URLSearchParams(window.location.search),i={};g.forEach((c,b)=>{i[b]=c}),Object.keys(i).length>0&&n({type:"SET_SEARCH_PARAMS",payload:i}),r==="checkCode"&&i.email&&n({type:"UPDATE_FORM_DATA",payload:{email:i.email,code:i.code||""}}),r==="resetPassword"&&i.link&&n({type:"SET_SEARCH_PARAMS",payload:i})},[r]);let h={state:a,dispatch:n,setScreen:(g,i)=>{n({type:"SET_SCREEN",payload:{screen:g,params:i}})},updateFormData:g=>{n({type:"UPDATE_FORM_DATA",payload:g})},setFieldError:(g,i)=>{n({type:"SET_ERRORS",payload:{[g]:i}})},clearErrors:()=>{n({type:"CLEAR_ERRORS"})},setLoading:g=>{n({type:"SET_LOADING",payload:g})}};return Mo(Mr.Provider,{value:h,children:e})},je=()=>{let e=Do(Mr);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};import{useEffect as Vo,useRef as Wo}from"react";import{Typography as tr,TextField as Wr,Button as Ho,Box as Fe,CircularProgress as jo,Alert as qo,Link as Hr}from"@mui/material";import{Fragment as Ko,jsx as X,jsxs as _e}from"react/jsx-runtime";var $o=({onScreenChange:e,onExternalNavigate:r,onLoginSuccess:o,onError:t,redirectUrl:a="/"})=>{let{crudify:n}=te(),{state:s,updateFormData:l,setFieldError:d,clearErrors:w,setLoading:u}=je(),{login:h}=ue(),g=Q(),{t:i}=g,c=g.i18n,b=Wo(null),p=Cr(i,{currentLanguage:c?.language,enableDebug:!1}),y=()=>{if(s.searchParams.redirect)try{let f=decodeURIComponent(s.searchParams.redirect);if(f.startsWith("/")&&!f.startsWith("//"))return f}catch{}return a||"/"};Vo(()=>{let f=setTimeout(()=>{b.current&&b.current.focus()},100);return()=>clearTimeout(f)},[]);let m=f=>{console.log("\u{1F50D} [LoginForm] Translating parsed error:",f);let C=p.translateError({code:f.code,message:f.message,field:f.field});return console.log("\u{1F50D} [LoginForm] Translation result:",C),C},P=async()=>{if(!s.loading){if(!s.formData.username.trim()){d("username",i("login.usernameRequired"));return}if(!s.formData.password.trim()){d("password",i("login.passwordRequired"));return}w(),u(!0);try{let f=await h(s.formData.username,s.formData.password);if(u(!1),f.success){console.log("\u{1F510} LoginForm - Login successful via SessionProvider, calling onLoginSuccess");let C=y();o&&o(f.data,C)}else{let C=f.rawResponse||f;R(C)}}catch(f){u(!1);let k=$(f).map(m);d("global",k),t&&t(k.join(", "))}}},R=f=>{let C=$(f),k=[];C.forEach(_=>{_.field?d(_.field,m(_)):k.push(m(_))}),k.length>0&&d("global",k)};return _e(Ko,{children:[_e(Fe,{component:"form",noValidate:!0,onSubmit:f=>{f.preventDefault(),P()},onKeyDown:f=>{f.key==="Enter"&&!s.loading&&(f.preventDefault(),P())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[_e(Fe,{sx:{mb:1},children:[X(tr,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:i("login.usernameOrEmailLabel")}),X(Wr,{fullWidth:!0,id:"email",name:"email",type:"email",value:s.formData.username,disabled:s.loading,onChange:f=>l({username:f.target.value}),error:!!s.errors.username,helperText:s.errors.username,autoComplete:"email",placeholder:i("login.usernameOrEmailPlaceholder"),inputRef:b,required:!0})]}),_e(Fe,{sx:{mb:1},children:[X(tr,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:i("login.passwordLabel")}),X(Wr,{fullWidth:!0,id:"password",name:"password",type:"password",value:s.formData.password,disabled:s.loading,onChange:f=>l({password:f.target.value}),error:!!s.errors.password,helperText:s.errors.password,autoComplete:"current-password",placeholder:i("login.passwordPlaceholder"),required:!0})]}),s.config.loginActions?.includes("forgotPassword")&&X(Fe,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:X(Hr,{sx:{cursor:"pointer"},onClick:()=>{e?.("forgotPassword",s.searchParams)},variant:"body2",color:"secondary",children:i("login.forgotPasswordLink")})}),X(Ho,{disabled:s.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:s.loading?X(jo,{size:20}):i("login.loginButton")})]}),X(Fe,{children:s.errors.global&&s.errors.global.length>0&&s.errors.global.map((f,C)=>X(qo,{variant:"filled",sx:{mt:2},severity:"error",children:X("div",{children:f})},C))}),s.config.loginActions?.includes("createUser")&&_e(tr,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[i("login.noAccountPrompt")," ",X(Hr,{sx:{cursor:"pointer"},onClick:()=>{let C=`/public/users/create${Object.keys(s.searchParams).length>0?`?${new URLSearchParams(s.searchParams).toString()}`:""}`;r?.(C)},fontWeight:"medium",color:"secondary",children:i("login.signUpLink")})]})]})},jr=$o;import{useState as Ie,useEffect as Go,useRef as Yo}from"react";import{Typography as Se,TextField as Jo,Button as qr,Box as ge,CircularProgress as Qo,Alert as Xo,Link as nr}from"@mui/material";import{Fragment as $r,jsx as U,jsxs as xe}from"react/jsx-runtime";var Zo=({onScreenChange:e,onError:r})=>{let{crudify:o}=te(),[t,a]=Ie(""),[n,s]=Ie(!1),[l,d]=Ie([]),[w,u]=Ie(null),[h,g]=Ie(!1),[i,c]=Ie(!1),b=Yo(null),{t:p}=Q();Go(()=>{b.current&&!h&&!i&&b.current.focus()},[h,i]);let y=f=>{let C=[`errors.auth.${f.code}`,`errors.data.${f.code}`,`errors.system.${f.code}`,`errors.${f.code}`,`forgotPassword.${f.code.toLowerCase()}`];for(let k of C){let _=p(k);if(_!==k)return _}return f.message||p("error.unknown")},m=f=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f),P=async()=>{if(!(n||!o)){if(d([]),u(null),!t){u(p("forgotPassword.emailRequired"));return}if(!m(t)){u(p("forgotPassword.invalidEmail"));return}s(!0);try{let f=[{operation:"requestPasswordReset",data:{email:t}}],C=await o.transaction(f);if(C.success)C.data&&C.data.existingCodeValid?c(!0):g(!0);else{let _=$(C).map(y);d(_)}}catch(f){let k=$(f).map(y);d(k),r&&r(k.join(", "))}finally{s(!1)}}},R=()=>{e?.("login")},M=()=>{if(h||i){e?.("checkCode",{email:t});return}if(!t){u(p("forgotPassword.emailRequired"));return}if(!m(t)){u(p("forgotPassword.invalidEmail"));return}e?.("checkCode",{email:t})};return h||i?U($r,{children:xe(ge,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[xe(ge,{sx:{mb:2},children:[U(Se,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:p(i?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),U(Se,{variant:"body2",sx:{color:i?"success.main":"grey.600"},children:p("forgotPassword.checkEmailInstructions")})]}),U(qr,{type:"button",onClick:M,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:p("forgotPassword.enterCodeLink")}),U(ge,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:U(nr,{sx:{cursor:"pointer"},onClick:R,variant:"body2",color:"secondary",children:p("common.back")})})]})}):xe($r,{children:[xe(ge,{component:"form",noValidate:!0,onSubmit:f=>{f.preventDefault(),P()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[xe(ge,{sx:{mb:2},children:[U(Se,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:p("forgotPassword.title")}),U(Se,{variant:"body2",sx:{color:"grey.600"},children:p("forgotPassword.instructions")})]}),xe(ge,{sx:{mb:1},children:[U(Se,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:p("forgotPassword.emailLabel")}),U(Jo,{fullWidth:!0,id:"email",name:"email",type:"email",value:t,disabled:n,onChange:f=>a(f.target.value),error:!!w,helperText:w,autoComplete:"email",placeholder:p("forgotPassword.emailPlaceholder"),required:!0,autoFocus:!0,inputRef:b})]}),U(qr,{disabled:n,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?U(Qo,{size:20}):p("forgotPassword.sendCodeButton")}),xe(ge,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[U(nr,{sx:{cursor:"pointer"},onClick:R,variant:"body2",color:"secondary",children:p("common.back")}),U(Se,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),U(nr,{sx:{cursor:"pointer"},onClick:M,variant:"body2",color:"secondary",children:p("login.alreadyHaveCodeLink")})]})]}),U(ge,{children:l.length>0&&l.map((f,C)=>U(Xo,{variant:"filled",sx:{mt:2},severity:"error",children:f},C))})]})},Kr=Zo;import{useState as Y,useEffect as Gr}from"react";import{Typography as qe,TextField as Yr,Button as et,Box as me,CircularProgress as Jr,Alert as Qr,Link as rt}from"@mui/material";import{Fragment as tt,jsx as W,jsxs as Oe}from"react/jsx-runtime";var ot=({onScreenChange:e,onError:r,searchParams:o,onResetSuccess:t})=>{let{crudify:a}=te(),[n,s]=Y(""),[l,d]=Y(""),[w,u]=Y(!1),[h,g]=Y([]),[i,c]=Y(null),[b,p]=Y(null),[y,m]=Y(""),[P,R]=Y(""),[M,x]=Y(!1),[f,C]=Y(!0),[k,_]=Y(!1),[ie,be]=Y(null),[oe,de]=Y(!1),{t:A}=Q(),V=v=>{let S=[`errors.auth.${v.code}`,`errors.data.${v.code}`,`errors.system.${v.code}`,`errors.${v.code}`,`resetPassword.${v.code.toLowerCase()}`];for(let O of S){let j=A(O);if(j!==O)return j}return v.message||A("error.unknown")},F=v=>o?o instanceof URLSearchParams?o.get(v):o[v]||null:null;Gr(()=>{if(o){if(o){let v=F("fromCodeVerification"),S=F("email"),O=F("code");if(v==="true"&&S&&O){m(S),R(O),x(!0),_(!0),C(!1);return}let j=F("link");if(j)try{let K=decodeURIComponent(j),[G,ae]=K.split("/");if(G&&ae&&G.length===6){R(G),m(ae),x(!1),be({email:ae,code:G});return}}catch{}if(S&&O){m(S),R(O),x(!1),be({email:S,code:O});return}}g([A("resetPassword.invalidCode")]),C(!1),setTimeout(()=>e?.("forgotPassword"),3e3)}},[o,a,A,e]),Gr(()=>{a&&ie&&!oe&&(de(!0),(async(S,O)=>{try{let j=[{operation:"validatePasswordResetCode",data:{email:S,codePassword:O}}],K=await a.transaction(j);if(K.data&&Array.isArray(K.data)){let G=K.data[0];if(G&&G.response&&G.response.status==="OK"){_(!0);return}}if(K.success)_(!0);else{let ae=$(K).map(V);g(ae),setTimeout(()=>e?.("forgotPassword"),3e3)}}catch(j){let G=$(j).map(V);g(G),setTimeout(()=>e?.("forgotPassword"),3e3)}finally{C(!1),be(null),de(!1)}})(ie.email,ie.code))},[a,ie,A,e]);let Te=v=>v.length<8?A("resetPassword.passwordTooShort"):null,I=async()=>{if(w||!a)return;g([]),c(null),p(null);let v=!1;if(!n)c(A("resetPassword.newPasswordRequired")),v=!0;else{let S=Te(n);S&&(c(S),v=!0)}if(l?n!==l&&(p(A("resetPassword.passwordsDoNotMatch")),v=!0):(p(A("resetPassword.confirmPasswordRequired")),v=!0),!v){u(!0);try{let S=[{operation:"validateAndResetPassword",data:{email:y,codePassword:P,newPassword:n}}],O=await a.transaction(S);if(O.success)g([]),setTimeout(()=>{t?.()},1e3);else{let K=$(O).map(V);g(K)}}catch(S){let j=$(S).map(V);g(j),r&&r(j.join(", "))}u(!1)}},H=()=>{M?e?.("checkCode",{email:y}):e?.("forgotPassword")};return f?W(me,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:W(Jr,{})}):k?Oe(tt,{children:[Oe(me,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Oe(me,{sx:{mb:2},children:[W(qe,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:A("resetPassword.title")}),W(qe,{variant:"body2",sx:{color:"grey.600"},children:A("resetPassword.instructions")})]}),Oe(me,{sx:{mb:1},children:[W(qe,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:A("resetPassword.newPasswordLabel")}),W(Yr,{fullWidth:!0,id:"newPassword",name:"newPassword",type:"password",value:n,disabled:w,onChange:v=>s(v.target.value),error:!!i,helperText:i,autoComplete:"new-password",placeholder:A("resetPassword.newPasswordPlaceholder"),required:!0})]}),Oe(me,{sx:{mb:1},children:[W(qe,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:A("resetPassword.confirmPasswordLabel")}),W(Yr,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:"password",value:l,disabled:w,onChange:v=>d(v.target.value),error:!!b,helperText:b,autoComplete:"new-password",placeholder:A("resetPassword.confirmPasswordPlaceholder"),required:!0})]}),W(et,{disabled:w,type:"button",onClick:I,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:w?W(Jr,{size:20}):A("resetPassword.resetPasswordButton")}),W(me,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:W(rt,{sx:{cursor:"pointer"},onClick:H,variant:"body2",color:"secondary",children:A("common.back")})})]}),W(me,{children:h.length>0&&h.map((v,S)=>W(Qr,{variant:"filled",sx:{mt:2},severity:"error",children:v},S))})]}):W(me,{children:h.length>0&&h.map((v,S)=>W(Qr,{variant:"filled",sx:{mt:2},severity:"error",children:v},S))})},Xr=ot;import{useState as Ne,useEffect as Zr,useRef as nt}from"react";import{Typography as sr,TextField as st,Button as it,Box as Be,CircularProgress as at,Alert as lt,Link as ct}from"@mui/material";import{Fragment as ut,jsx as ne,jsxs as $e}from"react/jsx-runtime";var dt=({onScreenChange:e,onError:r,searchParams:o})=>{let{crudify:t}=te(),[a,n]=Ne(""),[s,l]=Ne(!1),[d,w]=Ne([]),[u,h]=Ne(null),[g,i]=Ne(""),c=nt(null),{t:b}=Q(),p=x=>o?o instanceof URLSearchParams?o.get(x):o[x]||null:null,y=x=>{let f=[`errors.auth.${x.code}`,`errors.data.${x.code}`,`errors.system.${x.code}`,`errors.${x.code}`,`checkCode.${x.code.toLowerCase()}`];for(let C of f){let k=b(C);if(k!==C)return k}return x.message||b("error.unknown")};Zr(()=>{let x=p("email");x?i(x):e?.("forgotPassword")},[o,e]),Zr(()=>{c.current&&c.current.focus()},[]);let m=async()=>{if(!(s||!t)){if(w([]),h(null),!a){h(b("checkCode.codeRequired"));return}if(a.length!==6){h(b("checkCode.codeRequired"));return}l(!0);try{let x=[{operation:"validatePasswordResetCode",data:{email:g,codePassword:a}}],f=await t.transaction(x);if(f.success)e?.("resetPassword",{email:g,code:a,fromCodeVerification:"true"});else{let k=$(f).map(y);w(k),l(!1)}}catch(x){let C=$(x).map(y);w(C),l(!1),r&&r(C.join(", "))}}},P=()=>{e?.("forgotPassword")},R=x=>{let f=x.target.value.replace(/\D/g,"").slice(0,6);n(f)};return $e(ut,{children:[$e(Be,{component:"form",noValidate:!0,onSubmit:x=>{x.preventDefault(),m()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[$e(Be,{sx:{mb:2},children:[ne(sr,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:b("checkCode.title")}),ne(sr,{variant:"body2",sx:{color:"grey.600"},children:b("checkCode.instructions")})]}),$e(Be,{sx:{mb:1},children:[ne(sr,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:b("checkCode.codeLabel")}),ne(st,{fullWidth:!0,id:"code",name:"code",type:"text",value:a,disabled:s,onChange:R,error:!!u,helperText:u,placeholder:b("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0,autoFocus:!0,inputRef:c})]}),ne(it,{disabled:s||a.length!==6,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:s?ne(at,{size:20}):b("checkCode.verifyButton")}),ne(Be,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:ne(ct,{sx:{cursor:"pointer"},onClick:P,variant:"body2",color:"secondary",children:b("common.back")})})]}),ne(Be,{children:d.length>0&&d.map((x,f)=>ne(lt,{sx:{mt:2},severity:"error",children:x},f))})]})},eo=dt;import{Box as gt,CircularProgress as mt,Alert as ro,Typography as ir}from"@mui/material";import{Fragment as pt,jsx as Le,jsxs as oo}from"react/jsx-runtime";var to=({children:e,fallback:r})=>{let{isLoading:o,error:t,isInitialized:a}=te(),{t:n}=Q();return o?r||oo(gt,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[Le(mt,{}),Le(ir,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):t?Le(ro,{severity:"error",sx:{mt:2},children:oo(ir,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",t]})}):a?Le(pt,{children:e}):Le(ro,{severity:"warning",sx:{mt:2},children:Le(ir,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as ee,jsxs as wt}from"react/jsx-runtime";var ht=({onScreenChange:e,onExternalNavigate:r,onLoginSuccess:o,onError:t,redirectUrl:a="/"})=>{let{t:n}=Q(),{state:s,setScreen:l}=je(),{config:d}=ue(),{showNotification:w}=vr(),u=(g,i)=>{let c=i;g==="login"?c={}:g==="forgotPassword"&&!i&&(c={}),l(g,c),e?.(g,c)},h=()=>{let g={onScreenChange:u,onExternalNavigate:r,onError:t,redirectUrl:a};switch(s.currentScreen){case"forgotPassword":return ee(Kr,{...g});case"checkCode":return ee(eo,{...g,searchParams:s.searchParams});case"resetPassword":return ee(Xr,{...g,searchParams:s.searchParams,onResetSuccess:()=>{let i=n("resetPassword.successMessage");w(i,"success"),u("login")}});default:return ee(jr,{...g,onLoginSuccess:o})}};return wt(to,{children:[ee(ft,{sx:{display:"flex",justifyContent:"center",mb:3},children:ee("img",{src:d.logo||"https://logos.crudia.com/nocios-default.png",alt:n("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:g=>{let i=g.target;i.src="https://logos.crudia.com/nocios-default.png"}})}),!d.logo&&d.appName&&ee(yt,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:d.appName}),h()]})},bt=({translations:e,translationsUrl:r,language:o="en",initialScreen:t="login",autoReadFromCookies:a=!0,...n})=>{let{config:s}=ue();return ee(Dr,{translations:e,translationsUrl:r,language:o,children:ee(Pr,{config:s,children:ee(Vr,{config:s,initialScreen:t,autoReadFromCookies:a,children:ee(ht,{...n})})})})},ci=bt;import{Box as J,Card as no,CardContent as so,Typography as re,Chip as Ke,Avatar as xt,Divider as Pt,CircularProgress as Ct,Alert as io,List as vt,ListItem as ar,ListItemText as lr,ListItemIcon as Tt,Collapse as Et,IconButton as cr}from"@mui/material";import{Person as Rt,Email as It,Badge as St,Security as Lt,Schedule as kt,AccountCircle as At,ExpandMore as Ft,ExpandLess as _t,Info as Ot}from"@mui/icons-material";import{useState as Nt}from"react";import{Fragment as zt,jsx as T,jsxs as N}from"react/jsx-runtime";var Bt=({showExtendedData:e=!0,showProfileCard:r=!0,autoRefresh:o=!0})=>{let{userProfile:t,loading:a,error:n,extendedData:s,refreshProfile:l}=Tr({autoFetch:o,retryOnError:!0,maxRetries:3}),[d,w]=Nt(!1);if(a)return N(J,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[T(Ct,{}),T(re,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return N(io,{severity:"error",action:T(cr,{color:"inherit",size:"small",onClick:l,children:T(re,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!t)return T(io,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let u=s?.displayData||{},h=s?.totalFields||0,g=m=>{if(!m)return"No disponible";try{return new Date(m).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return m}},i=(m,P)=>P==null?"No disponible":typeof P=="boolean"?P?"S\xED":"No":Array.isArray(P)?P.length>0?P.join(", "):"Ninguno":typeof P=="object"?JSON.stringify(P,null,2):String(P),c=[{key:"id",label:"ID",icon:T(St,{})},{key:"email",label:"Email",icon:T(It,{})},{key:"username",label:"Usuario",icon:T(Rt,{})},{key:"fullName",label:"Nombre completo",icon:T(At,{})},{key:"role",label:"Rol",icon:T(Lt,{})}],b=[{key:"firstName",label:"Nombre"},{key:"lastName",label:"Apellido"},{key:"isActive",label:"Activo"},{key:"lastLogin",label:"\xDAltimo login"},{key:"createdAt",label:"Creado"},{key:"updatedAt",label:"Actualizado"}],p=[...c.map(m=>m.key),...b.map(m=>m.key),"permissions"],y=Object.keys(u).filter(m=>!p.includes(m)).map(m=>({key:m,label:m}));return N(J,{children:[r&&T(no,{sx:{mb:2},children:N(so,{children:[N(J,{display:"flex",alignItems:"center",mb:2,children:[T(xt,{src:u.avatar,sx:{width:56,height:56,mr:2},children:u.fullName?.[0]||u.username?.[0]||u.email?.[0]}),N(J,{children:[T(re,{variant:"h6",children:u.fullName||u.username||u.email}),T(re,{variant:"body2",color:"text.secondary",children:u.role||"Usuario"}),u.isActive!==void 0&&T(Ke,{label:u.isActive?"Activo":"Inactivo",color:u.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),T(J,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:c.map(({key:m,label:P,icon:R})=>u[m]?N(J,{display:"flex",alignItems:"center",children:[T(J,{sx:{mr:1,color:"text.secondary"},children:R}),N(J,{children:[T(re,{variant:"caption",color:"text.secondary",children:P}),T(re,{variant:"body2",children:i(m,u[m])})]})]},m):null)}),u.permissions&&Array.isArray(u.permissions)&&u.permissions.length>0&&N(J,{mt:2,children:[T(re,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),N(J,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[u.permissions.slice(0,5).map((m,P)=>T(Ke,{label:m,size:"small",variant:"outlined"},P)),u.permissions.length>5&&T(Ke,{label:`+${u.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&T(no,{children:N(so,{children:[N(J,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[N(re,{variant:"h6",display:"flex",alignItems:"center",children:[T(Ot,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),T(Ke,{label:`${h} campos totales`,size:"small"})]}),N(vt,{dense:!0,children:[b.map(({key:m,label:P})=>u[m]!==void 0&&N(ar,{divider:!0,children:[T(Tt,{children:T(kt,{fontSize:"small"})}),T(lr,{primary:P,secondary:m.includes("At")||m.includes("Login")?g(u[m]):i(m,u[m])})]},m)),y.length>0&&N(zt,{children:[T(Pt,{sx:{my:1}}),T(ar,{children:T(lr,{primary:N(J,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[N(re,{variant:"subtitle2",children:["Campos Personalizados (",y.length,")"]}),T(cr,{size:"small",onClick:()=>w(!d),children:d?T(_t,{}):T(Ft,{})})]})})}),T(Et,{in:d,children:y.map(({key:m,label:P})=>T(ar,{sx:{pl:4},children:T(lr,{primary:P,secondary:i(m,u[m])})},m))})]})]}),N(J,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[N(re,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",g(u.updatedAt)]}),T(cr,{size:"small",onClick:l,disabled:a,children:T(re,{variant:"caption",children:"Actualizar"})})]})]})})]})},Dt=Bt;var ao=["create","read","update","delete"],lo=["create","read","update","delete"];import{useRef as ln}from"react";import{useTranslation as cn}from"react-i18next";import{Box as Je,Typography as yo,Button as dn,Stack as un,Alert as ho,Divider as gn}from"@mui/material";import{Add as mn}from"@mui/icons-material";import{forwardRef as Gt}from"react";import{useTranslation as Yt}from"react-i18next";import{Box as Pe,FormControl as Jt,InputLabel as Qt,Select as Xt,MenuItem as Zt,IconButton as en,Typography as ke,FormHelperText as rn,Stack as Ye,Paper as fo,Divider as on,Button as mr}from"@mui/material";import{Delete as tn,SelectAll as nn,ClearAll as sn}from"@mui/icons-material";import{useState as co,useEffect as uo,useRef as go}from"react";import{useTranslation as Ut}from"react-i18next";import{Box as Ge,Typography as De,Button as mo,Stack as dr,FormControlLabel as Mt,FormHelperText as po,Switch as Vt,ToggleButton as ur,ToggleButtonGroup as Wt}from"@mui/material";import{CheckCircle as Ht,Cancel as jt,SelectAll as qt,ClearAll as $t}from"@mui/icons-material";import{jsx as D,jsxs as pe}from"react/jsx-runtime";var Kt=({value:e,onChange:r,availableFields:o,error:t,disabled:a=!1})=>{let{t:n}=Ut(),[s,l]=co("custom"),[d,w]=co(!1),u=go(null);uo(()=>{d&&u.current?.scrollIntoView({behavior:"smooth",block:"start"})},[d]);let h=go(!1);uo(()=>{let p=e||{allow:[],owner_allow:[],deny:[]},y=new Set(o),m=(p.allow||[]).filter(x=>y.has(x)),P=(p.owner_allow||[]).filter(x=>y.has(x)),R=(p.deny||[]).filter(x=>y.has(x));o.forEach(x=>{!m.includes(x)&&!P.includes(x)&&!R.includes(x)&&R.push(x)});let M={allow:m,owner_allow:P,deny:R};JSON.stringify(M)!==JSON.stringify(p)&&r(M),m.length===o.length?l("all"):R.length===o.length?l("none"):l("custom")},[o,e]);let g=()=>{h.current=!0,r({allow:[...o],owner_allow:[],deny:[]}),l("all"),setTimeout(()=>{h.current=!1},0)},i=()=>{h.current=!0,r({allow:[],owner_allow:[],deny:[...o]}),l("none"),setTimeout(()=>{h.current=!1},0)},c=p=>e?.allow?.includes(p)?"allow":e?.owner_allow?.includes(p)?"owner_allow":"deny",b=(p,y)=>{h.current=!0;let m=new Set(e?.allow||[]),P=new Set(e?.owner_allow||[]),R=new Set(e?.deny||[]);m.delete(p),P.delete(p),R.delete(p),y==="allow"&&m.add(p),y==="owner_allow"&&P.add(p),y==="deny"&&R.add(p),r({allow:Array.from(m),owner_allow:Array.from(P),deny:Array.from(R)}),l("custom"),setTimeout(()=>{h.current=!1},0)};return o.length===0?pe(Ge,{children:[D(De,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("modules.form.publicPolicies.fields.conditions.label")}),D(De,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("modules.form.publicPolicies.fields.conditions.noFieldsAvailable")}),t&&D(po,{error:!0,sx:{mt:1},children:t})]}):pe(Ge,{children:[D(De,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.label")}),pe(dr,{direction:"row",spacing:1,alignItems:"center",sx:{mb:d?3:1},children:[D(mo,{variant:s==="all"?"contained":"outlined",startIcon:D(qt,{}),onClick:g,disabled:a,size:"small",sx:{minWidth:120,...s==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("modules.form.publicPolicies.fields.conditions.allFields")}),D(mo,{variant:s==="none"?"contained":"outlined",startIcon:D($t,{}),onClick:i,disabled:a,size:"small",sx:{minWidth:120,...s==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("modules.form.publicPolicies.fields.conditions.noFields")}),D(Ge,{sx:{display:"flex",alignItems:"center",px:1.5,py:.35,borderRadius:"999px",backgroundColor:"#f3f4f6",border:"1px solid #d1d9e0"},children:D(Mt,{control:D(Vt,{size:"small",checked:d,onChange:()=>w(p=>!p),disabled:a,color:"primary",sx:{transform:"scale(1.15)",transformOrigin:"center",m:0}}),label:n("modules.form.publicPolicies.fields.conditions.customEdit"),labelPlacement:"end",sx:{ml:0,".MuiFormControlLabel-label":{fontSize:"0.75rem"}}})})]}),d&&pe(Ge,{ref:u,sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[D(De,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("modules.form.publicPolicies.fields.conditions.help")}),D(dr,{spacing:1,children:o.map(p=>{let y=c(p);return pe(dr,{direction:"row",spacing:1,alignItems:"center",children:[D(De,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:p}),pe(Wt,{value:y,exclusive:!0,size:"small",children:[pe(ur,{value:"allow",onClick:()=>b(p,"allow"),disabled:a,sx:{px:2,color:y==="allow"?"#ffffff":"#6b7280",backgroundColor:y==="allow"?"#16a34a":"#f3f4f6",borderColor:y==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:y==="allow"?"#15803d":"#e5e7eb",borderColor:y==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[D(Ht,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.allow")]}),D(ur,{value:"owner_allow",onClick:()=>b(p,"owner_allow"),disabled:a,sx:{px:2,color:y==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:y==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:y==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:y==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:y==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),pe(ur,{value:"deny",onClick:()=>b(p,"deny"),disabled:a,sx:{px:2,color:y==="deny"?"#ffffff":"#6b7280",backgroundColor:y==="deny"?"#dc2626":"#f3f4f6",borderColor:y==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:y==="deny"?"#b91c1c":"#e5e7eb",borderColor:y==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[D(jt,{sx:{fontSize:16,mr:.5}}),n("modules.form.publicPolicies.fields.conditions.states.deny")]})]})]},p)})})]}),t&&D(po,{error:!0,sx:{mt:1},children:t})]})},gr=Kt;import{jsx as z,jsxs as q}from"react/jsx-runtime";var an=Gt(({policy:e,onChange:r,onRemove:o,availableFields:t,isSubmitting:a=!1,usedActions:n,error:s},l)=>{let{t:d}=Yt(),w=new Set(Array.from(n||[]));w.delete(e.action);let u=ao.map(h=>({value:h,label:d(`modules.form.publicPolicies.fields.action.options.${h}`)}));return q(fo,{ref:l,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[q(Pe,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[z(ke,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:d("modules.form.publicPolicies.policyTitle")}),z(en,{onClick:o,size:"small",disabled:a,"aria-label":d("modules.form.publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:z(tn,{})})]}),q(Ye,{spacing:1,children:[z(Ye,{direction:{xs:"column",md:"row"},spacing:2,children:z(Pe,{sx:{flex:1,minWidth:200},children:q(Jt,{fullWidth:!0,children:[z(Qt,{children:d("modules.form.publicPolicies.fields.action.label")}),z(Xt,{value:e.action,label:d("modules.form.publicPolicies.fields.action.label"),disabled:a,onChange:h=>{let g=h.target.value,i={...e,action:g};g==="delete"?(i.permission="deny",delete i.fields):(i.fields={allow:[],owner_allow:[],deny:t},delete i.permission),r(i)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:u.map(h=>{let g=w.has(h.value);return z(Zt,{value:h.value,disabled:g,children:h.label},h.value)})}),s&&z(rn,{error:!0,children:s})]})})}),e.action==="delete"?q(Pe,{children:[z(ke,{variant:"body2",color:"text.secondary",sx:{mb:2},children:d("modules.form.publicPolicies.fields.conditions.label")}),q(Ye,{direction:"row",spacing:1,sx:{mb:1},children:[z(mr,{variant:e.permission==="*"?"contained":"outlined",startIcon:z(nn,{}),onClick:()=>r({...e,permission:"*"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:d("modules.form.publicPolicies.fields.conditions.allFields")}),z(mr,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>r({...e,permission:"owner"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:d("modules.form.publicPolicies.fields.conditions.states.ownerAllow")}),z(mr,{variant:e.permission==="deny"?"contained":"outlined",startIcon:z(sn,{}),onClick:()=>r({...e,permission:"deny"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:d("modules.form.publicPolicies.fields.conditions.noFields")})]})]}):z(gr,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:h=>r({...e,fields:h}),availableFields:t,disabled:a}),z(fo,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?q(ke,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[q(Pe,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[d("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):q(Ye,{spacing:.5,divider:z(on,{sx:{borderColor:"#e5e7eb"}}),children:[q(ke,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[q(Pe,{component:"span",sx:{color:"#16a34a"},children:[d("modules.form.publicPolicies.fields.conditions.states.allow"),":"]})," ",(e?.fields?.allow||[]).join(", ")||"-"]}),q(ke,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[q(Pe,{component:"span",sx:{color:"#0ea5e9"},children:[d("modules.form.publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(e?.fields?.owner_allow||[]).join(", ")||"-"]}),q(ke,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[q(Pe,{component:"span",sx:{color:"#dc2626"},children:[d("modules.form.publicPolicies.fields.conditions.states.deny"),":"]})," ",(e?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),pr=an;import{Fragment as yn,jsx as se,jsxs as Qe}from"react/jsx-runtime";var pn=()=>{let e=globalThis?.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`},fn=({policies:e,onChange:r,availableFields:o,errors:t,isSubmitting:a=!1})=>{let{t:n}=cn(),s=ln({}),l=new Set((e||[]).map(c=>c.action).filter(Boolean)),d=lo.filter(c=>!l.has(c)),w=d.length>0,u=()=>{let c=d[0]||"create",b={id:pn(),action:c};c==="delete"?b.permission="deny":b.fields={allow:[],owner_allow:[],deny:o};let p=[...e||[],b];r(p),setTimeout(()=>{let y=p.length-1,m=s.current[y];m&&m.scrollIntoView({behavior:"smooth",block:"center"})},100)},h=c=>{let b=[...e];b.splice(c,1),r(b)},g=(()=>{if(!t)return null;if(typeof t=="string")return t;let c=t._error;return typeof c=="string"?c:null})(),i=new Set((e||[]).map(c=>c.action));return Qe(yn,{children:[se(gn,{sx:{borderColor:"#e0e4e7"}}),Qe(Je,{children:[se(Je,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:Qe(Je,{children:[se(yo,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("modules.form.publicPolicies.title")}),se(yo,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("modules.form.publicPolicies.description")})]})}),g&&se(ho,{severity:"error",sx:{mb:3},children:g}),Qe(un,{spacing:3,children:[(e||[]).length===0?se(ho,{severity:"info",children:n("modules.form.publicPolicies.noPolicies")}):e.map((c,b)=>se(pr,{ref:p=>{s.current[b]=p},policy:c,onChange:p=>{let y=[...e];y[b]=p,r(y)},onRemove:()=>h(b),availableFields:o,isSubmitting:a,usedActions:i,error:typeof t=="object"&&t&&c.id in t?t[c.id]:void 0},c.id)),w&&se(Je,{children:se(dn,{type:"button",variant:"outlined",startIcon:se(mn,{}),onClick:u,disabled:a,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("modules.form.publicPolicies.addPolicy")})})]})]})]})},Ki=fn;import{useState as fr}from"react";import{Button as Xe,TextField as bo,Box as Ae,Alert as ze,Typography as fe,CircularProgress as yr}from"@mui/material";import{jsx as B,jsxs as ce}from"react/jsx-runtime";function ea(){let[e,r]=fr(""),[o,t]=fr(""),[a,n]=fr(!1),{isAuthenticated:s,isLoading:l,error:d,login:w,logout:u,refreshTokens:h,clearError:g,isExpiringSoon:i,expiresIn:c}=ue(),b=async m=>{if(m.preventDefault(),!e||!o)return;(await w(e,o)).success&&(r(""),t(""),n(!1))},p=async()=>{await u()},y=async()=>{await h()};return s?ce(Ae,{sx:{maxWidth:600,mx:"auto",p:3},children:[B(fe,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),B(ze,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),ce(Ae,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[B(fe,{variant:"h6",gutterBottom:!0,children:"Token Status"}),ce(fe,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(c/1e3/60)," minutes"]}),i&&B(ze,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),ce(Ae,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[B(Xe,{variant:"contained",onClick:y,disabled:l,startIcon:l?B(yr,{size:16}):null,children:"Refresh Tokens"}),B(Xe,{variant:"outlined",color:"error",onClick:p,disabled:l,children:"Logout"})]}),d&&B(ze,{severity:"error",sx:{mt:2},onClose:g,children:d})]}):ce(Ae,{sx:{maxWidth:400,mx:"auto",p:3},children:[B(fe,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),B(ze,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),a?ce("form",{onSubmit:b,children:[B(bo,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:m=>r(m.target.value),margin:"normal",required:!0,autoComplete:"email"}),B(bo,{fullWidth:!0,label:"Password",type:"password",value:o,onChange:m=>t(m.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),B(Xe,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:l,startIcon:l?B(yr,{size:16}):null,sx:{mt:3,mb:2},children:l?"Logging in...":"Login"})]}):B(Xe,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),d&&B(ze,{severity:"error",sx:{mt:2},onClose:g,children:d})]})}function ra(){let{isAuthenticated:e,isLoading:r,isExpiringSoon:o,expiresIn:t}=ue();return r?ce(Ae,{sx:{display:"flex",alignItems:"center",gap:1},children:[B(yr,{size:16}),B(fe,{variant:"caption",children:"Loading session..."})]}):e?ce(Ae,{children:[B(fe,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),o&&ce(fe,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(t/1e3/60)," min"]})]}):B(fe,{variant:"caption",color:"text.secondary",children:"Not logged in"})}import hn from"@mui/material/TextField";import bn from"@mui/material/CircularProgress";import wo from"@mui/material/InputAdornment";import wn from"@mui/material/IconButton";import xn from"@mui/icons-material/Refresh";import{jsx as ye}from"react/jsx-runtime";var Pn=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),Cn=({html:e})=>ye("span",{dangerouslySetInnerHTML:{__html:Pn(e)}}),da=({config:e,value:r,onChange:o,label:t,error:a=!1,helperText:n,readOnly:s=!1,disabled:l=!1})=>{let{value:d,loading:w,error:u,regenerate:h}=Er(e,{autoFetch:!r,onSuccess:y=>{o?.(y)}}),g=r||d,i=a||!!u,c=u||n,b=i&&c&&(c.toLowerCase().includes("duplicate")||c.toLowerCase().includes("duplicado")||c.toLowerCase().includes("duplicada")||c.toLowerCase().includes("unique")||c.toLowerCase().includes("\xFAnico")||c.toLowerCase().includes("unico")||c.toLowerCase().includes("\xFAnica")||c.toLowerCase().includes("unica")||c.toLowerCase().includes("already exists")||c.toLowerCase().includes("ya existe")||c.toLowerCase().includes("e11000"));return ye(hn,{label:t,fullWidth:!0,value:g,error:i,helperText:c?ye(Cn,{html:c}):" ",disabled:l,InputProps:{readOnly:!0,startAdornment:w?ye(wo,{position:"start",children:ye(bn,{size:20})}):void 0,endAdornment:b&&!w?ye(wo,{position:"end",children:ye(wn,{edge:"end",onClick:async()=>{!l&&!w&&await h()},disabled:l,size:"small",color:"error","aria-label":"regenerar c\xF3digo",title:"Regenerar c\xF3digo",children:ye(xn,{})})}):void 0}})};import xo,{useCallback as Ue,useRef as Po,useState as vo}from"react";import Ce from"@mui/material/Box";import ve from"@mui/material/Typography";import Co from"@mui/material/IconButton";import vn from"@mui/material/LinearProgress";import hr from"@mui/material/CircularProgress";import Tn from"@mui/material/Chip";import En from"@mui/material/Paper";import Rn from"@mui/material/List";import In from"@mui/material/ListItem";import Sn from"@mui/material/ListItemText";import Ln from"@mui/material/ListItemSecondaryAction";import kn from"@mui/material/FormHelperText";import An from"@mui/icons-material/CloudUpload";import Fn from"@mui/icons-material/InsertDriveFile";import _n from"@mui/icons-material/Image";import On from"@mui/icons-material/PictureAsPdf";import Nn from"@mui/icons-material/Delete";import Bn from"@mui/icons-material/Refresh";import Dn from"@mui/icons-material/CheckCircle";import zn from"@mui/icons-material/Error";import Na from"@mui/icons-material/BrokenImage";import{jsx as E,jsxs as he}from"react/jsx-runtime";var To=e=>{if(e===0)return"0 B";let r=1024,o=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(r));return`${parseFloat((e/Math.pow(r,t)).toFixed(1))} ${o[t]}`},Un=e=>e.startsWith("image/")?E(_n,{color:"primary"}):e==="application/pdf"?E(On,{color:"error"}):E(Fn,{color:"action"}),Mn=e=>{switch(e){case"completed":return E(Dn,{color:"success",fontSize:"small"});case"error":return E(zn,{color:"error",fontSize:"small"});case"uploading":case"pending":return E(hr,{size:16});case"removing":return E(hr,{size:16,color:"error"});default:return null}},Vn=({file:e,baseUrl:r,disabled:o,onRemove:t,onRetry:a})=>{let[n,s]=vo(!1),l=!o&&e.status!=="uploading"&&e.status!=="removing",d=!o&&e.status==="error"&&e.file,w=e.contentType.startsWith("image/"),u=e.visibility==="public"||e.filePath?.startsWith("public/")||e.filePath?.startsWith(r),g=!e.filePath||!u?null:e.filePath.startsWith("http://")||e.filePath.startsWith("https://")||e.filePath.startsWith(r)?e.filePath:`${r}${e.filePath}`,i=e.status==="completed"&&g,c=()=>w&&i&&!n?E(Ce,{component:i?"a":"div",href:g||void 0,target:"_blank",rel:"noopener noreferrer",sx:{width:48,height:48,borderRadius:1,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"grey.100",border:"1px solid",borderColor:"divider",cursor:i?"pointer":"default",transition:"all 0.2s ease",flexShrink:0,"&:hover":i?{borderColor:"primary.main",transform:"scale(1.05)"}:{}},children:E("img",{src:g,alt:e.name,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>s(!0)})}):E(Ce,{component:i?"a":"div",href:g||void 0,target:"_blank",rel:"noopener noreferrer",sx:{width:48,height:48,borderRadius:1,display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"grey.50",border:"1px solid",borderColor:"divider",cursor:i?"pointer":"default",transition:"all 0.2s ease",flexShrink:0,textDecoration:"none","&:hover":i?{borderColor:"primary.main",bgcolor:"action.hover"}:{}},children:Un(e.contentType)});return he(In,{sx:{borderRadius:1,mb:.5,bgcolor:e.status==="error"?"error.lighter":"background.paper",border:"1px solid",borderColor:e.status==="error"?"error.light":"divider",gap:1.5},children:[c(),E(Sn,{primary:he(Ce,{sx:{display:"flex",alignItems:"center",gap:1},children:[E(ve,{variant:"body2",noWrap:!0,sx:{maxWidth:200,overflow:"hidden",textOverflow:"ellipsis"},children:e.name}),Mn(e.status)]}),secondary:he(Ce,{children:[e.size>0&&E(ve,{variant:"caption",color:"text.secondary",children:To(e.size)}),e.status==="uploading"&&E(vn,{variant:"determinate",value:e.progress,sx:{mt:.5,height:4,borderRadius:2}}),e.status==="error"&&e.errorMessage&&E(ve,{variant:"caption",color:"error",display:"block",children:e.errorMessage}),i&&E(ve,{variant:"caption",color:"primary",display:"block",children:w?"Click thumbnail to view":"Click to download"})]})}),he(Ln,{children:[d&&E(Co,{edge:"end",size:"small",onClick:()=>a(e.id),color:"primary",title:"Retry",children:E(Bn,{fontSize:"small"})}),l&&E(Co,{edge:"end",size:"small",onClick:()=>t(e.id),color:"error",title:"Delete",children:E(Nn,{fontSize:"small"})})]})]})};var Da=({label:e,accept:r,maxFileSize:o=10*1024*1024,multiple:t=!1,maxFiles:a,minFiles:n=0,required:s=!1,disabled:l=!1,error:d=!1,helperText:w,onChange:u,onValidation:h,initialFiles:g,placeholder:i,showFileList:c=!0,visibility:b="private",showPreview:p=!0,baseUrl:y})=>{let m=Po(null),[P,R]=vo(!1),M=t?a:1,x=s?Math.max(n,1):n,f={acceptedTypes:r,maxFileSize:o,maxFiles:M,minFiles:x,visibility:b,onFilesChange:L=>{let Z=L.filter(we=>we.status==="completed"&&we.filePath).map(we=>{let Ee=we.filePath;return Ee.startsWith(y)||Ee.startsWith("http://")||Ee.startsWith("https://")?Ee:y?`${y}${Ee}`:Ee});u?.(Z)}},{files:C,isUploading:k,addFiles:_,removeFile:ie,retryUpload:be,isValid:oe,validationError:de,initializeFiles:A,isTouched:V,markAsTouched:F,getPreviewUrl:Te}=Rr(f),I=Po(!1);xo.useEffect(()=>{g&&g.length>0&&!I.current&&(I.current=!0,A(g))},[g,A]),xo.useEffect(()=>{h?.(oe,de)},[oe,de,h]);let H=Ue(L=>{F();let Z=L.target.files;Z&&Z.length>0&&_(Z),m.current&&(m.current.value="")},[_,F]),v=Ue(()=>{l||(F(),m.current?.click())},[l,F]),S=Ue(L=>{L.preventDefault(),L.stopPropagation(),l||R(!0)},[l]),O=Ue(L=>{L.preventDefault(),L.stopPropagation(),R(!1)},[]),j=Ue(L=>{if(L.preventDefault(),L.stopPropagation(),R(!1),l)return;F();let Z=L.dataTransfer.files;Z&&Z.length>0&&_(Z)},[l,_,F]),K=r?.join(",")||"",G=!l&&(t||C.length===0),ae=d||V&&!oe,br=w||(V?de:null);return he(Ce,{sx:{width:"100%"},children:[e&&he(ve,{variant:"body2",sx:{mb:1,fontWeight:500,color:ae?"error.main":"text.primary"},children:[e,s&&E("span",{style:{color:"red"},children:" *"})]}),E("input",{ref:m,type:"file",accept:K,multiple:t,onChange:H,disabled:l,style:{display:"none"}}),G&&he(En,{variant:"outlined",onClick:v,onDragOver:S,onDragLeave:O,onDrop:j,sx:{p:3,textAlign:"center",cursor:l?"not-allowed":"pointer",borderStyle:"dashed",borderWidth:2,borderColor:P?"primary.main":ae?"error.main":"divider",bgcolor:P?"primary.lighter":l?"action.disabledBackground":"background.paper",transition:"all 0.2s ease","&:hover":l?{}:{borderColor:"primary.main",bgcolor:"action.hover"}},children:[E(An,{sx:{fontSize:48,color:P?"primary.main":l?"action.disabled":"action.active",mb:1}}),E(ve,{variant:"body2",color:l?"text.disabled":"text.secondary",children:(()=>{if(i)return i;let L=[];if(P)return"Drop file here";if(L.push("Drag files here or click to select"),r&&r.length>0){let Z=r.map(we=>we.split("/")[1]?.toUpperCase()||we).join(", ");L.push(`Allowed types: ${Z}`)}return o&&L.push(`Max ${To(o)} per file`),M!==void 0&&t&&L.push(`Max ${M} files`),L[0]})()}),r&&r.length>0&&!P&&E(Ce,{sx:{mt:1,display:"flex",gap:.5,justifyContent:"center",flexWrap:"wrap"},children:r.map(L=>E(Tn,{label:L.split("/")[1]?.toUpperCase()||L,size:"small",variant:"outlined",sx:{fontSize:"0.7rem"}},L))})]}),c&&C.length>0&&E(Rn,{dense:!0,sx:{mt:1,p:0},children:C.map(L=>E(Vn,{file:L,baseUrl:y,disabled:l,onRemove:ie,onRetry:be},L.id))}),k&&he(Ce,{sx:{display:"flex",alignItems:"center",gap:1,mt:1},children:[E(hr,{size:16}),E(ve,{variant:"caption",color:"text.secondary",children:"Uploading files..."})]}),br&&E(kn,{error:ae,sx:{mt:.5},children:br})]})};export{le as a,Hn as b,jn as c,Ze as d,Ve as e,es as f,_r as g,ci as h,Dt as i,ao as j,lo as k,Ki as l,ea as m,ra as n,da as o,Da as p};