@nocios/crudify-components 2.0.24 → 2.0.32

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,210 +0,0 @@
1
- /* eslint-disable */
2
- var addSorting = (function() {
3
- 'use strict';
4
- var cols,
5
- currentSort = {
6
- index: 0,
7
- desc: false
8
- };
9
-
10
- // returns the summary table element
11
- function getTable() {
12
- return document.querySelector('.coverage-summary');
13
- }
14
- // returns the thead element of the summary table
15
- function getTableHeader() {
16
- return getTable().querySelector('thead tr');
17
- }
18
- // returns the tbody element of the summary table
19
- function getTableBody() {
20
- return getTable().querySelector('tbody');
21
- }
22
- // returns the th element for nth column
23
- function getNthColumn(n) {
24
- return getTableHeader().querySelectorAll('th')[n];
25
- }
26
-
27
- function onFilterInput() {
28
- const searchValue = document.getElementById('fileSearch').value;
29
- const rows = document.getElementsByTagName('tbody')[0].children;
30
-
31
- // Try to create a RegExp from the searchValue. If it fails (invalid regex),
32
- // it will be treated as a plain text search
33
- let searchRegex;
34
- try {
35
- searchRegex = new RegExp(searchValue, 'i'); // 'i' for case-insensitive
36
- } catch (error) {
37
- searchRegex = null;
38
- }
39
-
40
- for (let i = 0; i < rows.length; i++) {
41
- const row = rows[i];
42
- let isMatch = false;
43
-
44
- if (searchRegex) {
45
- // If a valid regex was created, use it for matching
46
- isMatch = searchRegex.test(row.textContent);
47
- } else {
48
- // Otherwise, fall back to the original plain text search
49
- isMatch = row.textContent
50
- .toLowerCase()
51
- .includes(searchValue.toLowerCase());
52
- }
53
-
54
- row.style.display = isMatch ? '' : 'none';
55
- }
56
- }
57
-
58
- // loads the search box
59
- function addSearchBox() {
60
- var template = document.getElementById('filterTemplate');
61
- var templateClone = template.content.cloneNode(true);
62
- templateClone.getElementById('fileSearch').oninput = onFilterInput;
63
- template.parentElement.appendChild(templateClone);
64
- }
65
-
66
- // loads all columns
67
- function loadColumns() {
68
- var colNodes = getTableHeader().querySelectorAll('th'),
69
- colNode,
70
- cols = [],
71
- col,
72
- i;
73
-
74
- for (i = 0; i < colNodes.length; i += 1) {
75
- colNode = colNodes[i];
76
- col = {
77
- key: colNode.getAttribute('data-col'),
78
- sortable: !colNode.getAttribute('data-nosort'),
79
- type: colNode.getAttribute('data-type') || 'string'
80
- };
81
- cols.push(col);
82
- if (col.sortable) {
83
- col.defaultDescSort = col.type === 'number';
84
- colNode.innerHTML =
85
- colNode.innerHTML + '<span class="sorter"></span>';
86
- }
87
- }
88
- return cols;
89
- }
90
- // attaches a data attribute to every tr element with an object
91
- // of data values keyed by column name
92
- function loadRowData(tableRow) {
93
- var tableCols = tableRow.querySelectorAll('td'),
94
- colNode,
95
- col,
96
- data = {},
97
- i,
98
- val;
99
- for (i = 0; i < tableCols.length; i += 1) {
100
- colNode = tableCols[i];
101
- col = cols[i];
102
- val = colNode.getAttribute('data-value');
103
- if (col.type === 'number') {
104
- val = Number(val);
105
- }
106
- data[col.key] = val;
107
- }
108
- return data;
109
- }
110
- // loads all row data
111
- function loadData() {
112
- var rows = getTableBody().querySelectorAll('tr'),
113
- i;
114
-
115
- for (i = 0; i < rows.length; i += 1) {
116
- rows[i].data = loadRowData(rows[i]);
117
- }
118
- }
119
- // sorts the table using the data for the ith column
120
- function sortByIndex(index, desc) {
121
- var key = cols[index].key,
122
- sorter = function(a, b) {
123
- a = a.data[key];
124
- b = b.data[key];
125
- return a < b ? -1 : a > b ? 1 : 0;
126
- },
127
- finalSorter = sorter,
128
- tableBody = document.querySelector('.coverage-summary tbody'),
129
- rowNodes = tableBody.querySelectorAll('tr'),
130
- rows = [],
131
- i;
132
-
133
- if (desc) {
134
- finalSorter = function(a, b) {
135
- return -1 * sorter(a, b);
136
- };
137
- }
138
-
139
- for (i = 0; i < rowNodes.length; i += 1) {
140
- rows.push(rowNodes[i]);
141
- tableBody.removeChild(rowNodes[i]);
142
- }
143
-
144
- rows.sort(finalSorter);
145
-
146
- for (i = 0; i < rows.length; i += 1) {
147
- tableBody.appendChild(rows[i]);
148
- }
149
- }
150
- // removes sort indicators for current column being sorted
151
- function removeSortIndicators() {
152
- var col = getNthColumn(currentSort.index),
153
- cls = col.className;
154
-
155
- cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, '');
156
- col.className = cls;
157
- }
158
- // adds sort indicators for current column being sorted
159
- function addSortIndicators() {
160
- getNthColumn(currentSort.index).className += currentSort.desc
161
- ? ' sorted-desc'
162
- : ' sorted';
163
- }
164
- // adds event listeners for all sorter widgets
165
- function enableUI() {
166
- var i,
167
- el,
168
- ithSorter = function ithSorter(i) {
169
- var col = cols[i];
170
-
171
- return function() {
172
- var desc = col.defaultDescSort;
173
-
174
- if (currentSort.index === i) {
175
- desc = !currentSort.desc;
176
- }
177
- sortByIndex(i, desc);
178
- removeSortIndicators();
179
- currentSort.index = i;
180
- currentSort.desc = desc;
181
- addSortIndicators();
182
- };
183
- };
184
- for (i = 0; i < cols.length; i += 1) {
185
- if (cols[i].sortable) {
186
- // add the click event handler on the th so users
187
- // dont have to click on those tiny arrows
188
- el = getNthColumn(i).querySelector('.sorter').parentElement;
189
- if (el.addEventListener) {
190
- el.addEventListener('click', ithSorter(i));
191
- } else {
192
- el.attachEvent('onclick', ithSorter(i));
193
- }
194
- }
195
- }
196
- }
197
- // adds sorting functionality to the UI
198
- return function() {
199
- if (!getTable()) {
200
- return;
201
- }
202
- cols = loadColumns();
203
- loadData();
204
- addSearchBox();
205
- addSortIndicators();
206
- enableUI();
207
- };
208
- })();
209
-
210
- window.addEventListener('load', addSorting);
@@ -1 +0,0 @@
1
- import{g as Jr,i as Yr,j as he,l as be,n as Zr,o as Qr,r as eo}from"./chunk-PTUSZGL4.mjs";import{g as J}from"./chunk-JAPL7EZJ.mjs";import{a as x,b as Kr,d as qr,f as Gr,p as Xr}from"./chunk-4ILUXVPW.mjs";var ge={es:{},en:{}},Rs=()=>Object.keys(ge),Ss=e=>ge[e]||ge.es;import Ye from"@nocios/crudify-sdk";var ro="crudify_translations_",xt=3600*1e3;function oo(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 mr=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&&x.debug("[TranslationService] Waiting for crudify initialization..."),this.initializationPromise):(this.enableDebug&&x.debug("[TranslationService] Initializing crudify SDK..."),this.initializationPromise=(async()=>{try{let t=Ye.getTokenData();if(t&&t.endpoint){this.enableDebug&&x.debug("[TranslationService] Crudify already initialized"),this.isInitialized=!0;return}Ye.config(o);let i=await Ye.init(r,this.enableDebug?"debug":"none");if(i.success===!1)throw new Error(`Failed to initialize crudify: ${JSON.stringify(i.errors||"Unknown error")}`);this.isInitialized=!0,this.enableDebug&&x.debug("[TranslationService] Crudify SDK initialized successfully")}catch(t){throw x.error("[TranslationService] Failed to initialize crudify",t instanceof Error?t:{message:String(t)}),this.initializationPromise=null,t}})(),this.initializationPromise)}async fetchTranslations(r){let{apiKey:o,featureKeys:t,crudifyEnv:i="stg",urlTranslations:n}=r;this.enableDebug&&x.debug("[TranslationService] fetchTranslations called with:",{apiKeyHash:oo(o),crudifyEnv:i,featureKeys:t,hasUrlTranslations:!!n});let l=this.getFromCache(o),a=l?this.isCacheExpired(l):!0;if(l&&!a)return this.enableDebug&&x.debug("[TranslationService] Using cached translations"),this.mergeWithUrlTranslations(l.data.translations,n);try{await this.ensureCrudifyInitialized(o,i)}catch(u){return x.error("[TranslationService] Failed to initialize crudify",u instanceof Error?u:{message:String(u)}),l?(x.warn("[TranslationService] Using expired cache (init failed)"),this.mergeWithUrlTranslations(l.data.translations,n)):(x.warn("[TranslationService] Using critical bundle (init failed)"),this.getCriticalTranslationsOnly())}try{this.enableDebug&&x.debug("[TranslationService] Fetching from API via crudify SDK");let u=await this.fetchFromAPI(t);this.hasDataChanged(l,u)||!l?this.saveToCache(o,u):this.refreshCacheTimestamp(o);let d=this.mergeWithUrlTranslations(u.translations,n);return this.enableDebug&&x.debug("[TranslationService] Translations loaded:",{languages:Object.keys(d),keysCount:d[Object.keys(d)[0]]?Object.keys(d[Object.keys(d)[0]]).length:0}),d}catch(u){return x.error("[TranslationService] API fetch failed",u instanceof Error?u:{message:String(u)}),l?(x.warn("[TranslationService] Using expired cache as fallback"),this.mergeWithUrlTranslations(l.data.translations,n)):(x.warn("[TranslationService] Using critical bundle translations"),this.getCriticalTranslationsOnly())}}async fetchFromAPI(r){let o=await Ye.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(i=>{t[i]={...r[i],...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 i=0;i<o.length;i++){let n=o.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return t.toString(36)}saveToCache(r,o){try{let t=this.getCacheKey(r),i={data:o,cachedAt:Date.now(),dataHash:this.hashData(o.translations)};localStorage.setItem(t,JSON.stringify(i)),this.enableDebug&&x.debug("[TranslationService] Saved to cache:",{cacheKey:t})}catch(t){x.error("[TranslationService] Failed to save cache",t instanceof Error?t:{message:String(t)})}}getFromCache(r){try{let o=this.getCacheKey(r),t=localStorage.getItem(o);return t?JSON.parse(t):null}catch(o){return x.error("[TranslationService] Failed to read cache",o instanceof Error?o:{message:String(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){x.error("[TranslationService] Failed to refresh cache timestamp",o instanceof Error?o:{message:String(o)})}}isCacheExpired(r){return Date.now()-r.cachedAt>xt}hasValidCache(r){let o=this.getFromCache(r);return o?!this.isCacheExpired(o):!1}getCacheKey(r){return`${ro}${oo(r)}`}getCriticalTranslationsOnly(){return ge}invalidateCache(r){let o=this.getCacheKey(r);localStorage.removeItem(o),this.enableDebug&&x.debug("[TranslationService] Cache invalidated:",{cacheKey:o})}async prefetchTranslations(r){try{await this.fetchTranslations(r),this.enableDebug&&x.debug("[TranslationService] Prefetch completed")}catch(o){x.error("[TranslationService] Prefetch failed",o instanceof Error?o:{message:String(o)})}}clearAllCaches(){try{let o=Object.keys(localStorage).filter(t=>t.startsWith(ro));o.forEach(t=>localStorage.removeItem(t)),this.enableDebug&&x.debug(`[TranslationService] Cleared ${o.length} cache entries`)}catch(r){x.error("[TranslationService] Failed to clear caches",r instanceof Error?r:{message:String(r)})}}},Ze=mr.getInstance();import{createContext as wt,useContext as Ct,useEffect as io,useState as Le,useMemo as to,useCallback as vt}from"react";import{Fragment as Tt,jsx as er}from"react/jsx-runtime";var Qe=null,fr=!1,so=wt(null);function no(e,r,o){return{...e,...r,...o||{}}}function Pt(e,r,o,t,i){io(()=>{if(!t||!e||!r)return;let n=o||typeof window<"u"&&window.i18next||typeof window<"u"&&window.i18n;if(!n||!n.addResourceBundle){i&&x.debug("[TranslationsProvider] i18next not found, skipping auto-sync");return}i&&x.debug("[TranslationsProvider] Auto-syncing translations with i18next",{languages:Object.keys(e),currentLanguage:r}),Object.keys(e).forEach(l=>{e[l]&&Object.keys(e[l]).length>0&&(n.addResourceBundle(l,"translation",e[l],!0,!0),i&&x.debug(`[TranslationsProvider] Synced ${Object.keys(e[l]).length} keys for language: ${l}`))}),n.language!==r&&n.changeLanguage&&(n.changeLanguage(r),i&&x.debug(`[TranslationsProvider] Changed i18next language to: ${r}`))},[e,r,o,t,i])}var Us=({children:e,apiKey:r,crudifyEnv:o="prod",featureKeys:t,language:i="es",devTranslations:n,translationUrl:l,enableDebug:a=!1,skipAutoInit:u=!0,autoSyncI18n:h=!0,i18nInstance:d,loadingFallback:b,waitForInitialLoad:w=!0})=>{let c=to(()=>qr({publicApiKey:r,env:o,featureKeys:t,enableDebug:a}),[r,o,t,a]),s=c.publicApiKey||"",y=c.env||o||"prod",p=c.featureKeys||t,[m,f]=Le({}),[v,E]=Le(!0),[z,g]=Le(!0),[C,I]=Le(null),[A,Y]=Le(void 0),[le,Q]=Le(!1),ne=vt(async()=>{if(!s){a&&x.debug("[TranslationsProvider] No apiKey - skipping translation fetch"),E(!1),g(!1);return}if(le){a&&x.debug("[TranslationsProvider] Skipping reload - using fallback translations");return}if(Ze.hasValidCache(s)&&z&&(a&&x.debug("[TranslationsProvider] Valid cache found - not blocking initial render"),g(!1)),fr&&Qe){a&&x.debug("[TranslationsProvider] Fetch already in progress, waiting for existing promise");try{let R=await Qe;f(R),E(!1);return}catch{a&&x.warn("[TranslationsProvider] Global fetch failed, retrying")}}fr=!0,E(!0),I(null);let V;if(l)try{a&&x.debug(`[TranslationsProvider] Fetching translations from URL: ${l}`);let R=await fetch(l);if(!R.ok)throw new Error(`Failed to fetch translations: ${R.statusText}`);V=await R.json(),Y(V),a&&x.debug("[TranslationsProvider] URL translations loaded:",{keysCount:V?Object.keys(V).length:0})}catch(R){x.error("[TranslationsProvider] Failed to load URL translations",R instanceof Error?R:{message:String(R)}),V=void 0,Y(void 0)}let ee=(async()=>{try{Ze.setDebug(a);let R=await Ze.fetchTranslations({apiKey:s,crudifyEnv:y,featureKeys:p,urlTranslations:V}),S={};return Object.keys(R).forEach(W=>{let ie=ge[W]||{},re=R[W]||{};S[W]=no(ie,re,n)}),a&&x.debug("[TranslationsProvider] Loaded translations:",{languages:Object.keys(S),keysCount:Object.keys(S[i]||{}).length}),S}catch(R){x.error("[TranslationsProvider] Failed to load",R instanceof Error?R:{message:String(R)}),I(R instanceof Error?R.message:String(R)),Q(!0);let S={};return Object.keys(ge).forEach(W=>{let ie=ge[W],re=V||A||{};S[W]=no(ie,re,n)}),a&&x.debug("[TranslationsProvider] Using fallback translations (critical + URL)"),S}})();Qe=ee;try{let R=await ee;f(R)}finally{E(!1),g(!1),fr=!1,setTimeout(()=>{Qe=null},1e3)}},[s,y,p,l,n,a,i,le]);io(()=>{ne();let H=setInterval(ne,3600*1e3);return()=>clearInterval(H)},[ne]);let Oe=to(()=>(H,V)=>{let R=(m[i]||{})[H];if(!R){let S=Object.keys(m);for(let W of S)if(m[W][H]){R=m[W][H];break}}return R||(a&&x.warn(`[TranslationsProvider] Missing translation: "${H}"`),R=H),V&&typeof R=="string"&&Object.entries(V).forEach(([S,W])=>{let ie=new RegExp(`{{${S}}}`,"g");R=R.replace(ie,String(W))}),R},[m,i,a]);Pt(m,i,d,h,a);let Ie={t:Oe,language:i,availableLanguages:Object.keys(m),translations:m,isLoading:v,error:C,refreshTranslations:ne};return s?w&&z&&v?b||er("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:er("div",{children:"Loading translations..."})}):er(so.Provider,{value:Ie,children:e}):(a&&x.warn("[TranslationsProvider] No API key available. Skipping translations. Provide apiKey via props or ensure cookies are set by Lambda."),er(Tt,{children:e}))},Me=()=>{let e=Ct(so);if(!e)throw new Error("useTranslations must be used within TranslationsProvider");return e};var Rt=/^[a-zA-Z0-9\-_./\?=&%#]+$/,St=[/^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]/,/\\/],ao=(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return x.warn("Open redirect blocked (relative path)",{path:e}),r;if(!Rt.test(o))return x.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let n of St)if(n.test(t))return x.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let i=o.split("?")[0].split("/").filter(Boolean);if(i.length===0)return o;for(let n of i)if(n===".."||n.includes(":")||n.length>100)return x.warn("Open redirect blocked (suspicious path part)",{part:n}),r;return o},Et=[/^files\.nocios\.link$/,/^files\.crudia\.com$/,/^[a-z0-9][a-z0-9-]*\.nocios\.link$/,/^[a-z0-9][a-z0-9-]*\.crudia\.com$/],lo=(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(o.startsWith("/"))return ao(o,r);try{if(o.includes("..")||o.includes("//",8))return x.warn("Redirect blocked (dangerous path pattern)",{url:o}),r;let t=new URL(o);if(t.protocol!=="https:")return x.warn("Redirect blocked (non-HTTPS protocol)",{url:o}),r;let i=t.hostname.toLowerCase();return Et.some(l=>l.test(i))?o:(x.warn("Redirect blocked (untrusted domain)",{url:o,hostname:i}),r)}catch{return x.warn("Redirect blocked (invalid URL)",{url:o}),r}},Hs=(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let i=decodeURIComponent(t);return ao(i,r)}catch(o){return x.warn("Error parsing redirect parameter",o instanceof Error?{errorMessage:o.message}:{message:String(o)}),r}};import{Box as co,Typography as kt}from"@mui/material";import It from"@mui/icons-material/CheckCircle";import At from"@mui/icons-material/RadioButtonUnchecked";import{jsx as Ne,jsxs as Dt}from"react/jsx-runtime";var Lt=({message:e,valid:r})=>Dt(co,{sx:{display:"flex",alignItems:"center",gap:.5,py:.25},children:[r?Ne(It,{sx:{fontSize:16,color:"success.main"}}):Ne(At,{sx:{fontSize:16,color:"text.disabled"}}),Ne(kt,{variant:"caption",sx:{color:r?"success.main":"text.secondary",transition:"color 0.2s ease"},children:e})]}),Ft=({requirements:e,show:r=!0})=>!r||e.length===0?null:Ne(co,{sx:{mt:.5,mb:1,px:.5},children:e.map((o,t)=>Ne(Lt,{message:o.message,valid:o.valid},t))}),uo=Ft;var Bt=/[A-Z]/,_t=/[a-z]/,zt=/[0-9]/,Ot=/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/,Ut=/^[A-Za-z0-9]+$/;function po(e,r){return r.map(o=>{let t=!0;switch(o.type){case"minLength":t=e.length>=Number(o.value??0);break;case"alphanumeric":t=e.length>0&&Ut.test(e);break;case"uppercase":t=Bt.test(e);break;case"lowercase":t=_t.test(e);break;case"number":t=zt.test(e);break;case"special":t=Ot.test(e);break;default:t=!0}return{message:o.message,valid:t,enforce:!!o.enforce}})}function go(e){return e.filter(r=>r.enforce).every(r=>r.valid)}var mo=[{type:"minLength",value:8,message:"passwordRequirements.minLength",enforce:!0},{type:"uppercase",message:"passwordRequirements.uppercase",enforce:!0},{type:"lowercase",message:"passwordRequirements.lowercase",enforce:!0},{type:"number",message:"passwordRequirements.number",enforce:!0},{type:"special",message:"passwordRequirements.special",enforce:!0}];import{Box as Rn,Typography as Sn}from"@mui/material";import{createContext as Nt,useContext as Wt,useMemo as hr}from"react";import{useState as yr,useEffect as Mt}from"react";var fo=(e,r)=>{let[o,t]=yr({}),[i,n]=yr(!1),[l,a]=yr(null);return Mt(()=>{if(r&&Object.keys(r).length>0){t(r),n(!1),a(null);return}if(!e){t({}),n(!1),a(null);return}let u=!1;return n(!0),a(null),fetch(e).then(h=>{if(!h.ok)throw new Error(`Failed to load translations: ${h.status}`);return h.json()}).then(h=>{u||(t(h),n(!1))}).catch(h=>{u||(x.error("[I18nProvider] Failed to load translations from URL",h instanceof Error?h:{message:String(h),url:e}),a(h instanceof Error?h.message:String(h)),t({}),n(!1))}),()=>{u=!0}},[e,r]),{translations:o,loading:i,error:l}};import{jsx as yo}from"react/jsx-runtime";var ho=Nt(null),Ht=()=>{try{return Me()}catch{return null}},Vt=(e,r)=>{if(r.includes(".")){let o=r.split(".").reduce((t,i)=>t&&typeof t=="object"?t[i]:void 0,e);if(o!==void 0)return o}if(e&&e[r])return e[r]},bo=({children:e,translations:r,translationsUrl:o,language:t="en"})=>{let n=Ht()?.translations?.[t]||{},{translations:l,loading:a}=fo(o,r),u=hr(()=>({...n,...l,...r||{}}),[n,l,r]),h=hr(()=>(b,w)=>{let c=Vt(u,b);return c==null&&(c=b),w&&typeof c=="string"&&Object.entries(w).forEach(([s,y])=>{c=c.replace(new RegExp(`{{${s}}}`,"g"),y)}),typeof c=="string"?c:b},[u]),d=hr(()=>({t:h,language:t}),[h,t]);return a?yo("div",{children:"Loading translations..."}):yo(ho.Provider,{value:d,children:e})},oe=()=>{let e=Wt(ho);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};import{createContext as $t,useContext as jt,useReducer as Kt,useEffect as br,useCallback as qt}from"react";import{jsx as Xt}from"react/jsx-runtime";var xo={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function Gt(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),i=t.toString()?`?${t.toString()}`:window.location.pathname;try{window.history.replaceState({},"",i)}catch{}return o;case"SET_SEARCH_PARAMS":return{...e,searchParams:r.payload};case"CLEAR_SEARCH_PARAMS":return{...e,searchParams:{}};case"UPDATE_FORM_DATA":return{...e,formData:{...e.formData,...r.payload},errors:{...e.errors,...Object.keys(r.payload).reduce((n,l)=>({...n,[l]: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:xo.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 wo=$t(void 0),Co=({children:e,initialScreen:r="login",config:o,autoReadFromCookies:t=!0})=>{let[i,n]=Kt(Gt,{...xo,currentScreen:r});br(()=>{n({type:"INIT_CONFIG",payload:(()=>{let s={};if(t)try{let y=Kr();y.configSource!=="none"&&y.logo&&(s.logo=y.logo)}catch(y){x.error("Error reading configuration",y instanceof Error?y:{message:String(y)})}return{publicApiKey:o?.publicApiKey,env:o?.env,appName:o?.appName,logo:o?.logo||s.logo,loginActions:o?.loginActions}})()})},[o,t]),br(()=>{let c=new URLSearchParams(window.location.search),s={};c.forEach((y,p)=>{s[p]=y}),Object.keys(s).length>0&&n({type:"SET_SEARCH_PARAMS",payload:s}),r==="checkCode"&&s.email&&n({type:"UPDATE_FORM_DATA",payload:{email:s.email,code:s.code||""}}),r==="resetPassword"&&s.link&&n({type:"SET_SEARCH_PARAMS",payload:s})},[r]),br(()=>{let c=Gr.subscribe(s=>{(s.type==="LOGOUT"||s.type==="SESSION_EXPIRED")&&(x.debug("LoginStateProvider: Clearing state due to auth event",{type:s.type}),n({type:"CLEAR_SEARCH_PARAMS"}),n({type:"RESET_FORM"}))});return()=>c()},[]);let l=(c,s)=>{n({type:"SET_SCREEN",payload:{screen:c,params:s}})},a=c=>{n({type:"UPDATE_FORM_DATA",payload:c})},u=(c,s)=>{n({type:"SET_ERRORS",payload:{[c]:s}})},h=()=>{n({type:"CLEAR_ERRORS"})},d=c=>{n({type:"SET_LOADING",payload:c})},b=qt(()=>{n({type:"CLEAR_SEARCH_PARAMS"})},[]),w={state:i,dispatch:n,setScreen:l,updateFormData:a,setFieldError:u,clearErrors:h,setLoading:d,clearSearchParams:b};return Xt(wo.Provider,{value:w,children:e})},rr=()=>{let e=jt(wo);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};import{useEffect as Jt,useRef as Yt}from"react";import{Typography as xr,TextField as vo,Button as Zt,Box as We,CircularProgress as Qt,Alert as en,Link as Po}from"@mui/material";import{Fragment as on,jsx as te,jsxs as He}from"react/jsx-runtime";var rn=({onScreenChange:e,onExternalNavigate:r,onLoginSuccess:o,onError:t,redirectUrl:i="/"})=>{let{state:n,updateFormData:l,setFieldError:a,clearErrors:u,setLoading:h}=rr(),{login:d}=be(),b=oe(),{t:w}=b,c="i18n"in b?b.i18n:void 0,s=Yt(null),y=Xr(w,{currentLanguage:c?.language,enableDebug:!1}),p=()=>{if(n.searchParams.redirect)try{let g=decodeURIComponent(n.searchParams.redirect);return lo(g,i||"/")}catch{}return i||"/"};Jt(()=>{let g=setTimeout(()=>{s.current&&s.current.focus()},100);return()=>clearTimeout(g)},[]);let m=g=>y.translateError({code:g.code,message:g.message,field:g.field}),f=async()=>{if(!n.loading){if(!n.formData.username.trim()){a("username",w("login.usernameRequired"));return}if(!n.formData.password.trim()){a("password",w("login.passwordRequired"));return}u(),h(!0);try{let g=await d(n.formData.username,n.formData.password);if(h(!1),g.success){let C=p();o&&o(g.data,C)}else{let C=g.rawResponse||g;v(C)}}catch(g){h(!1);let I=J(g).map(m);a("global",I),t&&t(I.join(", "))}}},v=g=>{let C=J(g),I=[];C.forEach(A=>{A.field?a(A.field,m(A)):I.push(m(A))}),I.length>0&&a("global",I)};return He(on,{children:[He(We,{component:"form",noValidate:!0,onSubmit:g=>{g.preventDefault(),f()},onKeyDown:g=>{g.key==="Enter"&&!n.loading&&(g.preventDefault(),f())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[He(We,{sx:{mb:1},children:[te(xr,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:w("login.usernameOrEmailLabel")}),te(vo,{fullWidth:!0,id:"email",name:"email",type:"email",value:n.formData.username,disabled:n.loading,onChange:g=>l({username:g.target.value}),error:!!n.errors.username,helperText:n.errors.username,autoComplete:"email",placeholder:w("login.usernameOrEmailPlaceholder"),inputRef:s,required:!0})]}),He(We,{sx:{mb:1},children:[te(xr,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:w("login.passwordLabel")}),te(vo,{fullWidth:!0,id:"password",name:"password",type:"password",value:n.formData.password,disabled:n.loading,onChange:g=>l({password:g.target.value}),error:!!n.errors.password,helperText:n.errors.password,autoComplete:"current-password",placeholder:w("login.passwordPlaceholder"),required:!0})]}),n.config.loginActions?.includes("forgotPassword")&&te(We,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:te(Po,{sx:{cursor:"pointer"},onClick:()=>{e?.("forgotPassword",n.searchParams)},variant:"body2",color:"secondary",children:w("login.forgotPasswordLink")})}),te(Zt,{disabled:n.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:n.loading?te(Qt,{size:20}):w("login.loginButton")})]}),te(We,{children:n.errors.global&&n.errors.global.length>0&&n.errors.global.map((g,C)=>te(en,{variant:"filled",sx:{mt:2},severity:"error",children:te("div",{children:g})},C))}),n.config.loginActions?.includes("createUser")&&He(xr,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[w("login.noAccountPrompt")," ",te(Po,{sx:{cursor:"pointer"},onClick:()=>{let C=`/public/users/create${Object.keys(n.searchParams).length>0?`?${new URLSearchParams(n.searchParams).toString()}`:""}`;r?.(C)},fontWeight:"medium",color:"secondary",children:w("login.signUpLink")})]})]})},To=rn;import{useState as Fe,useEffect as tn,useRef as nn}from"react";import{Typography as De,TextField as sn,Button as Ro,Box as xe,CircularProgress as an,Alert as ln,Link as wr}from"@mui/material";import{Fragment as So,jsx as N,jsxs as Se}from"react/jsx-runtime";var cn=({onScreenChange:e,onError:r})=>{let{crudify:o}=he(),[t,i]=Fe(""),[n,l]=Fe(!1),[a,u]=Fe([]),[h,d]=Fe(null),[b,w]=Fe(!1),[c,s]=Fe(!1),y=nn(null),{t:p}=oe();tn(()=>{y.current&&!b&&!c&&y.current.focus()},[b,c]);let m=C=>{let I=[`errors.auth.${C.code}`,`errors.data.${C.code}`,`errors.system.${C.code}`,`errors.${C.code}`,`forgotPassword.${C.code.toLowerCase()}`];for(let A of I){let Y=p(A);if(Y!==A)return Y}return C.message||p("base.errors.errorUnknown")},f=C=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(C),v=async()=>{if(!(n||!o)){if(u([]),d(null),!t){d(p("errors.REQUIRED",{field:p("base.fields.email")}));return}if(!f(t)){d(p("base.errors.invalidEmail"));return}l(!0);try{let C=[{operation:"requestPasswordReset",data:{email:t}}],I=await o.transaction(C);if(I.success)I.data&&I.data.existingCodeValid?s(!0):w(!0);else{let Y=J(I).map(m);u(Y)}}catch(C){let A=J(C).map(m);u(A),r&&r(A.join(", "))}finally{l(!1)}}},E=()=>{e?.("login")},z=()=>{if(b||c){e?.("checkCode",{email:t});return}if(!t){d(p("errors.REQUIRED",{field:p("base.fields.email")}));return}if(!f(t)){d(p("base.errors.invalidEmail"));return}e?.("checkCode",{email:t})};return b||c?N(So,{children:Se(xe,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[Se(xe,{sx:{mb:2},children:[N(De,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:p(c?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),N(De,{variant:"body2",sx:{color:c?"success.main":"grey.600"},children:p("forgotPassword.checkEmailInstructions")})]}),N(Ro,{type:"button",onClick:z,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:p("forgotPassword.enterCodeLink")}),N(xe,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:N(wr,{sx:{cursor:"pointer"},onClick:E,variant:"body2",color:"secondary",children:p("base.btn.back")})})]})}):Se(So,{children:[Se(xe,{component:"form",noValidate:!0,onSubmit:C=>{C.preventDefault(),v()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Se(xe,{sx:{mb:2},children:[N(De,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:p("forgotPassword.title")}),N(De,{variant:"body2",sx:{color:"grey.600"},children:p("forgotPassword.instructions")})]}),Se(xe,{sx:{mb:1},children:[N(De,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:p("base.fields.email")}),N(sn,{fullWidth:!0,id:"email",name:"email",type:"email",value:t,disabled:n,onChange:C=>i(C.target.value),error:!!h,helperText:h,autoComplete:"email",placeholder:p("forgotPassword.emailPlaceholder"),required:!0,autoFocus:!0,inputRef:y})]}),N(Ro,{disabled:n,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?N(an,{size:20}):p("forgotPassword.sendCodeButton")}),Se(xe,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[N(wr,{sx:{cursor:"pointer"},onClick:E,variant:"body2",color:"secondary",children:p("base.btn.back")}),N(De,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),N(wr,{sx:{cursor:"pointer"},onClick:z,variant:"body2",color:"secondary",children:p("login.alreadyHaveCodeLink")})]})]}),N(xe,{children:a.length>0&&a.map((C,I)=>N(ln,{variant:"filled",sx:{mt:2},severity:"error",children:C},I))})]})},Eo=cn;import{useState as $,useEffect as ko,useMemo as Cr}from"react";import{Typography as or,TextField as Io,Button as dn,Box as we,CircularProgress as Ao,Alert as Lo,Link as un,IconButton as Fo,InputAdornment as Do}from"@mui/material";import Bo from"@mui/icons-material/Visibility";import _o from"@mui/icons-material/VisibilityOff";import{Fragment as gn,jsx as F,jsxs as Ve}from"react/jsx-runtime";var pn=({onScreenChange:e,onError:r,searchParams:o,onResetSuccess:t,passwordRules:i})=>{let{crudify:n}=he(),[l,a]=$(""),[u,h]=$(""),[d,b]=$(!1),[w,c]=$([]),[s,y]=$(null),[p,m]=$(null),[f,v]=$(""),[E,z]=$(""),[g,C]=$(!1),[I,A]=$(!0),[Y,le]=$(!1),[Q,ne]=$(null),[Oe,Ie]=$(!1),[H,V]=$(!1),[ee,R]=$(!1),{t:S}=oe(),W=Cr(()=>(i||mo).map(D=>({...D,message:S(D.message)})),[i,S]),ie=Cr(()=>po(l,W),[l,W]),re=Cr(()=>go(ie),[ie]),Ue=l===u,Re=k=>{let D=[`errors.auth.${k.code}`,`errors.data.${k.code}`,`errors.system.${k.code}`,`errors.${k.code}`,`resetPassword.${k.code.toLowerCase()}`];for(let M of D){let q=S(M);if(q!==M)return q}return k.message||S("base.errors.errorUnknown")},Ae=k=>o?o instanceof URLSearchParams?o.get(k):o[k]||null:null;ko(()=>{if(o){if(o){let k=Ae("fromCodeVerification"),D=Ae("email"),M=Ae("code");if(k==="true"&&D&&M){v(D),z(M),C(!0),le(!0),A(!1);return}let q=Ae("link");if(q)try{let G=decodeURIComponent(q),[X,ye]=G.split("/");if(X&&ye&&X.length===6){z(X),v(ye),C(!1),ne({email:ye,code:X});return}}catch{}if(D&&M){v(D),z(M),C(!1),ne({email:D,code:M});return}}c([S("resetPassword.invalidCode")]),A(!1),setTimeout(()=>e?.("forgotPassword"),3e3)}},[o,n,S,e]),ko(()=>{n&&Q&&!Oe&&(Ie(!0),(async(D,M)=>{try{let q=[{operation:"validatePasswordResetCode",data:{email:D,codePassword:M}}],G=await n.transaction(q);if(G.data&&Array.isArray(G.data)){let X=G.data[0];if(X&&X.response&&X.response.status==="OK"){le(!0);return}}if(G.success)le(!0);else{let ye=J(G).map(Re);c(ye),setTimeout(()=>e?.("forgotPassword"),3e3)}}catch(q){let X=J(q).map(Re);c(X),setTimeout(()=>e?.("forgotPassword"),3e3)}finally{A(!1),ne(null),Ie(!1)}})(Q.email,Q.code))},[n,Q,S,e]);let Xe=async()=>{if(d||!n)return;c([]),y(null),m(null);let k=!1;if(l?re||(y(S("resetPassword.passwordRequirementsNotMet")),k=!0):(y(S("resetPassword.newPasswordRequired")),k=!0),u?Ue||(m(S("resetPassword.passwordsDoNotMatch")),k=!0):(m(S("resetPassword.confirmPasswordRequired")),k=!0),!k){b(!0);try{let D=[{operation:"validateAndResetPassword",data:{email:f,codePassword:E,newPassword:l}}],M=await n.transaction(D);if(M.success)c([]),setTimeout(()=>{t?.()},1e3);else{let G=J(M).map(Re);c(G)}}catch(D){let q=J(D).map(Re);c(q),r&&r(q.join(", "))}b(!1)}},Or=()=>{g?e?.("checkCode",{email:f}):e?.("forgotPassword")};return I?F(we,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:F(Ao,{})}):Y?Ve(gn,{children:[Ve(we,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Ve(we,{sx:{mb:2},children:[F(or,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:S("resetPassword.title")}),F(or,{variant:"body2",sx:{color:"grey.600"},children:S("resetPassword.instructions")})]}),Ve(we,{sx:{mb:1},children:[F(or,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:S("resetPassword.newPasswordLabel")}),F(Io,{fullWidth:!0,id:"newPassword",name:"newPassword",type:H?"text":"password",value:l,disabled:d,onChange:k=>a(k.target.value),error:!!s,helperText:s,autoComplete:"new-password",placeholder:S("resetPassword.newPasswordPlaceholder"),required:!0,InputProps:{endAdornment:F(Do,{position:"end",children:F(Fo,{"aria-label":S(H?"base.btn.hidePassword":"base.btn.showPassword"),onClick:()=>V(!H),edge:"end",size:"small",disabled:d,children:H?F(_o,{}):F(Bo,{})})})}}),F(uo,{requirements:ie,show:l.length>0})]}),Ve(we,{sx:{mb:1},children:[F(or,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:S("resetPassword.confirmPasswordLabel")}),F(Io,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:ee?"text":"password",value:u,disabled:d,onChange:k=>h(k.target.value),error:!!p,helperText:p,autoComplete:"new-password",placeholder:S("resetPassword.confirmPasswordPlaceholder"),required:!0,InputProps:{endAdornment:F(Do,{position:"end",children:F(Fo,{"aria-label":S(ee?"base.btn.hidePassword":"base.btn.showPassword"),onClick:()=>R(!ee),edge:"end",size:"small",disabled:d,children:ee?F(_o,{}):F(Bo,{})})})}})]}),F(dn,{disabled:d||!re||!Ue||!l||!u,type:"button",onClick:Xe,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:d?F(Ao,{size:20}):S("resetPassword.resetPasswordButton")}),F(we,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:F(un,{sx:{cursor:"pointer"},onClick:Or,variant:"body2",color:"secondary",children:S("base.btn.back")})})]}),F(we,{children:w.length>0&&w.map((k,D)=>F(Lo,{variant:"filled",sx:{mt:2},severity:"error",children:k},D))})]}):F(we,{children:w.length>0&&w.map((k,D)=>F(Lo,{variant:"filled",sx:{mt:2},severity:"error",children:k},D))})},zo=pn;import{useState as $e,useEffect as Oo,useRef as mn}from"react";import{Typography as vr,TextField as fn,Button as yn,Box as je,CircularProgress as hn,Alert as bn,Link as xn}from"@mui/material";import{Fragment as Cn,jsx as de,jsxs as tr}from"react/jsx-runtime";var wn=({onScreenChange:e,onError:r,searchParams:o})=>{let{crudify:t}=he(),[i,n]=$e(""),[l,a]=$e(!1),[u,h]=$e([]),[d,b]=$e(null),[w,c]=$e(""),s=mn(null),{t:y}=oe(),p=g=>o?o instanceof URLSearchParams?o.get(g):o[g]||null:null,m=g=>{let C=[`errors.auth.${g.code}`,`errors.data.${g.code}`,`errors.system.${g.code}`,`errors.${g.code}`,`checkCode.${g.code.toLowerCase()}`];for(let I of C){let A=y(I);if(A!==I)return A}return g.message||y("base.errors.errorUnknown")};Oo(()=>{let g=p("email");g?c(g):e?.("forgotPassword")},[o,e]),Oo(()=>{s.current&&s.current.focus()},[]);let f=async()=>{if(!(l||!t)){if(h([]),b(null),!i){b(y("checkCode.codeRequired"));return}if(i.length!==6){b(y("checkCode.codeRequired"));return}a(!0);try{let g=[{operation:"validatePasswordResetCode",data:{email:w,codePassword:i}}],C=await t.transaction(g);if(C.success)e?.("resetPassword",{email:w,code:i,fromCodeVerification:"true"});else{let A=J(C).map(m);h(A),a(!1)}}catch(g){let I=J(g).map(m);h(I),a(!1),r&&r(I.join(", "))}}},v=()=>{e?.("forgotPassword")},E=g=>{let C=g.target.value.replace(/\D/g,"").slice(0,6);n(C)};return tr(Cn,{children:[tr(je,{component:"form",noValidate:!0,onSubmit:g=>{g.preventDefault(),f()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[tr(je,{sx:{mb:2},children:[de(vr,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:y("checkCode.title")}),de(vr,{variant:"body2",sx:{color:"grey.600"},children:y("checkCode.instructions")})]}),tr(je,{sx:{mb:1},children:[de(vr,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:y("checkCode.codeLabel")}),de(fn,{fullWidth:!0,id:"code",name:"code",type:"text",value:i,disabled:l,onChange:E,error:!!d,helperText:d,placeholder:y("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0,autoFocus:!0,inputRef:s})]}),de(yn,{disabled:l||i.length!==6,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:l?de(hn,{size:20}):y("checkCode.verifyButton")}),de(je,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:de(xn,{sx:{cursor:"pointer"},onClick:v,variant:"body2",color:"secondary",children:y("base.btn.back")})})]}),de(je,{children:u.length>0&&u.map((g,C)=>de(bn,{sx:{mt:2},severity:"error",children:g},C))})]})},Uo=wn;import{Box as vn,CircularProgress as Pn,Alert as Mo,Typography as Pr}from"@mui/material";import{Fragment as Tn,jsx as Be,jsxs as No}from"react/jsx-runtime";var Wo=({children:e,fallback:r})=>{let{isLoading:o,error:t,isInitialized:i}=he(),{t:n}=oe();return o?r||No(vn,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[Be(Pn,{}),Be(Pr,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):t?Be(Mo,{severity:"error",sx:{mt:2},children:No(Pr,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",t]})}):i?Be(Tn,{children:e}):Be(Mo,{severity:"warning",sx:{mt:2},children:Be(Pr,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as se,jsxs as In}from"react/jsx-runtime";var En=({onScreenChange:e,onExternalNavigate:r,onLoginSuccess:o,onError:t,redirectUrl:i="/",passwordRules:n})=>{let{t:l}=oe(),{state:a,setScreen:u}=rr(),{config:h}=be(),{showNotification:d}=Jr(),b=(c,s)=>{let y=s;c==="login"?y={}:c==="forgotPassword"&&!s&&(y={}),u(c,y),e?.(c,y)},w=()=>{let c={onScreenChange:b,onExternalNavigate:r,onError:t,redirectUrl:i};switch(a.currentScreen){case"forgotPassword":return se(Eo,{...c});case"checkCode":return se(Uo,{...c,searchParams:a.searchParams});case"resetPassword":return se(zo,{...c,searchParams:a.searchParams,passwordRules:n,onResetSuccess:()=>{let s=l("resetPassword.successMessage");d(s,"success"),b("login")}});default:return se(To,{...c,onLoginSuccess:o})}};return In(Wo,{children:[se(Rn,{sx:{display:"flex",justifyContent:"center",mb:3},children:se("img",{src:h.logo||"https://logos.crudia.com/nocios-default.png",alt:l("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:c=>{let s=c.target;s.src="https://logos.crudia.com/nocios-default.png"}})}),!h.logo&&h.appName&&se(Sn,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:h.appName}),w()]})},kn=({translations:e,translationsUrl:r,language:o="en",initialScreen:t="login",autoReadFromCookies:i=!0,...n})=>{let{config:l}=be();return se(bo,{translations:e,translationsUrl:r,language:o,children:se(Yr,{config:l,children:se(Co,{config:l,initialScreen:t,autoReadFromCookies:i,children:se(En,{...n})})})})},ul=kn;import{Box as Z,Card as Ho,CardContent as Vo,Typography as ae,Chip as nr,Avatar as An,Divider as Ln,CircularProgress as Fn,Alert as $o,List as Dn,ListItem as Tr,ListItemText as Rr,ListItemIcon as Bn,Collapse as _n,IconButton as Sr}from"@mui/material";import{Person as zn,Email as On,Badge as Un,Security as Mn,Schedule as Nn,AccountCircle as Wn,ExpandMore as Hn,ExpandLess as Vn,Info as $n}from"@mui/icons-material";import{useState as jn}from"react";import{Fragment as Gn,jsx as T,jsxs as B}from"react/jsx-runtime";var Kn=({showExtendedData:e=!0,showProfileCard:r=!0,autoRefresh:o=!0})=>{let{userProfile:t,loading:i,error:n,extendedData:l,refreshProfile:a}=Zr({autoFetch:o,retryOnError:!0,maxRetries:3}),[u,h]=jn(!1);if(i)return B(Z,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[T(Fn,{}),T(ae,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return B($o,{severity:"error",action:T(Sr,{color:"inherit",size:"small",onClick:a,children:T(ae,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!t)return T($o,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let d=l?.displayData||{},b=l?.totalFields||0,w=f=>{if(!f)return"No disponible";try{return new Date(f).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return f}},c=(f,v)=>v==null?"No disponible":typeof v=="boolean"?v?"S\xED":"No":Array.isArray(v)?v.length>0?v.join(", "):"Ninguno":typeof v=="object"?JSON.stringify(v,null,2):String(v),s=[{key:"id",label:"ID",icon:T(Un,{})},{key:"email",label:"Email",icon:T(On,{})},{key:"username",label:"Usuario",icon:T(zn,{})},{key:"fullName",label:"Nombre completo",icon:T(Wn,{})},{key:"role",label:"Rol",icon:T(Mn,{})}],y=[{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=[...s.map(f=>f.key),...y.map(f=>f.key),"permissions"],m=Object.keys(d).filter(f=>!p.includes(f)).map(f=>({key:f,label:f}));return B(Z,{children:[r&&T(Ho,{sx:{mb:2},children:B(Vo,{children:[B(Z,{display:"flex",alignItems:"center",mb:2,children:[T(An,{src:d.avatar,sx:{width:56,height:56,mr:2},children:d.fullName?.[0]||d.username?.[0]||d.email?.[0]}),B(Z,{children:[T(ae,{variant:"h6",children:d.fullName||d.username||d.email}),T(ae,{variant:"body2",color:"text.secondary",children:d.role||"Usuario"}),d.isActive!==void 0&&T(nr,{label:d.isActive?"Activo":"Inactivo",color:d.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),T(Z,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:s.map(({key:f,label:v,icon:E})=>d[f]?B(Z,{display:"flex",alignItems:"center",children:[T(Z,{sx:{mr:1,color:"text.secondary"},children:E}),B(Z,{children:[T(ae,{variant:"caption",color:"text.secondary",children:v}),T(ae,{variant:"body2",children:c(f,d[f])})]})]},f):null)}),d.permissions&&Array.isArray(d.permissions)&&d.permissions.length>0&&B(Z,{mt:2,children:[T(ae,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),B(Z,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[d.permissions.slice(0,5).map((f,v)=>T(nr,{label:f,size:"small",variant:"outlined"},v)),d.permissions.length>5&&T(nr,{label:`+${d.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&T(Ho,{children:B(Vo,{children:[B(Z,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[B(ae,{variant:"h6",display:"flex",alignItems:"center",children:[T($n,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),T(nr,{label:`${b} campos totales`,size:"small"})]}),B(Dn,{dense:!0,children:[y.map(({key:f,label:v})=>d[f]!==void 0&&B(Tr,{divider:!0,children:[T(Bn,{children:T(Nn,{fontSize:"small"})}),T(Rr,{primary:v,secondary:f.includes("At")||f.includes("Login")?w(d[f]):c(f,d[f])})]},f)),m.length>0&&B(Gn,{children:[T(Ln,{sx:{my:1}}),T(Tr,{children:T(Rr,{primary:B(Z,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[B(ae,{variant:"subtitle2",children:["Campos Personalizados (",m.length,")"]}),T(Sr,{size:"small",onClick:()=>h(!u),children:u?T(Vn,{}):T(Hn,{})})]})})}),T(_n,{in:u,children:m.map(({key:f,label:v})=>T(Tr,{sx:{pl:4},children:T(Rr,{primary:v,secondary:c(f,d[f])})},f))})]})]}),B(Z,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[B(ae,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",w(d.updatedAt)]}),T(Sr,{size:"small",onClick:a,disabled:i,children:T(ae,{variant:"caption",children:"Actualizar"})})]})]})})]})},qn=Kn;var jo=["create","read","update","delete"],Ko=["create","read","update","delete"];import{useRef as hi}from"react";import{useTranslation as bi}from"react-i18next";import{Box as ar,Typography as Qo,Button as xi,Stack as wi,Alert as et,Divider as Ci}from"@mui/material";import{Add as vi}from"@mui/icons-material";import{forwardRef as ni}from"react";import{useTranslation as ii}from"react-i18next";import{Box as Ee,FormControl as si,InputLabel as ai,Select as li,MenuItem as ci,IconButton as di,Typography as _e,FormHelperText as ui,Stack as sr,Paper as Zo,Divider as pi,Button as Ar}from"@mui/material";import{Delete as gi,SelectAll as mi,ClearAll as fi}from"@mui/icons-material";import{useState as qo,useEffect as Go,useRef as Xo}from"react";import{useTranslation as Xn}from"react-i18next";import{Box as ir,Typography as Ke,Button as Jo,Stack as Er,FormControlLabel as Jn,FormHelperText as Yo,Switch as Yn,ToggleButton as kr,ToggleButtonGroup as Zn}from"@mui/material";import{CheckCircle as Qn,Cancel as ei,SelectAll as ri,ClearAll as oi}from"@mui/icons-material";import{jsx as O,jsxs as Ce}from"react/jsx-runtime";var ti=({value:e,onChange:r,availableFields:o,error:t,disabled:i=!1})=>{let{t:n}=Xn(),[l,a]=qo("custom"),[u,h]=qo(!1),d=Xo(null);Go(()=>{u&&d.current?.scrollIntoView({behavior:"smooth",block:"start"})},[u]);let b=Xo(!1);Go(()=>{let p=e||{allow:[],owner_allow:[],deny:[]},m=new Set(o),f=(p.allow||[]).filter(g=>m.has(g)),v=(p.owner_allow||[]).filter(g=>m.has(g)),E=(p.deny||[]).filter(g=>m.has(g));o.forEach(g=>{!f.includes(g)&&!v.includes(g)&&!E.includes(g)&&E.push(g)});let z={allow:f,owner_allow:v,deny:E};JSON.stringify(z)!==JSON.stringify(p)&&r(z),f.length===o.length?a("all"):E.length===o.length?a("none"):a("custom")},[o,e]);let w=()=>{b.current=!0,r({allow:[...o],owner_allow:[],deny:[]}),a("all"),setTimeout(()=>{b.current=!1},0)},c=()=>{b.current=!0,r({allow:[],owner_allow:[],deny:[...o]}),a("none"),setTimeout(()=>{b.current=!1},0)},s=p=>e?.allow?.includes(p)?"allow":e?.owner_allow?.includes(p)?"owner_allow":"deny",y=(p,m)=>{b.current=!0;let f=new Set(e?.allow||[]),v=new Set(e?.owner_allow||[]),E=new Set(e?.deny||[]);f.delete(p),v.delete(p),E.delete(p),m==="allow"&&f.add(p),m==="owner_allow"&&v.add(p),m==="deny"&&E.add(p),r({allow:Array.from(f),owner_allow:Array.from(v),deny:Array.from(E)}),a("custom"),setTimeout(()=>{b.current=!1},0)};return o.length===0?Ce(ir,{children:[O(Ke,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("publicPolicies.fields.conditions.label")}),O(Ke,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("publicPolicies.fields.conditions.noFieldsAvailable")}),t&&O(Yo,{error:!0,sx:{mt:1},children:t})]}):Ce(ir,{children:[O(Ke,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("publicPolicies.fields.conditions.label")}),Ce(Er,{direction:"row",spacing:1,alignItems:"center",sx:{mb:u?3:1},children:[O(Jo,{variant:l==="all"?"contained":"outlined",startIcon:O(ri,{}),onClick:w,disabled:i,size:"small",sx:{minWidth:120,...l==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("publicPolicies.fields.conditions.allFields")}),O(Jo,{variant:l==="none"?"contained":"outlined",startIcon:O(oi,{}),onClick:c,disabled:i,size:"small",sx:{minWidth:120,...l==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("publicPolicies.fields.conditions.noFields")}),O(ir,{sx:{display:"flex",alignItems:"center",px:1.5,py:.35,borderRadius:"999px",backgroundColor:"#f3f4f6",border:"1px solid #d1d9e0"},children:O(Jn,{control:O(Yn,{size:"small",checked:u,onChange:()=>h(p=>!p),disabled:i,color:"primary",sx:{transform:"scale(1.15)",transformOrigin:"center",m:0}}),label:n("publicPolicies.fields.conditions.customEdit"),labelPlacement:"end",sx:{ml:0,".MuiFormControlLabel-label":{fontSize:"0.75rem"}}})})]}),u&&Ce(ir,{ref:d,sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[O(Ke,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("publicPolicies.fields.conditions.help")}),O(Er,{spacing:1,children:o.map(p=>{let m=s(p);return Ce(Er,{direction:"row",spacing:1,alignItems:"center",children:[O(Ke,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:p}),Ce(Zn,{value:m,exclusive:!0,size:"small",children:[Ce(kr,{value:"allow",onClick:()=>y(p,"allow"),disabled:i,sx:{px:2,color:m==="allow"?"#ffffff":"#6b7280",backgroundColor:m==="allow"?"#16a34a":"#f3f4f6",borderColor:m==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:m==="allow"?"#15803d":"#e5e7eb",borderColor:m==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[O(Qn,{sx:{fontSize:16,mr:.5}}),n("publicPolicies.fields.conditions.states.allow")]}),O(kr,{value:"owner_allow",onClick:()=>y(p,"owner_allow"),disabled:i,sx:{px:2,color:m==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:m==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:m==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:m==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:m==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("publicPolicies.fields.conditions.states.ownerAllow")}),Ce(kr,{value:"deny",onClick:()=>y(p,"deny"),disabled:i,sx:{px:2,color:m==="deny"?"#ffffff":"#6b7280",backgroundColor:m==="deny"?"#dc2626":"#f3f4f6",borderColor:m==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:m==="deny"?"#b91c1c":"#e5e7eb",borderColor:m==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[O(ei,{sx:{fontSize:16,mr:.5}}),n("publicPolicies.fields.conditions.states.deny")]})]})]},p)})})]}),t&&O(Yo,{error:!0,sx:{mt:1},children:t})]})},Ir=ti;import{jsx as U,jsxs as j}from"react/jsx-runtime";var yi=ni(({policy:e,onChange:r,onRemove:o,availableFields:t,isSubmitting:i=!1,usedActions:n,error:l},a)=>{let{t:u}=ii(),h=new Set(Array.from(n||[]));h.delete(e.action);let d=jo.map(b=>({value:b,label:u(`publicPolicies.fields.action.options.${b}`)}));return j(Zo,{ref:a,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[j(Ee,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[U(_e,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:u("publicPolicies.policyTitle")}),U(di,{onClick:o,size:"small",disabled:i,"aria-label":u("publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:U(gi,{})})]}),j(sr,{spacing:1,children:[U(sr,{direction:{xs:"column",md:"row"},spacing:2,children:U(Ee,{sx:{flex:1,minWidth:200},children:j(si,{fullWidth:!0,children:[U(ai,{children:u("publicPolicies.fields.action.label")}),U(li,{value:e.action,label:u("publicPolicies.fields.action.label"),disabled:i,onChange:b=>{let w=b.target.value,c={...e,action:w};w==="delete"?(c.permission="deny",delete c.fields):(c.fields={allow:[],owner_allow:[],deny:t},delete c.permission),r(c)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:d.map(b=>{let w=h.has(b.value);return U(ci,{value:b.value,disabled:w,children:b.label},b.value)})}),l&&U(ui,{error:!0,children:l})]})})}),e.action==="delete"?j(Ee,{children:[U(_e,{variant:"body2",color:"text.secondary",sx:{mb:2},children:u("publicPolicies.fields.conditions.label")}),j(sr,{direction:"row",spacing:1,sx:{mb:1},children:[U(Ar,{variant:e.permission==="*"?"contained":"outlined",startIcon:U(mi,{}),onClick:()=>r({...e,permission:"*"}),disabled:i,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:u("publicPolicies.fields.conditions.allFields")}),U(Ar,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>r({...e,permission:"owner"}),disabled:i,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:u("publicPolicies.fields.conditions.states.ownerAllow")}),U(Ar,{variant:e.permission==="deny"?"contained":"outlined",startIcon:U(fi,{}),onClick:()=>r({...e,permission:"deny"}),disabled:i,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:u("publicPolicies.fields.conditions.noFields")})]})]}):U(Ir,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:b=>r({...e,fields:b}),availableFields:t,disabled:i}),U(Zo,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?j(_e,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(Ee,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[u("publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):j(sr,{spacing:.5,divider:U(pi,{sx:{borderColor:"#e5e7eb"}}),children:[j(_e,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(Ee,{component:"span",sx:{color:"#16a34a"},children:[u("publicPolicies.fields.conditions.states.allow"),":"]})," ",(e?.fields?.allow||[]).join(", ")||"-"]}),j(_e,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(Ee,{component:"span",sx:{color:"#0ea5e9"},children:[u("publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(e?.fields?.owner_allow||[]).join(", ")||"-"]}),j(_e,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(Ee,{component:"span",sx:{color:"#dc2626"},children:[u("publicPolicies.fields.conditions.states.deny"),":"]})," ",(e?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),Lr=yi;import{Fragment as Ri,jsx as ue,jsxs as lr}from"react/jsx-runtime";var Pi=()=>typeof globalThis<"u"&&globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,Ti=({policies:e,onChange:r,availableFields:o,errors:t,isSubmitting:i=!1})=>{let{t:n}=bi(),l=hi({}),a=new Set((e||[]).map(s=>s.action).filter(Boolean)),u=Ko.filter(s=>!a.has(s)),h=u.length>0,d=()=>{let s=u[0]||"create",y={id:Pi(),action:s};s==="delete"?y.permission="deny":y.fields={allow:[],owner_allow:[],deny:o};let p=[...e||[],y];r(p),setTimeout(()=>{let m=p.length-1,f=l.current[m];f&&f.scrollIntoView({behavior:"smooth",block:"center"})},100)},b=s=>{let y=[...e];y.splice(s,1),r(y)},w=(()=>{if(!t)return null;if(typeof t=="string")return t;let s=t._error;return typeof s=="string"?s:null})(),c=new Set((e||[]).map(s=>s.action));return lr(Ri,{children:[ue(Ci,{sx:{borderColor:"#e0e4e7"}}),lr(ar,{children:[ue(ar,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:lr(ar,{children:[ue(Qo,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("publicPolicies.title")}),ue(Qo,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("publicPolicies.description")})]})}),w&&ue(et,{severity:"error",sx:{mb:3},children:w}),lr(wi,{spacing:3,children:[(e||[]).length===0?ue(et,{severity:"info",children:n("publicPolicies.noPolicies")}):e.map((s,y)=>ue(Lr,{ref:p=>{l.current[y]=p},policy:s,onChange:p=>{let m=[...e];m[y]=p,r(m)},onRemove:()=>b(y),availableFields:o,isSubmitting:i,usedActions:c,error:typeof t=="object"&&t!==null&&!("_error"in t)&&s.id in t?t[s.id]:void 0},s.id)),h&&ue(ar,{children:ue(xi,{type:"button",variant:"outlined",startIcon:ue(vi,{}),onClick:d,disabled:i,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("publicPolicies.addPolicy")})})]})]})]})},Xl=Ti;import{useState as Fr}from"react";import{Button as cr,TextField as rt,Box as ze,Alert as qe,Typography as ve,CircularProgress as Dr}from"@mui/material";import{jsx as _,jsxs as me}from"react/jsx-runtime";function oc(){let[e,r]=Fr(""),[o,t]=Fr(""),[i,n]=Fr(!1),{isAuthenticated:l,isLoading:a,error:u,login:h,logout:d,refreshTokens:b,clearError:w,isExpiringSoon:c,expiresIn:s}=be(),y=async f=>{if(f.preventDefault(),!e||!o)return;(await h(e,o)).success&&(r(""),t(""),n(!1))},p=async()=>{await d()},m=async()=>{await b()};return l?me(ze,{sx:{maxWidth:600,mx:"auto",p:3},children:[_(ve,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),_(qe,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),me(ze,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[_(ve,{variant:"h6",gutterBottom:!0,children:"Token Status"}),me(ve,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(s/1e3/60)," minutes"]}),c&&_(qe,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),me(ze,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[_(cr,{variant:"contained",onClick:m,disabled:a,startIcon:a?_(Dr,{size:16}):null,children:"Refresh Tokens"}),_(cr,{variant:"outlined",color:"error",onClick:p,disabled:a,children:"Logout"})]}),u&&_(qe,{severity:"error",sx:{mt:2},onClose:w,children:u})]}):me(ze,{sx:{maxWidth:400,mx:"auto",p:3},children:[_(ve,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),_(qe,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),i?me("form",{onSubmit:y,children:[_(rt,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:f=>r(f.target.value),margin:"normal",required:!0,autoComplete:"email"}),_(rt,{fullWidth:!0,label:"Password",type:"password",value:o,onChange:f=>t(f.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),_(cr,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:a,startIcon:a?_(Dr,{size:16}):null,sx:{mt:3,mb:2},children:a?"Logging in...":"Login"})]}):_(cr,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),u&&_(qe,{severity:"error",sx:{mt:2},onClose:w,children:u})]})}function tc(){let{isAuthenticated:e,isLoading:r,isExpiringSoon:o,expiresIn:t}=be();return r?me(ze,{sx:{display:"flex",alignItems:"center",gap:1},children:[_(Dr,{size:16}),_(ve,{variant:"caption",children:"Loading session..."})]}):e?me(ze,{children:[_(ve,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),o&&me(ve,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(t/1e3/60)," min"]})]}):_(ve,{variant:"caption",color:"text.secondary",children:"Not logged in"})}import Si from"@mui/material/TextField";import Ei from"@mui/material/CircularProgress";import ot from"@mui/material/InputAdornment";import ki from"@mui/material/IconButton";import Ii from"@mui/icons-material/Refresh";import{jsx as Pe}from"react/jsx-runtime";var Ai=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),Li=({html:e})=>Pe("span",{dangerouslySetInnerHTML:{__html:Ai(e)}}),pc=({config:e,value:r,onChange:o,label:t,error:i=!1,helperText:n,readOnly:l=!1,disabled:a=!1})=>{let{value:u,loading:h,error:d,regenerate:b}=Qr(e,{autoFetch:!r,onSuccess:m=>{o?.(m)}}),w=r||u,c=i||!!d,s=d||n,y=c&&s&&(s.toLowerCase().includes("duplicate")||s.toLowerCase().includes("duplicado")||s.toLowerCase().includes("duplicada")||s.toLowerCase().includes("unique")||s.toLowerCase().includes("\xFAnico")||s.toLowerCase().includes("unico")||s.toLowerCase().includes("\xFAnica")||s.toLowerCase().includes("unica")||s.toLowerCase().includes("already exists")||s.toLowerCase().includes("ya existe")||s.toLowerCase().includes("e11000"));return Pe(Si,{label:t,fullWidth:!0,value:w,error:c,helperText:s?Pe(Li,{html:s}):" ",disabled:a,InputProps:{readOnly:!0,startAdornment:h?Pe(ot,{position:"start",children:Pe(Ei,{size:20})}):void 0,endAdornment:y&&!h?Pe(ot,{position:"end",children:Pe(ki,{edge:"end",onClick:async()=>{!a&&!h&&await b()},disabled:a,size:"small",color:"error","aria-label":"regenerar c\xF3digo",title:"Regenerar c\xF3digo",children:Pe(Ii,{})})}):void 0}})};import Br,{useCallback as fe,useRef as tt,useState as Ge}from"react";import ke from"@mui/material/Box";import Te from"@mui/material/Typography";import _r from"@mui/material/IconButton";import Fi from"@mui/material/LinearProgress";import dr from"@mui/material/CircularProgress";import it from"@mui/material/Chip";import Di from"@mui/material/Paper";import Bi from"@mui/material/List";import _i from"@mui/material/ListItem";import zi from"@mui/material/ListItemText";import Oi from"@mui/material/ListItemSecondaryAction";import Ui from"@mui/material/FormHelperText";import Mi from"@mui/material/Dialog";import Ni from"@mui/material/DialogTitle";import Wi from"@mui/material/DialogContent";import Hi from"@mui/material/DialogActions";import nt from"@mui/material/Button";import Vi from"@mui/icons-material/CloudUpload";import $i from"@mui/icons-material/InsertDriveFile";import ji from"@mui/icons-material/Image";import Ki from"@mui/icons-material/PictureAsPdf";import qi from"@mui/icons-material/Delete";import Gi from"@mui/icons-material/Refresh";import Xi from"@mui/icons-material/Restore";import Ji from"@mui/icons-material/CheckCircle";import Yi from"@mui/icons-material/Error";import $c from"@mui/icons-material/BrokenImage";import{jsx as P,jsxs as pe}from"react/jsx-runtime";var Zi=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),Qi=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]}`},es=e=>e.startsWith("image/")?P(ji,{color:"primary"}):e==="application/pdf"?P(Ki,{color:"error"}):P($i,{color:"action"}),rs=(e,r)=>{switch(e){case"completed":return P(Ji,{color:"success",fontSize:"small"});case"error":return P(Yi,{color:"error",fontSize:"small"});case"uploading":case"pending":return P(dr,{size:16});case"removing":return P(dr,{size:16,color:"error"});case"pendingDeletion":return P(it,{label:r("base.file.pendingDeletion"),size:"small",color:"warning",variant:"outlined",sx:{fontSize:"0.65rem",height:20}});default:return null}},os=({file:e,baseUrl:r,disabled:o,onRemove:t,onRestore:i,onRetry:n})=>{let{t:l}=Me(),[a,u]=Ge(!1),h=e.status==="pendingDeletion",d=!o&&e.status!=="uploading"&&e.status!=="removing"&&!h,b=!o&&h,w=!o&&e.status==="error"&&e.file,c=e.contentType.startsWith("image/"),s=e.visibility==="public"||e.filePath?.startsWith("public/")||e.filePath?.startsWith(r),p=!e.filePath||!s?null:e.filePath.startsWith("http://")||e.filePath.startsWith("https://")||e.filePath.startsWith(r)?e.filePath:`${r}${e.filePath}`,m=e.status==="completed"&&p,f=()=>c&&m&&!a?P(ke,{component:m?"a":"div",href:p||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:m?"pointer":"default",transition:"all 0.2s ease",flexShrink:0,"&:hover":m?{borderColor:"primary.main",transform:"scale(1.05)"}:{}},children:P("img",{src:p,alt:e.name,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>u(!0)})}):P(ke,{component:m?"a":"div",href:p||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:m?"pointer":"default",transition:"all 0.2s ease",flexShrink:0,textDecoration:"none","&:hover":m?{borderColor:"primary.main",bgcolor:"action.hover"}:{}},children:es(e.contentType)});return pe(_i,{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:[f(),P(zi,{primary:pe(ke,{sx:{display:"flex",alignItems:"center",gap:1},children:[P(Te,{variant:"body2",noWrap:!0,sx:{maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",textDecoration:h?"line-through":"none",opacity:h?.6:1},children:e.name}),rs(e.status,l)]}),secondary:pe(ke,{sx:{opacity:h?.6:1},children:[e.size>0&&P(Te,{variant:"caption",color:"text.secondary",children:Qi(e.size)}),e.status==="uploading"&&P(Fi,{variant:"determinate",value:e.progress,sx:{mt:.5,height:4,borderRadius:2}}),e.status==="error"&&e.errorMessage&&P(Te,{variant:"caption",color:"error",display:"block",children:e.errorMessage}),m&&P(Te,{variant:"caption",color:"primary",display:"block",component:"a",href:p||void 0,target:"_blank",rel:"noopener noreferrer",sx:{cursor:"pointer",textDecoration:"underline","&:hover":{textDecoration:"none"}},children:l(c?"base.file.clickToPreview":"base.file.clickToDownload")})]})}),pe(Oi,{children:[w&&P(_r,{edge:"end",size:"small",onClick:()=>n(e.id),color:"primary",title:l("base.file.restore"),children:P(Gi,{fontSize:"small"})}),b&&P(_r,{edge:"end",size:"small",onClick:()=>i(e.id),color:"primary",title:l("base.file.restore"),children:P(Xi,{fontSize:"small"})}),d&&P(_r,{edge:"end",size:"small",onClick:()=>t(e.id),color:"error",title:l("base.file.delete"),children:P(qi,{fontSize:"small"})})]})]})};var qc=({label:e,accept:r,maxFileSize:o=10*1024*1024,multiple:t=!1,maxFiles:i,minFiles:n=0,required:l=!1,disabled:a=!1,error:u=!1,helperText:h,onChange:d,onValidation:b,initialFiles:w,placeholder:c,showFileList:s=!0,visibility:y="private",showPreview:p=!0,baseUrl:m,onDeletionHandlersReady:f,mode:v="create"})=>{let{t:E}=Me(),z=tt(null),[g,C]=Ge(!1),[I,A]=Ge(!1),[Y,le]=Ge(null),[Q,ne]=Ge(!1),Oe=t?i:1,Ie=l?Math.max(n,1):n,H={acceptedTypes:r,maxFileSize:o,maxFiles:Oe,minFiles:Ie,visibility:y,mode:v,onFilesChange:L=>{let ce=L.filter(Je=>Je.status==="completed"&&Je.filePath).map(Je=>{let gr=Je.filePath;return gr.startsWith("/")?gr:`/${gr}`});d?.(ce)}},{files:V,isUploading:ee,addFiles:R,removeFile:S,restoreFile:W,retryUpload:ie,isValid:re,validationError:Ue,validationErrorKey:Re,validationErrorParams:Ae,initializeFiles:Xe,isTouched:Or,markAsTouched:k,isSubmitted:D,markAsSubmitted:M,getPreviewUrl:q,commitDeletions:G,restorePendingDeletions:X,hasPendingDeletions:ye,deleteFileImmediately:Ur,activeFiles:Ps,activeFileCount:ct,waitForUploads:Mr,completedFilePaths:Nr}=eo(H),Wr=fe(()=>Nr,[Nr]),Hr=tt(!1);Br.useEffect(()=>{w&&w.length>0&&!Hr.current&&(Hr.current=!0,Xe(w,m))},[w,Xe,m]),Br.useEffect(()=>{b?.(re,Ue)},[re,Ue,b]),Br.useEffect(()=>{f?.({commitDeletions:G,restorePendingDeletions:X,hasPendingDeletions:ye,markAsSubmitted:M,isValid:re,isUploading:ee,waitForUploads:Mr,getCompletedFilePaths:Wr})},[f,G,X,ye,M,re,ee,Mr,Wr]);let dt=fe(L=>{k();let ce=L.target.files;ce&&ce.length>0&&R(ce),z.current&&(z.current.value="")},[R,k]),ut=fe(()=>{a||z.current?.click()},[a]),pt=fe(L=>{L.preventDefault(),L.stopPropagation(),a||C(!0)},[a]),gt=fe(L=>{L.preventDefault(),L.stopPropagation(),C(!1)},[]),mt=fe(L=>{if(L.preventDefault(),L.stopPropagation(),C(!1),a)return;k();let ce=L.dataTransfer.files;ce&&ce.length>0&&R(ce)},[a,R,k]),ft=fe(async L=>{(await S(L)).needsConfirmation&&(le(L),A(!0))},[S]),yt=fe(async()=>{if(Y){ne(!0);try{let L=await Ur(Y);L.success||x.error("Error deleting file",{error:L.error})}finally{ne(!1),A(!1),le(null)}}},[Y,Ur]),Vr=fe(()=>{A(!1),le(null)},[]),ht=r?.join(",")||"",bt=!a&&(t||ct===0),$r=D&&!re,pr=u||$r,jr=h||($r&&Re?E(Re,Ae):null);return pe(ke,{sx:{width:"100%"},children:[e&&pe(Te,{variant:"body2",sx:{mb:1,fontWeight:500,color:pr?"error.main":"text.primary"},children:[e,l&&P("span",{style:{color:"red"},children:" *"})]}),P("input",{ref:z,type:"file",accept:ht,multiple:t,onChange:dt,disabled:a,style:{display:"none"}}),bt&&pe(Di,{variant:"outlined",onClick:ut,onDragOver:pt,onDragLeave:gt,onDrop:mt,sx:{p:3,textAlign:"center",cursor:a?"not-allowed":"pointer",borderStyle:"dashed",borderWidth:2,borderColor:g?"primary.main":pr?"error.main":"divider",bgcolor:g?"primary.lighter":a?"action.disabledBackground":"background.paper",transition:"all 0.2s ease","&:hover":a?{}:{borderColor:"primary.main",bgcolor:"action.hover"}},children:[P(Vi,{sx:{fontSize:48,color:g?"primary.main":a?"action.disabled":"action.active",mb:1}}),P(Te,{variant:"body2",color:a?"text.disabled":"text.secondary",children:c||E(g?"base.file.dropHere":"base.file.dragOrClick")}),r&&r.length>0&&!g&&P(ke,{sx:{mt:1,display:"flex",gap:.5,justifyContent:"center",flexWrap:"wrap"},children:r.map(L=>P(it,{label:L.split("/")[1]?.toUpperCase()||L,size:"small",variant:"outlined",sx:{fontSize:"0.7rem"}},L))})]}),s&&V.length>0&&P(Bi,{dense:!0,sx:{mt:1,p:0},children:V.map(L=>P(os,{file:L,baseUrl:m,disabled:a,onRemove:ft,onRestore:W,onRetry:ie},L.id))}),ee&&pe(ke,{sx:{display:"flex",alignItems:"center",gap:1,mt:1},children:[P(dr,{size:16}),P(Te,{variant:"caption",color:"text.secondary",children:E("base.file.uploading")})]}),jr&&P(Ui,{error:pr,sx:{mt:.5},dangerouslySetInnerHTML:{__html:Zi(jr)}}),pe(Mi,{open:I,onClose:Q?void 0:Vr,children:[P(Ni,{children:E("base.file.confirmDelete.title")}),P(Wi,{children:P(Te,{children:E("base.file.confirmDelete.message")})}),pe(Hi,{children:[P(nt,{onClick:Vr,disabled:Q,children:E("base.file.confirmDelete.cancel")}),P(nt,{onClick:yt,color:"error",variant:"contained",disabled:Q,startIcon:Q?P(dr,{size:16,color:"inherit"}):void 0,children:E(Q?"base.file.deleting":"base.file.confirmDelete.confirm")})]})]})]})};import{useCallback as ts,useRef as ns,useEffect as is}from"react";import st from"@mui/material/Box";import at from"@mui/material/Typography";import lt from"@mui/material/FormHelperText";import{MDXEditor as ss,headingsPlugin as as,listsPlugin as ls,quotePlugin as cs,thematicBreakPlugin as ds,markdownShortcutPlugin as us,linkPlugin as ps,linkDialogPlugin as gs,tablePlugin as ms,toolbarPlugin as fs,UndoRedo as ys,BoldItalicUnderlineToggles as hs,BlockTypeSelect as bs,CreateLink as xs,InsertTable as ws,ListsToggle as Cs,Separator as ur}from"@mdxeditor/editor";import"@mdxeditor/editor/style.css";import{Fragment as vs,jsx as K,jsxs as zr}from"react/jsx-runtime";var td=({label:e,value:r="",onChange:o,required:t=!1,disabled:i=!1,error:n=!1,helperText:l,placeholder:a="Write here...",minHeight:u=200,maxHeight:h=500})=>{let d=ns(null);is(()=>{d.current&&d.current.getMarkdown()!==r&&d.current.setMarkdown(r||"")},[r]);let b=ts(w=>{o?.(w)},[o]);return zr(st,{sx:{width:"100%"},children:[e&&zr(at,{component:"label",sx:{display:"block",mb:.5,fontSize:"0.875rem",fontWeight:500,color:n?"error.main":"text.primary"},children:[e,t&&K(at,{component:"span",color:"error.main",sx:{ml:.5},children:"*"})]}),K(st,{sx:{border:1,borderColor:n?"error.main":"divider",borderRadius:1,overflow:"hidden",opacity:i?.6:1,pointerEvents:i?"none":"auto","& .mdxeditor":{minHeight:u,maxHeight:h,overflow:"auto"},"& .mdxeditor-toolbar":{borderBottom:1,borderColor:"divider",backgroundColor:"background.default"},"& .mdxeditor-root-contenteditable":{padding:2,minHeight:u-50}},children:K(ss,{ref:d,markdown:r||"",onChange:b,placeholder:a,readOnly:i,plugins:[as(),ls(),cs(),ds(),us(),ps(),gs(),ms(),fs({toolbarContents:()=>zr(vs,{children:[K(ys,{}),K(ur,{}),K(hs,{}),K(ur,{}),K(bs,{}),K(ur,{}),K(Cs,{}),K(ur,{}),K(xs,{}),K(ws,{})]})})]})}),l&&K(lt,{error:n,sx:{mx:0,mt:.5},children:l}),!l&&K(lt,{sx:{mx:0,mt:.5},children:"\xA0"})]})};export{ge as a,Rs as b,Ss as c,mr as d,Ze as e,Us as f,Me as g,ao as h,lo as i,Hs as j,uo as k,po as l,go as m,mo as n,ul as o,qn as p,jo as q,Ko as r,Xl as s,oc as t,tc as u,pc as v,qc as w,td as x};