@nocios/crudify-components 2.0.26 → 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:{}},Ss=()=>Object.keys(ge),Es=e=>ge[e]||ge.es;import Ye from"@nocios/crudify-sdk";var ro="crudify_translations_",wt=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>wt}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 Ct,useContext as vt,useEffect as io,useState as Le,useMemo as to,useCallback as Pt}from"react";import{Fragment as Rt,jsx as er}from"react/jsx-runtime";var Qe=null,fr=!1,so=Ct(null);function no(e,r,o){return{...e,...r,...o||{}}}function Tt(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 Ms=({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),[L,Y]=Le(void 0),[le,ee]=Le(!1),ne=Pt(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 S=await Qe;f(S),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 S=await fetch(l);if(!S.ok)throw new Error(`Failed to fetch translations: ${S.statusText}`);V=await S.json(),Y(V),a&&x.debug("[TranslationsProvider] URL translations loaded:",{keysCount:V?Object.keys(V).length:0})}catch(S){x.error("[TranslationsProvider] Failed to load URL translations",S instanceof Error?S:{message:String(S)}),V=void 0,Y(void 0)}let Z=(async()=>{try{Ze.setDebug(a);let S=await Ze.fetchTranslations({apiKey:s,crudifyEnv:y,featureKeys:p,urlTranslations:V}),P={};return Object.keys(S).forEach(H=>{let ie=ge[H]||{},re=S[H]||{};P[H]=no(ie,re,n)}),a&&x.debug("[TranslationsProvider] Loaded translations:",{languages:Object.keys(P),keysCount:Object.keys(P[i]||{}).length}),P}catch(S){x.error("[TranslationsProvider] Failed to load",S instanceof Error?S:{message:String(S)}),I(S instanceof Error?S.message:String(S)),ee(!0);let P={};return Object.keys(ge).forEach(H=>{let ie=ge[H],re=V||L||{};P[H]=no(ie,re,n)}),a&&x.debug("[TranslationsProvider] Using fallback translations (critical + URL)"),P}})();Qe=Z;try{let S=await Z;f(S)}finally{E(!1),g(!1),fr=!1,setTimeout(()=>{Qe=null},1e3)}},[s,y,p,l,n,a,i,le]);io(()=>{ne();let W=setInterval(ne,3600*1e3);return()=>clearInterval(W)},[ne]);let Oe=to(()=>(W,V)=>{let S=(m[i]||{})[W];if(!S){let P=Object.keys(m);for(let H of P)if(m[H][W]){S=m[H][W];break}}return S||(a&&x.warn(`[TranslationsProvider] Missing translation: "${W}"`),S=W),V&&typeof S=="string"&&Object.entries(V).forEach(([P,H])=>{let ie=new RegExp(`{{${P}}}`,"g");S=S.replace(ie,String(H))}),S},[m,i,a]);Tt(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(Rt,{children:e}))},Me=()=>{let e=vt(so);if(!e)throw new Error("useTranslations must be used within TranslationsProvider");return e};var St=/^[a-zA-Z0-9\-_./\?=&%#]+$/,Et=[/^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(!St.test(o))return x.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let n of Et)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},kt=[/^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 kt.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}},Vs=(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 It}from"@mui/material";import At from"@mui/icons-material/CheckCircle";import Lt from"@mui/icons-material/RadioButtonUnchecked";import{jsx as Ne,jsxs as Bt}from"react/jsx-runtime";var Ft=({message:e,valid:r})=>Bt(co,{sx:{display:"flex",alignItems:"center",gap:.5,py:.25},children:[r?Ne(At,{sx:{fontSize:16,color:"success.main"}}):Ne(Lt,{sx:{fontSize:16,color:"text.disabled"}}),Ne(It,{variant:"caption",sx:{color:r?"success.main":"text.secondary",transition:"color 0.2s ease"},children:e})]}),Dt=({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(Ft,{message:o.message,valid:o.valid},t))}),uo=Dt;var _t=/[A-Z]/,zt=/[a-z]/,Ot=/[0-9]/,Ut=/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/,Mt=/^[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&&Mt.test(e);break;case"uppercase":t=_t.test(e);break;case"lowercase":t=zt.test(e);break;case"number":t=Ot.test(e);break;case"special":t=Ut.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 Sn,Typography as En}from"@mui/material";import{createContext as Wt,useContext as Ht,useMemo as hr}from"react";import{useState as yr,useEffect as Nt}from"react";var fo=(e,r)=>{let[o,t]=yr({}),[i,n]=yr(!1),[l,a]=yr(null);return Nt(()=>{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=Wt(null),Vt=()=>{try{return Me()}catch{return null}},$t=(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=Vt()?.translations?.[t]||{},{translations:l,loading:a}=fo(o,r),u=hr(()=>({...n,...l,...r||{}}),[n,l,r]),h=hr(()=>(b,w)=>{let c=$t(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=Ht(ho);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};import{createContext as jt,useContext as Kt,useReducer as qt,useEffect as br,useCallback as Gt}from"react";import{jsx as Jt}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 Xt(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=jt(void 0),Co=({children:e,initialScreen:r="login",config:o,autoReadFromCookies:t=!0})=>{let[i,n]=qt(Xt,{...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=Gt(()=>{n({type:"CLEAR_SEARCH_PARAMS"})},[]),w={state:i,dispatch:n,setScreen:l,updateFormData:a,setFieldError:u,clearErrors:h,setLoading:d,clearSearchParams:b};return Jt(wo.Provider,{value:w,children:e})},rr=()=>{let e=Kt(wo);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};import{useEffect as Yt,useRef as Zt}from"react";import{Typography as xr,TextField as vo,Button as Qt,Box as We,CircularProgress as en,Alert as rn,Link as Po}from"@mui/material";import{Fragment as tn,jsx as te,jsxs as He}from"react/jsx-runtime";var on=({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=Zt(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||"/"};Yt(()=>{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(L=>{L.field?a(L.field,m(L)):I.push(m(L))}),I.length>0&&a("global",I)};return He(tn,{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(Qt,{disabled:n.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:n.loading?te(en,{size:20}):w("login.loginButton")})]}),te(We,{children:n.errors.global&&n.errors.global.length>0&&n.errors.global.map((g,C)=>te(rn,{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=on;import{useState as Fe,useEffect as nn,useRef as sn}from"react";import{Typography as De,TextField as an,Button as Ro,Box as xe,CircularProgress as ln,Alert as cn,Link as wr}from"@mui/material";import{Fragment as So,jsx as N,jsxs as Se}from"react/jsx-runtime";var dn=({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=sn(null),{t:p}=oe();nn(()=>{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 L of I){let Y=p(L);if(Y!==L)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 L=J(C).map(m);u(L),r&&r(L.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(an,{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(ln,{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(cn,{variant:"filled",sx:{mt:2},severity:"error",children:C},I))})]})},Eo=dn;import{useState as $,useEffect as ko,useMemo as Cr}from"react";import{Typography as or,TextField as Io,Button as un,Box as we,CircularProgress as Ao,Alert as Lo,Link as pn,IconButton as Fo,InputAdornment as Do,Tooltip as Bo}from"@mui/material";import _o from"@mui/icons-material/Visibility";import zo from"@mui/icons-material/VisibilityOff";import{Fragment as mn,jsx as A,jsxs as Ve}from"react/jsx-runtime";var gn=({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,L]=$(!0),[Y,le]=$(!1),[ee,ne]=$(null),[Oe,Ie]=$(!1),[W,V]=$(!1),[Z,S]=$(!1),{t:P}=oe(),H=Cr(()=>(i||mo).map(D=>({...D,message:P(D.message)})),[i,P]),ie=Cr(()=>po(l,H),[l,H]),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=P(M);if(q!==M)return q}return k.message||P("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),L(!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([P("resetPassword.invalidCode")]),L(!1),setTimeout(()=>e?.("forgotPassword"),3e3)}},[o,n,P,e]),ko(()=>{n&&ee&&!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{L(!1),ne(null),Ie(!1)}})(ee.email,ee.code))},[n,ee,P,e]);let Xe=async()=>{if(d||!n)return;c([]),y(null),m(null);let k=!1;if(l?re||(y(P("resetPassword.passwordRequirementsNotMet")),k=!0):(y(P("resetPassword.newPasswordRequired")),k=!0),u?Ue||(m(P("resetPassword.passwordsDoNotMatch")),k=!0):(m(P("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?A(we,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:A(Ao,{})}):Y?Ve(mn,{children:[Ve(we,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Ve(we,{sx:{mb:2},children:[A(or,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:P("resetPassword.title")}),A(or,{variant:"body2",sx:{color:"grey.600"},children:P("resetPassword.instructions")})]}),Ve(we,{sx:{mb:1},children:[A(or,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:P("base.fields.password")}),A(Io,{fullWidth:!0,id:"newPassword",name:"newPassword",type:W?"text":"password",value:l,disabled:d,onChange:k=>a(k.target.value),error:!!s,helperText:s,autoComplete:"new-password",placeholder:P("base.fields.confirmPassword"),required:!0,InputProps:{endAdornment:A(Do,{position:"end",children:A(Bo,{title:P(W?"base.btn.hidePassword":"base.btn.showPassword"),children:A("span",{children:A(Fo,{"aria-label":P(W?"base.btn.hidePassword":"base.btn.showPassword"),onClick:()=>V(!W),edge:"end",size:"small",disabled:d,children:W?A(zo,{}):A(_o,{})})})})})}}),A(uo,{requirements:ie,show:l.length>0})]}),Ve(we,{sx:{mb:1},children:[A(or,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:P("resetPassword.confirmPasswordLabel")}),A(Io,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:Z?"text":"password",value:u,disabled:d,onChange:k=>h(k.target.value),error:!!p,helperText:p,autoComplete:"new-password",placeholder:P("resetPassword.confirmPasswordPlaceholder"),required:!0,InputProps:{endAdornment:A(Do,{position:"end",children:A(Bo,{title:P(Z?"base.btn.hidePassword":"base.btn.showPassword"),children:A("span",{children:A(Fo,{"aria-label":P(Z?"base.btn.hidePassword":"base.btn.showPassword"),onClick:()=>S(!Z),edge:"end",size:"small",disabled:d,children:Z?A(zo,{}):A(_o,{})})})})})}})]}),A(un,{disabled:d||!re||!Ue||!l||!u,type:"button",onClick:Xe,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:d?A(Ao,{size:20}):P("resetPassword.resetPasswordButton")}),A(we,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:A(pn,{sx:{cursor:"pointer"},onClick:Or,variant:"body2",color:"secondary",children:P("base.btn.back")})})]}),A(we,{children:w.length>0&&w.map((k,D)=>A(Lo,{variant:"filled",sx:{mt:2},severity:"error",children:k},D))})]}):A(we,{children:w.length>0&&w.map((k,D)=>A(Lo,{variant:"filled",sx:{mt:2},severity:"error",children:k},D))})},Oo=gn;import{useState as $e,useEffect as Uo,useRef as fn}from"react";import{Typography as vr,TextField as yn,Button as hn,Box as je,CircularProgress as bn,Alert as xn,Link as wn}from"@mui/material";import{Fragment as vn,jsx as de,jsxs as tr}from"react/jsx-runtime";var Cn=({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=fn(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 L=y(I);if(L!==I)return L}return g.message||y("base.errors.errorUnknown")};Uo(()=>{let g=p("email");g?c(g):e?.("forgotPassword")},[o,e]),Uo(()=>{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 L=J(C).map(m);h(L),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(vn,{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(yn,{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(hn,{disabled:l||i.length!==6,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:l?de(bn,{size:20}):y("checkCode.verifyButton")}),de(je,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:de(wn,{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(xn,{sx:{mt:2},severity:"error",children:g},C))})]})},Mo=Cn;import{Box as Pn,CircularProgress as Tn,Alert as No,Typography as Pr}from"@mui/material";import{Fragment as Rn,jsx as Be,jsxs as Wo}from"react/jsx-runtime";var Ho=({children:e,fallback:r})=>{let{isLoading:o,error:t,isInitialized:i}=he(),{t:n}=oe();return o?r||Wo(Pn,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[Be(Tn,{}),Be(Pr,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):t?Be(No,{severity:"error",sx:{mt:2},children:Wo(Pr,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",t]})}):i?Be(Rn,{children:e}):Be(No,{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 An}from"react/jsx-runtime";var kn=({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(Mo,{...c,searchParams:a.searchParams});case"resetPassword":return se(Oo,{...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 An(Ho,{children:[se(Sn,{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(En,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:h.appName}),w()]})},In=({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(kn,{...n})})})})},pl=In;import{Box as Q,Card as Vo,CardContent as $o,Typography as ae,Chip as nr,Avatar as Ln,Divider as Fn,CircularProgress as Dn,Alert as jo,List as Bn,ListItem as Tr,ListItemText as Rr,ListItemIcon as _n,Collapse as zn,IconButton as Sr}from"@mui/material";import{Person as On,Email as Un,Badge as Mn,Security as Nn,Schedule as Wn,AccountCircle as Hn,ExpandMore as Vn,ExpandLess as $n,Info as jn}from"@mui/icons-material";import{useState as Kn}from"react";import{Fragment as Xn,jsx as R,jsxs as B}from"react/jsx-runtime";var qn=({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]=Kn(!1);if(i)return B(Q,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[R(Dn,{}),R(ae,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return B(jo,{severity:"error",action:R(Sr,{color:"inherit",size:"small",onClick:a,children:R(ae,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!t)return R(jo,{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:R(Mn,{})},{key:"email",label:"Email",icon:R(Un,{})},{key:"username",label:"Usuario",icon:R(On,{})},{key:"fullName",label:"Nombre completo",icon:R(Hn,{})},{key:"role",label:"Rol",icon:R(Nn,{})}],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(Q,{children:[r&&R(Vo,{sx:{mb:2},children:B($o,{children:[B(Q,{display:"flex",alignItems:"center",mb:2,children:[R(Ln,{src:d.avatar,sx:{width:56,height:56,mr:2},children:d.fullName?.[0]||d.username?.[0]||d.email?.[0]}),B(Q,{children:[R(ae,{variant:"h6",children:d.fullName||d.username||d.email}),R(ae,{variant:"body2",color:"text.secondary",children:d.role||"Usuario"}),d.isActive!==void 0&&R(nr,{label:d.isActive?"Activo":"Inactivo",color:d.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),R(Q,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:s.map(({key:f,label:v,icon:E})=>d[f]?B(Q,{display:"flex",alignItems:"center",children:[R(Q,{sx:{mr:1,color:"text.secondary"},children:E}),B(Q,{children:[R(ae,{variant:"caption",color:"text.secondary",children:v}),R(ae,{variant:"body2",children:c(f,d[f])})]})]},f):null)}),d.permissions&&Array.isArray(d.permissions)&&d.permissions.length>0&&B(Q,{mt:2,children:[R(ae,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),B(Q,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[d.permissions.slice(0,5).map((f,v)=>R(nr,{label:f,size:"small",variant:"outlined"},v)),d.permissions.length>5&&R(nr,{label:`+${d.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&R(Vo,{children:B($o,{children:[B(Q,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[B(ae,{variant:"h6",display:"flex",alignItems:"center",children:[R(jn,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),R(nr,{label:`${b} campos totales`,size:"small"})]}),B(Bn,{dense:!0,children:[y.map(({key:f,label:v})=>d[f]!==void 0&&B(Tr,{divider:!0,children:[R(_n,{children:R(Wn,{fontSize:"small"})}),R(Rr,{primary:v,secondary:f.includes("At")||f.includes("Login")?w(d[f]):c(f,d[f])})]},f)),m.length>0&&B(Xn,{children:[R(Fn,{sx:{my:1}}),R(Tr,{children:R(Rr,{primary:B(Q,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[B(ae,{variant:"subtitle2",children:["Campos Personalizados (",m.length,")"]}),R(Sr,{size:"small",onClick:()=>h(!u),children:u?R($n,{}):R(Vn,{})})]})})}),R(zn,{in:u,children:m.map(({key:f,label:v})=>R(Tr,{sx:{pl:4},children:R(Rr,{primary:v,secondary:c(f,d[f])})},f))})]})]}),B(Q,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[B(ae,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",w(d.updatedAt)]}),R(Sr,{size:"small",onClick:a,disabled:i,children:R(ae,{variant:"caption",children:"Actualizar"})})]})]})})]})},Gn=qn;var Ko=["create","read","update","delete"],qo=["create","read","update","delete"];import{useRef as bi}from"react";import{useTranslation as xi}from"react-i18next";import{Box as ar,Typography as et,Button as wi,Stack as Ci,Alert as rt,Divider as vi}from"@mui/material";import{Add as Pi}from"@mui/icons-material";import{forwardRef as ii}from"react";import{useTranslation as si}from"react-i18next";import{Box as Ee,FormControl as ai,InputLabel as li,Select as ci,MenuItem as di,IconButton as ui,Typography as _e,FormHelperText as pi,Stack as sr,Paper as Qo,Divider as gi,Button as Ar}from"@mui/material";import{Delete as mi,SelectAll as fi,ClearAll as yi}from"@mui/icons-material";import{useState as Go,useEffect as Xo,useRef as Jo}from"react";import{useTranslation as Jn}from"react-i18next";import{Box as ir,Typography as Ke,Button as Yo,Stack as Er,FormControlLabel as Yn,FormHelperText as Zo,Switch as Zn,ToggleButton as kr,ToggleButtonGroup as Qn}from"@mui/material";import{CheckCircle as ei,Cancel as ri,SelectAll as oi,ClearAll as ti}from"@mui/icons-material";import{jsx as O,jsxs as Ce}from"react/jsx-runtime";var ni=({value:e,onChange:r,availableFields:o,error:t,disabled:i=!1})=>{let{t:n}=Jn(),[l,a]=Go("custom"),[u,h]=Go(!1),d=Jo(null);Xo(()=>{u&&d.current?.scrollIntoView({behavior:"smooth",block:"start"})},[u]);let b=Jo(!1);Xo(()=>{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(Zo,{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(Yo,{variant:l==="all"?"contained":"outlined",startIcon:O(oi,{}),onClick:w,disabled:i,size:"small",sx:{minWidth:120,...l==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("publicPolicies.fields.conditions.allFields")}),O(Yo,{variant:l==="none"?"contained":"outlined",startIcon:O(ti,{}),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(Yn,{control:O(Zn,{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(Qn,{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(ei,{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(ri,{sx:{fontSize:16,mr:.5}}),n("publicPolicies.fields.conditions.states.deny")]})]})]},p)})})]}),t&&O(Zo,{error:!0,sx:{mt:1},children:t})]})},Ir=ni;import{jsx as U,jsxs as j}from"react/jsx-runtime";var hi=ii(({policy:e,onChange:r,onRemove:o,availableFields:t,isSubmitting:i=!1,usedActions:n,error:l},a)=>{let{t:u}=si(),h=new Set(Array.from(n||[]));h.delete(e.action);let d=Ko.map(b=>({value:b,label:u(`publicPolicies.fields.action.options.${b}`)}));return j(Qo,{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(ui,{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(mi,{})})]}),j(sr,{spacing:1,children:[U(sr,{direction:{xs:"column",md:"row"},spacing:2,children:U(Ee,{sx:{flex:1,minWidth:200},children:j(ai,{fullWidth:!0,children:[U(li,{children:u("publicPolicies.fields.action.label")}),U(ci,{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(di,{value:b.value,disabled:w,children:b.label},b.value)})}),l&&U(pi,{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(fi,{}),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(yi,{}),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(Qo,{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(gi,{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=hi;import{Fragment as Si,jsx as ue,jsxs as lr}from"react/jsx-runtime";var Ti=()=>typeof globalThis<"u"&&globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,Ri=({policies:e,onChange:r,availableFields:o,errors:t,isSubmitting:i=!1})=>{let{t:n}=xi(),l=bi({}),a=new Set((e||[]).map(s=>s.action).filter(Boolean)),u=qo.filter(s=>!a.has(s)),h=u.length>0,d=()=>{let s=u[0]||"create",y={id:Ti(),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(Si,{children:[ue(vi,{sx:{borderColor:"#e0e4e7"}}),lr(ar,{children:[ue(ar,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:lr(ar,{children:[ue(et,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("publicPolicies.title")}),ue(et,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("publicPolicies.description")})]})}),w&&ue(rt,{severity:"error",sx:{mb:3},children:w}),lr(Ci,{spacing:3,children:[(e||[]).length===0?ue(rt,{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(wi,{type:"button",variant:"outlined",startIcon:ue(Pi,{}),onClick:d,disabled:i,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("publicPolicies.addPolicy")})})]})]})]})},Jl=Ri;import{useState as Fr}from"react";import{Button as cr,TextField as ot,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 tc(){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:[_(ot,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:f=>r(f.target.value),margin:"normal",required:!0,autoComplete:"email"}),_(ot,{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 nc(){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 Ei from"@mui/material/TextField";import ki from"@mui/material/CircularProgress";import tt from"@mui/material/InputAdornment";import Ii from"@mui/material/IconButton";import Ai from"@mui/icons-material/Refresh";import{jsx as Pe}from"react/jsx-runtime";var Li=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),Fi=({html:e})=>Pe("span",{dangerouslySetInnerHTML:{__html:Li(e)}}),gc=({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(Ei,{label:t,fullWidth:!0,value:w,error:c,helperText:s?Pe(Fi,{html:s}):" ",disabled:a,InputProps:{readOnly:!0,startAdornment:h?Pe(tt,{position:"start",children:Pe(ki,{size:20})}):void 0,endAdornment:y&&!h?Pe(tt,{position:"end",children:Pe(Ii,{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(Ai,{})})}):void 0}})};import Br,{useCallback as fe,useRef as nt,useState as Ge}from"react";import ke from"@mui/material/Box";import Te from"@mui/material/Typography";import _r from"@mui/material/IconButton";import Di from"@mui/material/LinearProgress";import dr from"@mui/material/CircularProgress";import st from"@mui/material/Chip";import Bi from"@mui/material/Paper";import _i from"@mui/material/List";import zi from"@mui/material/ListItem";import Oi from"@mui/material/ListItemText";import Ui from"@mui/material/ListItemSecondaryAction";import Mi from"@mui/material/FormHelperText";import Ni from"@mui/material/Dialog";import Wi from"@mui/material/DialogTitle";import Hi from"@mui/material/DialogContent";import Vi from"@mui/material/DialogActions";import it from"@mui/material/Button";import $i from"@mui/icons-material/CloudUpload";import ji from"@mui/icons-material/InsertDriveFile";import Ki from"@mui/icons-material/Image";import qi from"@mui/icons-material/PictureAsPdf";import Gi from"@mui/icons-material/Delete";import Xi from"@mui/icons-material/Refresh";import Ji from"@mui/icons-material/Restore";import Yi from"@mui/icons-material/CheckCircle";import Zi from"@mui/icons-material/Error";import jc from"@mui/icons-material/BrokenImage";import{jsx as T,jsxs as pe}from"react/jsx-runtime";var Qi=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),es=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]}`},rs=e=>e.startsWith("image/")?T(Ki,{color:"primary"}):e==="application/pdf"?T(qi,{color:"error"}):T(ji,{color:"action"}),os=(e,r)=>{switch(e){case"completed":return T(Yi,{color:"success",fontSize:"small"});case"error":return T(Zi,{color:"error",fontSize:"small"});case"uploading":case"pending":return T(dr,{size:16});case"removing":return T(dr,{size:16,color:"error"});case"pendingDeletion":return T(st,{label:r("base.file.pendingDeletion"),size:"small",color:"warning",variant:"outlined",sx:{fontSize:"0.65rem",height:20}});default:return null}},ts=({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?T(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:T("img",{src:p,alt:e.name,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>u(!0)})}):T(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:rs(e.contentType)});return pe(zi,{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(),T(Oi,{primary:pe(ke,{sx:{display:"flex",alignItems:"center",gap:1},children:[T(Te,{variant:"body2",noWrap:!0,sx:{maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",textDecoration:h?"line-through":"none",opacity:h?.6:1},children:e.name}),os(e.status,l)]}),secondary:pe(ke,{sx:{opacity:h?.6:1},children:[e.size>0&&T(Te,{variant:"caption",color:"text.secondary",children:es(e.size)}),e.status==="uploading"&&T(Di,{variant:"determinate",value:e.progress,sx:{mt:.5,height:4,borderRadius:2}}),e.status==="error"&&e.errorMessage&&T(Te,{variant:"caption",color:"error",display:"block",children:e.errorMessage}),m&&T(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(Ui,{children:[w&&T(_r,{edge:"end",size:"small",onClick:()=>n(e.id),color:"primary",title:l("base.file.restore"),children:T(Xi,{fontSize:"small"})}),b&&T(_r,{edge:"end",size:"small",onClick:()=>i(e.id),color:"primary",title:l("base.file.restore"),children:T(Ji,{fontSize:"small"})}),d&&T(_r,{edge:"end",size:"small",onClick:()=>t(e.id),color:"error",title:l("base.file.delete"),children:T(Gi,{fontSize:"small"})})]})]})};var Gc=({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=nt(null),[g,C]=Ge(!1),[I,L]=Ge(!1),[Y,le]=Ge(null),[ee,ne]=Ge(!1),Oe=t?i:1,Ie=l?Math.max(n,1):n,W={acceptedTypes:r,maxFileSize:o,maxFiles:Oe,minFiles:Ie,visibility:y,mode:v,onFilesChange:F=>{let ce=F.filter(Je=>Je.status==="completed"&&Je.filePath).map(Je=>{let gr=Je.filePath;return gr.startsWith("/")?gr:`/${gr}`});d?.(ce)}},{files:V,isUploading:Z,addFiles:S,removeFile:P,restoreFile:H,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:Ts,activeFileCount:dt,waitForUploads:Mr,completedFilePaths:Nr}=eo(W),Wr=fe(()=>Nr,[Nr]),Hr=nt(!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:Z,waitForUploads:Mr,getCompletedFilePaths:Wr})},[f,G,X,ye,M,re,Z,Mr,Wr]);let ut=fe(F=>{k();let ce=F.target.files;ce&&ce.length>0&&S(ce),z.current&&(z.current.value="")},[S,k]),pt=fe(()=>{a||z.current?.click()},[a]),gt=fe(F=>{F.preventDefault(),F.stopPropagation(),a||C(!0)},[a]),mt=fe(F=>{F.preventDefault(),F.stopPropagation(),C(!1)},[]),ft=fe(F=>{if(F.preventDefault(),F.stopPropagation(),C(!1),a)return;k();let ce=F.dataTransfer.files;ce&&ce.length>0&&S(ce)},[a,S,k]),yt=fe(async F=>{(await P(F)).needsConfirmation&&(le(F),L(!0))},[P]),ht=fe(async()=>{if(Y){ne(!0);try{let F=await Ur(Y);F.success||x.error("Error deleting file",{error:F.error})}finally{ne(!1),L(!1),le(null)}}},[Y,Ur]),Vr=fe(()=>{L(!1),le(null)},[]),bt=r?.join(",")||"",xt=!a&&(t||dt===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&&T("span",{style:{color:"red"},children:" *"})]}),T("input",{ref:z,type:"file",accept:bt,multiple:t,onChange:ut,disabled:a,style:{display:"none"}}),xt&&pe(Bi,{variant:"outlined",onClick:pt,onDragOver:gt,onDragLeave:mt,onDrop:ft,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:[T($i,{sx:{fontSize:48,color:g?"primary.main":a?"action.disabled":"action.active",mb:1}}),T(Te,{variant:"body2",color:a?"text.disabled":"text.secondary",children:c||E(g?"base.file.dropHere":"base.file.dragOrClick")}),r&&r.length>0&&!g&&T(ke,{sx:{mt:1,display:"flex",gap:.5,justifyContent:"center",flexWrap:"wrap"},children:r.map(F=>T(st,{label:F.split("/")[1]?.toUpperCase()||F,size:"small",variant:"outlined",sx:{fontSize:"0.7rem"}},F))})]}),s&&V.length>0&&T(_i,{dense:!0,sx:{mt:1,p:0},children:V.map(F=>T(ts,{file:F,baseUrl:m,disabled:a,onRemove:yt,onRestore:H,onRetry:ie},F.id))}),Z&&pe(ke,{sx:{display:"flex",alignItems:"center",gap:1,mt:1},children:[T(dr,{size:16}),T(Te,{variant:"caption",color:"text.secondary",children:E("base.file.uploading")})]}),jr&&T(Mi,{error:pr,sx:{mt:.5},dangerouslySetInnerHTML:{__html:Qi(jr)}}),pe(Ni,{open:I,onClose:ee?void 0:Vr,children:[T(Wi,{children:E("base.file.confirmDelete.title")}),T(Hi,{children:T(Te,{children:E("base.file.confirmDelete.message")})}),pe(Vi,{children:[T(it,{onClick:Vr,disabled:ee,children:E("base.file.confirmDelete.cancel")}),T(it,{onClick:ht,color:"error",variant:"contained",disabled:ee,startIcon:ee?T(dr,{size:16,color:"inherit"}):void 0,children:E(ee?"base.file.deleting":"base.file.confirmDelete.confirm")})]})]})]})};import{useCallback as ns,useRef as is,useEffect as ss}from"react";import at from"@mui/material/Box";import lt from"@mui/material/Typography";import ct from"@mui/material/FormHelperText";import{MDXEditor as as,headingsPlugin as ls,listsPlugin as cs,quotePlugin as ds,thematicBreakPlugin as us,markdownShortcutPlugin as ps,linkPlugin as gs,linkDialogPlugin as ms,tablePlugin as fs,toolbarPlugin as ys,UndoRedo as hs,BoldItalicUnderlineToggles as bs,BlockTypeSelect as xs,CreateLink as ws,InsertTable as Cs,ListsToggle as vs,Separator as ur}from"@mdxeditor/editor";import"@mdxeditor/editor/style.css";import{Fragment as Ps,jsx as K,jsxs as zr}from"react/jsx-runtime";var nd=({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=is(null);ss(()=>{d.current&&d.current.getMarkdown()!==r&&d.current.setMarkdown(r||"")},[r]);let b=ns(w=>{o?.(w)},[o]);return zr(at,{sx:{width:"100%"},children:[e&&zr(lt,{component:"label",sx:{display:"block",mb:.5,fontSize:"0.875rem",fontWeight:500,color:n?"error.main":"text.primary"},children:[e,t&&K(lt,{component:"span",color:"error.main",sx:{ml:.5},children:"*"})]}),K(at,{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(as,{ref:d,markdown:r||"",onChange:b,placeholder:a,readOnly:i,plugins:[ls(),cs(),ds(),us(),ps(),gs(),ms(),fs(),ys({toolbarContents:()=>zr(Ps,{children:[K(hs,{}),K(ur,{}),K(bs,{}),K(ur,{}),K(xs,{}),K(ur,{}),K(vs,{}),K(ur,{}),K(ws,{}),K(Cs,{})]})})]})}),l&&K(ct,{error:n,sx:{mx:0,mt:.5},children:l}),!l&&K(ct,{sx:{mx:0,mt:.5},children:"\xA0"})]})};export{ge as a,Ss as b,Es as c,mr as d,Ze as e,Ms as f,Me as g,ao as h,lo as i,Vs as j,uo as k,po as l,go as m,mo as n,pl as o,Gn as p,Ko as q,qo as r,Jl as s,tc as t,nc as u,gc as v,Gc as w,nd as x};