@nocios/crudify-components 1.0.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/coverage/coverage-final.json +13 -13
- package/coverage/index.html +48 -48
- package/dist/chunk-4ILUXVPW.mjs +1 -0
- package/dist/{chunk-5HFI5CZ5.js → chunk-4VN5YRYZ.js} +1 -1
- package/dist/chunk-7ORHVSWL.mjs +1 -0
- package/dist/chunk-AOPB3KXB.js +1 -0
- package/dist/chunk-CR5KJUST.js +1 -0
- package/dist/{chunk-NBQH6QOU.mjs → chunk-GT7B57S5.mjs} +1 -1
- package/dist/{chunk-CHDM7KGH.js → chunk-LK6QVSG4.js} +1 -1
- package/dist/chunk-RJBX4MWF.mjs +1 -0
- package/dist/{chunk-2XOTIEKS.js → chunk-RORGWKHP.js} +1 -1
- package/dist/{chunk-U4RS66TB.mjs → chunk-XZ6OGRJR.mjs} +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/errorTranslation-By5Av0tL.d.ts +335 -0
- package/dist/errorTranslation-DeeDj7Vt.d.mts +335 -0
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/index.d.mts +9 -8
- package/dist/index.d.ts +9 -8
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/utils.d.mts +2 -48
- package/dist/utils.d.ts +2 -48
- package/dist/utils.js +1 -1
- package/dist/utils.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-HVTRRU4W.mjs +0 -1
- package/dist/chunk-JNEWPO2J.mjs +0 -1
- package/dist/chunk-MFYHD6S5.js +0 -1
- package/dist/chunk-MGJZTOEM.mjs +0 -1
- package/dist/chunk-PNI3ZBZV.js +0 -1
- package/dist/errorTranslation-DGdrMidg.d.ts +0 -143
- package/dist/errorTranslation-qwwQTvCO.d.mts +0 -143
package/coverage/index.html
CHANGED
|
@@ -23,30 +23,30 @@
|
|
|
23
23
|
<div class='clearfix'>
|
|
24
24
|
|
|
25
25
|
<div class='fl pad1y space-right2'>
|
|
26
|
-
<span class="strong">58.
|
|
26
|
+
<span class="strong">58.43% </span>
|
|
27
27
|
<span class="quiet">Statements</span>
|
|
28
|
-
<span class='fraction'>
|
|
28
|
+
<span class='fraction'>9570/16378</span>
|
|
29
29
|
</div>
|
|
30
30
|
|
|
31
31
|
|
|
32
32
|
<div class='fl pad1y space-right2'>
|
|
33
|
-
<span class="strong">80.
|
|
33
|
+
<span class="strong">80.85% </span>
|
|
34
34
|
<span class="quiet">Branches</span>
|
|
35
|
-
<span class='fraction'>
|
|
35
|
+
<span class='fraction'>1271/1572</span>
|
|
36
36
|
</div>
|
|
37
37
|
|
|
38
38
|
|
|
39
39
|
<div class='fl pad1y space-right2'>
|
|
40
|
-
<span class="strong">80.
|
|
40
|
+
<span class="strong">80.42% </span>
|
|
41
41
|
<span class="quiet">Functions</span>
|
|
42
|
-
<span class='fraction'>
|
|
42
|
+
<span class='fraction'>267/332</span>
|
|
43
43
|
</div>
|
|
44
44
|
|
|
45
45
|
|
|
46
46
|
<div class='fl pad1y space-right2'>
|
|
47
|
-
<span class="strong">58.
|
|
47
|
+
<span class="strong">58.43% </span>
|
|
48
48
|
<span class="quiet">Lines</span>
|
|
49
|
-
<span class='fraction'>
|
|
49
|
+
<span class='fraction'>9570/16378</span>
|
|
50
50
|
</div>
|
|
51
51
|
|
|
52
52
|
|
|
@@ -84,13 +84,13 @@
|
|
|
84
84
|
<div class="chart"><div class="cover-fill" style="width: 0%"></div><div class="cover-empty" style="width: 100%"></div></div>
|
|
85
85
|
</td>
|
|
86
86
|
<td data-value="0" class="pct low">0%</td>
|
|
87
|
-
<td data-value="
|
|
87
|
+
<td data-value="287" class="abs low">0/287</td>
|
|
88
88
|
<td data-value="0" class="pct low">0%</td>
|
|
89
89
|
<td data-value="1" class="abs low">0/1</td>
|
|
90
90
|
<td data-value="0" class="pct low">0%</td>
|
|
91
91
|
<td data-value="1" class="abs low">0/1</td>
|
|
92
92
|
<td data-value="0" class="pct low">0%</td>
|
|
93
|
-
<td data-value="
|
|
93
|
+
<td data-value="287" class="abs low">0/287</td>
|
|
94
94
|
</tr>
|
|
95
95
|
|
|
96
96
|
<tr>
|
|
@@ -155,47 +155,47 @@
|
|
|
155
155
|
|
|
156
156
|
<tr>
|
|
157
157
|
<td class="file high" data-value="src/components/CrudifyLogin/context"><a href="src/components/CrudifyLogin/context/index.html">src/components/CrudifyLogin/context</a></td>
|
|
158
|
-
<td data-value="80.
|
|
158
|
+
<td data-value="80.26" class="pic high">
|
|
159
159
|
<div class="chart"><div class="cover-fill" style="width: 80%"></div><div class="cover-empty" style="width: 20%"></div></div>
|
|
160
160
|
</td>
|
|
161
|
-
<td data-value="80.
|
|
162
|
-
<td data-value="
|
|
163
|
-
<td data-value="87.
|
|
164
|
-
<td data-value="
|
|
161
|
+
<td data-value="80.26" class="pct high">80.26%</td>
|
|
162
|
+
<td data-value="593" class="abs high">476/593</td>
|
|
163
|
+
<td data-value="87.8" class="pct high">87.8%</td>
|
|
164
|
+
<td data-value="82" class="abs high">72/82</td>
|
|
165
165
|
<td data-value="86.66" class="pct high">86.66%</td>
|
|
166
166
|
<td data-value="15" class="abs high">13/15</td>
|
|
167
|
-
<td data-value="80.
|
|
168
|
-
<td data-value="
|
|
167
|
+
<td data-value="80.26" class="pct high">80.26%</td>
|
|
168
|
+
<td data-value="593" class="abs high">476/593</td>
|
|
169
169
|
</tr>
|
|
170
170
|
|
|
171
171
|
<tr>
|
|
172
172
|
<td class="file high" data-value="src/components/CrudifyLogin/hooks"><a href="src/components/CrudifyLogin/hooks/index.html">src/components/CrudifyLogin/hooks</a></td>
|
|
173
|
-
<td data-value="
|
|
174
|
-
<div class="chart"><div class="cover-fill" style="width:
|
|
173
|
+
<td data-value="87.34" class="pic high">
|
|
174
|
+
<div class="chart"><div class="cover-fill" style="width: 87%"></div><div class="cover-empty" style="width: 13%"></div></div>
|
|
175
175
|
</td>
|
|
176
|
-
<td data-value="
|
|
177
|
-
<td data-value="
|
|
176
|
+
<td data-value="87.34" class="pct high">87.34%</td>
|
|
177
|
+
<td data-value="166" class="abs high">145/166</td>
|
|
178
178
|
<td data-value="85.71" class="pct high">85.71%</td>
|
|
179
179
|
<td data-value="28" class="abs high">24/28</td>
|
|
180
180
|
<td data-value="100" class="pct high">100%</td>
|
|
181
181
|
<td data-value="2" class="abs high">2/2</td>
|
|
182
|
-
<td data-value="
|
|
183
|
-
<td data-value="
|
|
182
|
+
<td data-value="87.34" class="pct high">87.34%</td>
|
|
183
|
+
<td data-value="166" class="abs high">145/166</td>
|
|
184
184
|
</tr>
|
|
185
185
|
|
|
186
186
|
<tr>
|
|
187
187
|
<td class="file high" data-value="src/components/CrudifyLogin/utils"><a href="src/components/CrudifyLogin/utils/index.html">src/components/CrudifyLogin/utils</a></td>
|
|
188
|
-
<td data-value="85.
|
|
188
|
+
<td data-value="85.03" class="pic high">
|
|
189
189
|
<div class="chart"><div class="cover-fill" style="width: 85%"></div><div class="cover-empty" style="width: 15%"></div></div>
|
|
190
190
|
</td>
|
|
191
|
-
<td data-value="85.
|
|
192
|
-
<td data-value="
|
|
193
|
-
<td data-value="
|
|
194
|
-
<td data-value="
|
|
195
|
-
<td data-value="93.
|
|
196
|
-
<td data-value="
|
|
197
|
-
<td data-value="85.
|
|
198
|
-
<td data-value="
|
|
191
|
+
<td data-value="85.03" class="pct high">85.03%</td>
|
|
192
|
+
<td data-value="254" class="abs high">216/254</td>
|
|
193
|
+
<td data-value="79.62" class="pct medium">79.62%</td>
|
|
194
|
+
<td data-value="54" class="abs medium">43/54</td>
|
|
195
|
+
<td data-value="93.33" class="pct high">93.33%</td>
|
|
196
|
+
<td data-value="15" class="abs high">14/15</td>
|
|
197
|
+
<td data-value="85.03" class="pct high">85.03%</td>
|
|
198
|
+
<td data-value="254" class="abs high">216/254</td>
|
|
199
199
|
</tr>
|
|
200
200
|
|
|
201
201
|
<tr>
|
|
@@ -410,17 +410,17 @@
|
|
|
410
410
|
|
|
411
411
|
<tr>
|
|
412
412
|
<td class="file medium" data-value="src/providers"><a href="src/providers/index.html">src/providers</a></td>
|
|
413
|
-
<td data-value="51.
|
|
413
|
+
<td data-value="51.81" class="pic medium">
|
|
414
414
|
<div class="chart"><div class="cover-fill" style="width: 51%"></div><div class="cover-empty" style="width: 49%"></div></div>
|
|
415
415
|
</td>
|
|
416
|
-
<td data-value="51.
|
|
417
|
-
<td data-value="
|
|
416
|
+
<td data-value="51.81" class="pct medium">51.81%</td>
|
|
417
|
+
<td data-value="880" class="abs medium">456/880</td>
|
|
418
418
|
<td data-value="70.37" class="pct medium">70.37%</td>
|
|
419
419
|
<td data-value="81" class="abs medium">57/81</td>
|
|
420
420
|
<td data-value="85.71" class="pct high">85.71%</td>
|
|
421
421
|
<td data-value="7" class="abs high">6/7</td>
|
|
422
|
-
<td data-value="51.
|
|
423
|
-
<td data-value="
|
|
422
|
+
<td data-value="51.81" class="pct medium">51.81%</td>
|
|
423
|
+
<td data-value="880" class="abs medium">456/880</td>
|
|
424
424
|
</tr>
|
|
425
425
|
|
|
426
426
|
<tr>
|
|
@@ -470,17 +470,17 @@
|
|
|
470
470
|
|
|
471
471
|
<tr>
|
|
472
472
|
<td class="file high" data-value="src/utils"><a href="src/utils/index.html">src/utils</a></td>
|
|
473
|
-
<td data-value="
|
|
474
|
-
<div class="chart"><div class="cover-fill" style="width:
|
|
473
|
+
<td data-value="92.05" class="pic high">
|
|
474
|
+
<div class="chart"><div class="cover-fill" style="width: 92%"></div><div class="cover-empty" style="width: 8%"></div></div>
|
|
475
475
|
</td>
|
|
476
|
-
<td data-value="
|
|
477
|
-
<td data-value="
|
|
478
|
-
<td data-value="85.
|
|
479
|
-
<td data-value="
|
|
480
|
-
<td data-value="
|
|
481
|
-
<td data-value="
|
|
482
|
-
<td data-value="
|
|
483
|
-
<td data-value="
|
|
476
|
+
<td data-value="92.05" class="pct high">92.05%</td>
|
|
477
|
+
<td data-value="2818" class="abs high">2594/2818</td>
|
|
478
|
+
<td data-value="85.83" class="pct high">85.83%</td>
|
|
479
|
+
<td data-value="459" class="abs high">394/459</td>
|
|
480
|
+
<td data-value="89.21" class="pct high">89.21%</td>
|
|
481
|
+
<td data-value="102" class="abs high">91/102</td>
|
|
482
|
+
<td data-value="92.05" class="pct high">92.05%</td>
|
|
483
|
+
<td data-value="2818" class="abs high">2594/2818</td>
|
|
484
484
|
</tr>
|
|
485
485
|
|
|
486
486
|
</tbody>
|
|
@@ -491,7 +491,7 @@
|
|
|
491
491
|
<div class='footer quiet pad2 space-top1 center small'>
|
|
492
492
|
Code coverage generated by
|
|
493
493
|
<a href="https://istanbul.js.org/" target="_blank" rel="noopener noreferrer">istanbul</a>
|
|
494
|
-
at 2026-01-
|
|
494
|
+
at 2026-01-05T05:29:06.723Z
|
|
495
495
|
</div>
|
|
496
496
|
<script src="prettify.js"></script>
|
|
497
497
|
<script>
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var N=[/password[^:]*[:=]\s*[^\s,}]+/gi,/token[^:]*[:=]\s*[^\s,}]+/gi,/key[^:]*[:=]\s*["']?[^\s,}"']+/gi,/secret[^:]*[:=]\s*[^\s,}]+/gi,/authorization[^:]*[:=]\s*[^\s,}]+/gi,/mongodb(\+srv)?:\/\/[^\s]+/gi,/postgres:\/\/[^\s]+/gi,/mysql:\/\/[^\s]+/gi];function R(){if(typeof window>"u")return"prod";let t=window.__TENANT_CONFIG__;return t?.environment&&["dev","stg","api","prod"].includes(t.environment)?t.environment:window.__CRUDIFY_ENV__?window.__CRUDIFY_ENV__:"prod"}var A=null,I="CrudifyUI",E=class{constructor(){this.explicitEnv=null;this.explicitEnv=A,this.prefix=I}getEffectiveEnv(){return this.explicitEnv!==null?this.explicitEnv:R()}sanitize(n){let e=n;for(let r of N)e=e.replace(r,"[REDACTED]");return e}sanitizeContext(n){let e={};for(let[r,i]of Object.entries(n))if(i!=null)if(r==="userId"&&typeof i=="string")e[r]=i.length>8?`${i.substring(0,8)}***`:i;else if(r==="email"&&typeof i=="string"){let[a,l]=i.split("@");e[r]=a&&l?`${a.substring(0,3)}***@${l}`:"[REDACTED]"}else typeof i=="string"?e[r]=this.sanitize(i):typeof i=="object"&&i!==null?e[r]=this.sanitizeContext(i):e[r]=i;return e}shouldLog(n){if(typeof window<"u"&&window.__CRUDIFY_DEBUG_MODE__)return!0;let e=this.getEffectiveEnv();return!((e==="prod"||e==="production"||e==="api")&&n!=="error")}log(n,e,r){if(!this.shouldLog(n))return;let i=this.sanitize(e),a=r?this.sanitizeContext(r):void 0,l={timestamp:new Date().toISOString(),level:n,environment:this.getEffectiveEnv(),service:this.prefix,message:i,...a&&Object.keys(a).length>0&&{context:a}},u=JSON.stringify(l);switch(n){case"error":console.error(u);break;case"warn":console.warn(u);break;case"info":console.info(u);break;case"debug":console.log(u);break}}error(n,e){let r;e instanceof Error?r={errorName:e.name,errorMessage:e.message,stack:e.stack}:r=e,this.log("error",n,r)}warn(n,e){this.log("warn",n,e)}info(n,e){this.log("info",n,e)}debug(n,e){this.log("debug",n,e)}getEnvironment(){return this.getEffectiveEnv()}setEnvironment(n){if(this.explicitEnv=n,A=n,typeof window<"u"){let e=["dev","stg","api","prod"];window.__CRUDIFY_ENV__=e.includes(n)?n:void 0}}isExplicitlyConfigured(){return this.explicitEnv!==null}},s=new E;var S=["dev","stg","api","prod"];function _(t){return!!t&&S.includes(t)}function w(){if(typeof window>"u")return null;let t=window.__TENANT_CONFIG__;return!t||!t.publicApiKey?null:t}function h(t={}){let{publicApiKey:n,env:e,appName:r,logo:i,loginActions:a,featureKeys:l,theme:u,enabledServices:g,enableDebug:p=!1}=t,o=w();if(o){p&&s.info("[TenantConfig] Using INJECTED configuration (Lambda@Edge)",{hasApiKey:!!o.publicApiKey,environment:o.environment,hasAppName:!!o.appName,hasLogo:!!o.logo,loginActionsCount:o.loginActions?.length,featureKeysCount:o.featureKeys?.length,hasTheme:!!o.theme});let d=_(o.environment)?o.environment:"prod";return{publicApiKey:o.publicApiKey,environment:d,appName:o.appName,logo:o.logo,loginActions:o.loginActions,featureKeys:o.featureKeys,theme:o.theme,enabledServices:o.enabledServices,configSource:"injected"}}return n?(p&&s.info("[TenantConfig] Using PROPS configuration (development)",{environment:e,hasAppName:!!r,hasLogo:!!i,loginActionsCount:a?.length,featureKeysCount:l?.length,hasTheme:!!u}),{publicApiKey:n,environment:e||"prod",appName:r,logo:i,loginActions:a,featureKeys:l,theme:u,enabledServices:g,configSource:"props"}):(p&&s.error("[TenantConfig] No configuration found! Ensure Lambda@Edge injects window.__TENANT_CONFIG__ (production) or provide props (development)."),{configSource:"none"})}function B(t={}){return h(t)}function O(t){return t==="injected"?"cookies":t}function D(t={}){let n={publicApiKey:t.publicApiKey,env:t.env,appName:t.appName,logo:t.logo,loginActions:t.loginActions,featureKeys:t.featureKeys,enableDebug:t.enableDebug},e=h(n),r={publicApiKey:e.publicApiKey,env:e.environment,appName:e.appName,logo:e.logo,loginActions:e.loginActions,featureKeys:e.featureKeys,theme:e.theme,configSource:O(e.configSource)};return t.enableDebug&&typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=r),r}function G(t={}){return D(t)}var y=class t{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return t.instance||(t.instance=new t),t.instance}emit(n,e){let r=Date.now();if(this.isHandlingAuthError&&this.lastEventType===n&&r-this.lastErrorTime<this.DEBOUNCE_TIME){s.debug(`AuthEventBus: Ignoring duplicate ${n} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=r,this.lastEventType=n,s.debug(`AuthEventBus: Emitting ${n} event`,e?{details:e}:void 0);let i={type:n,details:e,timestamp:r};this.listeners.forEach(a=>{try{a(i)}catch(l){s.error("AuthEventBus: Error in listener",l instanceof Error?l:{message:String(l)})}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},j=y.getInstance();var L=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],x={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},U={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function f(t,n){let{translateFn:e,currentLanguage:r,enableDebug:i}=n;i&&s.debug(`[ErrorTranslation] Translating error code: ${t} (lang: ${r||"unknown"})`);let a=t.toUpperCase(),l=x[a],u=L.map(o=>o.replace("{category}",l||"general").replace("{code}",a));i&&s.debug("[ErrorTranslation] Searching keys:",{translationKeys:u});for(let o of u){let d=e(o);if(i&&s.debug(`[ErrorTranslation] Checking key: "${o}" -> result: "${d}" (same as key: ${d===o})`),d&&d!==o)return i&&s.debug(`[ErrorTranslation] Found translation at key: ${o} = "${d}"`),d}let g=U[a];if(g)return i&&s.debug(`[ErrorTranslation] Using default message: "${g}"`),g;let p=a.replace(/_/g," ").toLowerCase().replace(/\b\w/g,o=>o.toUpperCase());return i&&s.debug(`[ErrorTranslation] No translation found, using friendly code: "${p}"`),p}function P(t,n){return t.map(e=>f(e,n))}function K(t,n){let{enableDebug:e}=n;e&&s.debug("[ErrorTranslation] Translating error:",{error:t});let r=f(t.code,n);return r!==t.code.toUpperCase()&&r!==t.code?(e&&s.debug(`[ErrorTranslation] Using hierarchical translation: "${r}"`),t.field?`${t.field}: ${r}`:r):t.message&&!t.message.includes("Error:")&&t.message.length>0&&t.message!==t.code?(e&&s.debug(`[ErrorTranslation] No hierarchical translation found, using API message: "${t.message}"`),t.message):(e&&s.debug(`[ErrorTranslation] Using final fallback: "${r}"`),t.field?`${t.field}: ${r}`:r)}function X(t,n={}){let e={translateFn:t,currentLanguage:n.currentLanguage,enableDebug:n.enableDebug||!1};return{translateErrorCode:r=>f(r,e),translateErrorCodes:r=>P(r,e),translateError:r=>K(r,e),translateApiError:r=>r?.data?.response?.status?f(r.data.response.status,e):r?.status?f(r.status,e):r?.code?f(r.code,e):"Unknown error"}}var c=class c{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return c.instance||(c.instance=new c),c.instance}subscribe(n){return this.listeners.add(n),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(n)}}unsubscribe(n){this.listeners.delete(n),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let n=this;window.history.pushState=function(...e){let r=n.originalPushState.apply(this,e);return n.notifyListeners(),r},window.history.replaceState=function(...e){let r=n.originalReplaceState.apply(this,e);return n.notifyListeners(),r},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(n=>{try{n()}catch(e){s.error("NavigationTracker: Error in navigation listener",e instanceof Error?e:{message:String(e)})}})}static reset(){c.instance?.isPatched&&c.instance.removePatches(),c.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};c.instance=null;var b=c;var C=t=>{try{let n=t.split(".");if(n.length!==3)return s.warn("Invalid JWT format: token must have 3 parts"),null;let e=n[1],r=e+"=".repeat((4-e.length%4)%4);return JSON.parse(atob(r))}catch(n){return s.warn("Failed to decode JWT token",n instanceof Error?{errorMessage:n.message}:{message:String(n)}),null}},te=()=>{try{let t=null;if(t=sessionStorage.getItem("authToken"),t||(t=sessionStorage.getItem("token")),t||(t=localStorage.getItem("authToken")||localStorage.getItem("token")),!t)return null;let n=C(t);return n&&(n.email||n["cognito:username"])||null}catch(t){return s.warn("Failed to get current user email",t instanceof Error?{errorMessage:t.message}:{message:String(t)}),null}},ne=t=>{try{let n=C(t);if(!n||!n.exp)return!0;let e=Math.floor(Date.now()/1e3);return n.exp<e}catch{return!0}};var T="AES-GCM";async function ie(t){let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(r)).map(a=>a.toString(16).padStart(2,"0")).join("")}async function k(t,n){let e=new TextEncoder,r=await crypto.subtle.importKey("raw",e.encode(t),"PBKDF2",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:n.buffer,iterations:1e5,hash:"SHA-256"},r,{name:T,length:256},!1,["encrypt","decrypt"])}async function oe(t,n,e){let r=new TextEncoder,i=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:T,iv:i},n,r.encode(t)),l=v(i),u=v(e),g=v(new Uint8Array(a));return`v2:${l}:${u}:${g}`}async function se(t,n){if(!t.startsWith("v2:"))return null;try{let e=t.slice(3).split(":");if(e.length!==3)return null;let[r,i,a]=e,l=m(r),u=m(i),g=m(a),p=await k(n,u),o=await crypto.subtle.decrypt({name:T,iv:l.buffer},p,g.buffer);return new TextDecoder().decode(o)}catch{return null}}function ae(){return crypto.getRandomValues(new Uint8Array(16))}function le(t){return t.startsWith("v2:")}function v(t){let n="";for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return btoa(n)}function m(t){let n=atob(t),e=new Uint8Array(n.length);for(let r=0;r<n.length;r++)e[r]=n.charCodeAt(r);return e}export{s as a,h as b,B as c,D as d,G as e,j as f,ie as g,k as h,oe as i,se as j,ae as k,le as l,f as m,P as n,K as o,X as p,b as q,C as r,te as s,ne as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkCR5KJUSTjs = require('./chunk-CR5KJUST.js');var c="crudify_login_storage_version",d=2,g="crudify_login_encryption_salt",a=class{constructor(t="sessionStorage"){this.encryptionKey=null;this.salt=null;this.initPromise=null;this.initialized=!1;this.storage=t==="localStorage"?window.localStorage:window.sessionStorage}async ensureInitialized(){if(!(this.initialized&&this.encryptionKey)){if(this.initPromise){await this.initPromise;return}this.initPromise=this.initialize(),await this.initPromise}}async initialize(){try{parseInt(this.storage.getItem(c)||"1")<d&&(this.clearLegacyData(),this.storage.setItem(c,d.toString()));let e=this.storage.getItem(g);e&&_chunkCR5KJUSTjs.l.call(void 0, `v2:x:${e}:x`)?this.salt=this.base64ToUint8Array(e):(this.salt=_chunkCR5KJUSTjs.k.call(void 0, ),this.storage.setItem(g,this.uint8ArrayToBase64(this.salt)));let i=await this.generateFingerprint();this.encryptionKey=await _chunkCR5KJUSTjs.h.call(void 0, i,this.salt),this.initialized=!0}catch(t){_chunkCR5KJUSTjs.a.error("SecureStorage initialization failed",t instanceof Error?t:{message:String(t)}),this.initialized=!1}}async generateFingerprint(){let t=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset().toString(),screen.colorDepth.toString(),screen.width.toString(),screen.height.toString(),"crudify-login"].join("|");return _chunkCR5KJUSTjs.g.call(void 0, t)}clearLegacyData(){let t=[];for(let e=0;e<this.storage.length;e++){let i=this.storage.key(e);i&&!i.startsWith(c)&&!i.startsWith(g)&&t.push(i)}t.forEach(e=>this.storage.removeItem(e))}async setItem(t,e,i){try{if(await this.ensureInitialized(),!this.encryptionKey||!this.salt){_chunkCR5KJUSTjs.a.error("SecureStorage not properly initialized");return}let r=await _chunkCR5KJUSTjs.i.call(void 0, e,this.encryptionKey,this.salt);if(this.storage.setItem(t,r),i){let o=Date.now()+i*60*1e3;this.storage.setItem(`${t}_expiry`,o.toString())}}catch(r){_chunkCR5KJUSTjs.a.error("Failed to encrypt and store data",r instanceof Error?r:{message:String(r)})}}async getItem(t){try{await this.ensureInitialized();let e=`${t}_expiry`,i=this.storage.getItem(e);if(i){let f=parseInt(i,10);if(Date.now()>f)return this.removeItem(t),null}let r=this.storage.getItem(t);if(!r)return null;if(!_chunkCR5KJUSTjs.l.call(void 0, r))return this.removeItem(t),null;let o=await this.generateFingerprint(),s=await _chunkCR5KJUSTjs.j.call(void 0, r,o);return s||(_chunkCR5KJUSTjs.a.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return _chunkCR5KJUSTjs.a.error("Failed to decrypt data",e instanceof Error?e:{message:String(e)}),this.removeItem(t),null}}removeItem(t){this.storage.removeItem(t),this.storage.removeItem(`${t}_expiry`)}clear(){this.storage.clear()}async setToken(t){try{let e=t.split(".");if(e.length===3){let i=JSON.parse(atob(e[1]));if(i.exp){let r=i.exp*1e3,o=Date.now(),s=Math.floor((r-o)/(60*1e3));if(s>0){await this.setItem("authToken",t,s);return}}}}catch (e2){_chunkCR5KJUSTjs.a.warn("Failed to parse token expiry, using default expiry")}await this.setItem("authToken",t,1440)}async getToken(){let t=await this.getItem("authToken");if(t)try{let e=t.split(".");if(e.length===3){let i=JSON.parse(atob(e[1]));if(i.exp){let r=Math.floor(Date.now()/1e3);if(i.exp<r)return this.removeItem("authToken"),null}}}catch (e3){return _chunkCR5KJUSTjs.a.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}async hasValidToken(){return await this.getToken()!==null}async migrateFromLocalStorage(t){let e=window.localStorage.getItem(t);e&&(window.localStorage.removeItem(t),t==="authToken"?await this.setToken(e):await this.setItem(t,e))}uint8ArrayToBase64(t){let e="";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return btoa(e)}base64ToUint8Array(t){let e=atob(t),i=new Uint8Array(e.length);for(let r=0;r<e.length;r++)i[r]=e.charCodeAt(r);return i}},I= exports.a =new a("sessionStorage"),T= exports.b =new a("localStorage");exports.a = I; exports.b = T;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{g as Xr,i as Jr,j as ye,l as be,n as Qr,o as Zr,r as eo}from"./chunk-GT7B57S5.mjs";import{g as X}from"./chunk-JAPL7EZJ.mjs";import{a as P,b as jr,d as Kr,f as Gr,p as Yr}from"./chunk-4ILUXVPW.mjs";var ge={es:{"checkCode.codeLabel":"C\xF3digo de Verificaci\xF3n","checkCode.codePlaceholder":"Ingresa el c\xF3digo de 6 d\xEDgitos","checkCode.codeRequired":"El c\xF3digo es obligatorio","checkCode.emailLabel":"Correo Electr\xF3nico","checkCode.emailPlaceholder":"Ingresa tu correo electr\xF3nico","checkCode.emailRequired":"El correo electr\xF3nico es obligatorio","checkCode.instructions":"Ingresa el c\xF3digo de 6 d\xEDgitos que enviamos a tu correo electr\xF3nico.","checkCode.invalidEmail":"Ingresa un correo electr\xF3nico v\xE1lido","checkCode.resendCodeLink":"Reenviar c\xF3digo","checkCode.title":"Verificar C\xF3digo","checkCode.verifyButton":"Verificar C\xF3digo","base.btn.back":"Volver","base.btn.cancel":"Cancelar","error.app.config":"Error de Configuraci\xF3n: {{message}}","error.app.initialization":"Error durante la inicializaci\xF3n final de la aplicaci\xF3n.","error.transaction":"Error en la operaci\xF3n","base.errors.errorUnknown":"Ocurri\xF3 un error desconocido.","errors.DUPLICATE":"El campo <b>{{field}}</b> debe ser \xFAnico.","errors.FOREIGN_KEY_NOT_FOUND":"El campo <b>{{field}}</b> debe referenciar un \xEDtem existente.","errors.INVALID_EMAIL":"El campo <b>{{field}}</b> debe ser un correo electr\xF3nico v\xE1lido.","errors.INVALID_OBJECT_ID":"El campo <b>{{field}}</b> debe ser un valor v\xE1lido.","errors.IN_USE":"El \xEDtem est\xE1 en uso y no puede ser eliminado.","errors.MAX_LENGTH":"El campo <b>{{field}}</b> no debe exceder los <b>{{length}}</b> caracteres.","errors.MIN_LENGTH":"El campo <b>{{field}}</b> debe tener al menos <b>{{length}}</b> caracteres.","errors.MUST_NOT_BE_EMAIL":"El campo <b>{{field}}</b> no debe ser un correo electr\xF3nico.","errors.NO_PERMISSION":"No tienes permiso para realizar esta acci\xF3n.","errors.NO_SPACES":"El campo <b>{{field}}</b> no debe contener espacios.","errors.ONE_OR_MORE_OPERATIONS_FAILED":"Error en la operaci\xF3n","errors.REQUIRED":"El campo <b>{{field}}</b> es obligatorio.","errors.TOKEN_HAS_EXPIRED":"La sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.","errors.TOO_MANY_REQUESTS":"L\xEDmite de solicitudes alcanzado. Por favor intenta m\xE1s tarde.","errors.UNAUTHORIZED":"No est\xE1s autorizado para realizar esta acci\xF3n.","errors.all_password_fields_required":"Todos los campos de contrase\xF1a son obligatorios","errors.auth.INVALID_API_KEY":"Clave de API inv\xE1lida","errors.auth.INVALID_CREDENTIALS":"Usuario y/o contrase\xF1a incorrectos","errors.auth.NO_PERMISSION":"No tienes permisos suficientes","errors.auth.SESSION_EXPIRED":"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.","errors.auth.TOO_MANY_REQUESTS":"Demasiados intentos. Por favor espera 15 minutos e intenta nuevamente","errors.auth.UNAUTHORIZED":"No tienes permisos para realizar esta acci\xF3n","errors.auth.USER_NOT_ACTIVE":"Usuario no activo","errors.auth.USER_NOT_FOUND":"Usuario no encontrado","errors.data.BAD_REQUEST":"Solicitud inv\xE1lida","errors.data.FIELD_ERROR":"Error en los datos ingresados","errors.data.IN_USE":"El elemento est\xE1 en uso y no puede ser eliminado","errors.data.ITEM_NOT_FOUND":"El elemento solicitado no fue encontrado","errors.data.NOT_FOUND":"No se encontr\xF3 lo solicitado","errors.internal_error_changing_password":"Error interno al cambiar la contrase\xF1a. Intenta nuevamente","errors.password_min_length":"La contrase\xF1a debe tener al menos 8 caracteres","errors.password_mismatch":"Las contrase\xF1as no coinciden","errors.password_must_be_different":"La nueva contrase\xF1a debe ser diferente a la actual","errors.system.DATABASE_CONNECTION_ERROR":"Error de conexi\xF3n. Verifica tu conexi\xF3n a internet.","errors.system.INTERNAL_SERVER_ERROR":"Error interno del servidor. Intenta nuevamente.","errors.system.INVALID_CONFIGURATION":"Error de configuraci\xF3n del sistema","errors.system.TOO_MANY_REQUESTS":"Demasiadas solicitudes. Por favor espera un momento e intenta nuevamente","errors.system.UNKNOWN_OPERATION":"Operaci\xF3n no reconocida","errors.users_module_not_configured":"M\xF3dulo de usuarios no configurado","footer.copyright":"Nocios S.R.L. Todos los derechos reservados.","footer.version":"Versi\xF3n","forgotPassword.checkEmailInstructions":"Revisa tu bandeja de entrada para el c\xF3digo de verificaci\xF3n","forgotPassword.codeAlreadyExistsMessage":"Ya se envi\xF3 un c\xF3digo y a\xFAn es v\xE1lido","forgotPassword.emailLabel":"Correo Electr\xF3nico","forgotPassword.emailPlaceholder":"Ingresa tu correo electr\xF3nico","forgotPassword.emailRequired":"El correo electr\xF3nico es obligatorio","forgotPassword.emailSentMessage":"C\xF3digo enviado exitosamente","forgotPassword.enterCodeLink":"Ingresar C\xF3digo","forgotPassword.instructions":"Ingresa tu correo electr\xF3nico y te enviaremos un c\xF3digo para restablecer tu contrase\xF1a.","forgotPassword.invalidEmail":"Ingresa un correo electr\xF3nico v\xE1lido","forgotPassword.sendCodeButton":"Enviar C\xF3digo","forgotPassword.title":"Recuperar Contrase\xF1a","base.loading.configInitial":"Cargando configuraci\xF3n inicial...","base.loading.pleaseWait":"Cargando, por favor espera...","base.loading.starting":"Iniciando aplicaci\xF3n...","base.loading.themeSetup":"Generando tema...","base.loading.validatingSession":"Validando sesi\xF3n...","login.alreadyHaveCodeLink":"\xBFYa tienes un c\xF3digo?","login.forgotPasswordLink":"\xBFOlvidaste tu contrase\xF1a?","login.initializationError":"Error de inicializaci\xF3n","login.initializing":"Inicializando...","login.loginButton":"Iniciar Sesi\xF3n","login.logoAlt":"Logotipo","login.noAccountPrompt":"\xBFNo tienes una cuenta?","login.notInitialized":"Sistema no inicializado","login.passwordLabel":"Contrase\xF1a","login.passwordPlaceholder":"Ingresa tu contrase\xF1a","login.passwordRequired":"Contrase\xF1a es obligatoria","login.signUpLink":"Reg\xEDstrate","login.usernameOrEmailLabel":"Correo Electr\xF3nico","login.usernameOrEmailPlaceholder":"Ingresa tu correo electr\xF3nico","login.usernameRequired":"Correo electr\xF3nico es obligatorio","resetPassword.codeExpiredOrInvalid":"El c\xF3digo ha expirado o es inv\xE1lido","resetPassword.confirmPasswordLabel":"Confirmar Contrase\xF1a","resetPassword.confirmPasswordPlaceholder":"Confirma tu nueva contrase\xF1a","resetPassword.confirmPasswordRequired":"Confirma tu contrase\xF1a","resetPassword.goToLoginButton":"Ir al Login","resetPassword.instructions":"Ingresa tu nueva contrase\xF1a.","resetPassword.invalidCode":"El c\xF3digo de verificaci\xF3n es inv\xE1lido. Por favor, verifica el enlace o solicita uno nuevo.","resetPassword.missingParameters":"Faltan par\xE1metros obligatorios","resetPassword.newPasswordLabel":"Nueva Contrase\xF1a","resetPassword.newPasswordPlaceholder":"Ingresa tu nueva contrase\xF1a","resetPassword.newPasswordRequired":"La nueva contrase\xF1a es obligatoria","resetPassword.passwordTooShort":"La contrase\xF1a debe tener al menos 8 caracteres","resetPassword.passwordsDoNotMatch":"Las contrase\xF1as no coinciden","resetPassword.requestNewCodeButton":"Solicitar Nuevo C\xF3digo","resetPassword.resetPasswordButton":"Restablecer Contrase\xF1a","resetPassword.successInstructions":"Ahora puedes iniciar sesi\xF3n con tu nueva contrase\xF1a","resetPassword.successMessage":"Contrase\xF1a restablecida exitosamente","resetPassword.title":"Nueva Contrase\xF1a","resetPassword.validatingCode":"Validando c\xF3digo...","resetPassword.passwordRequirementsNotMet":"La contrase\xF1a no cumple con todos los requisitos","passwordRequirements.minLength":"M\xEDnimo 8 caracteres","passwordRequirements.uppercase":"Una letra may\xFAscula","passwordRequirements.lowercase":"Una letra min\xFAscula","passwordRequirements.number":"Un n\xFAmero","passwordRequirements.special":"Un car\xE1cter especial (!@#$%...)","base.btn.showPassword":"Mostrar contrase\xF1a","base.btn.hidePassword":"Ocultar contrase\xF1a","publicPolicies.fields.conditions.customEdit":"Edici\xF3n personalizada","base.file.clickToPreview":"Clic para ver imagen","base.file.clickToDownload":"Clic para descargar","base.file.privateFile":"Archivo privado","base.file.noPreview":"Sin vista previa","base.file.dropHere":"Suelta el archivo aqu\xED","base.file.dragOrClick":"Arrastra archivos aqu\xED o haz clic para seleccionar","base.file.uploading":"Subiendo archivos...","base.file.restore":"Restaurar","base.file.delete":"Eliminar","base.file.pendingDeletion":"Pendiente de eliminaci\xF3n","base.file.allowedTypes":"Tipos permitidos: {{types}}","base.file.maxSize":"M\xE1ximo {{size}} por archivo","base.file.maxFiles":"M\xE1ximo {{count}} archivos","base.file.validation.minFilesRequired":"Se requiere al menos un archivo","base.file.validation.minFilesRequiredPlural":"Se requieren al menos {{count}} archivos","base.file.validation.maxFilesExceeded":"M\xE1ximo {{count}} archivos permitidos","base.file.validation.filesWithErrors":"Algunos archivos tienen errores","base.file.confirmDelete.title":"Eliminar archivo","base.file.confirmDelete.message":"\xBFEst\xE1s seguro de que deseas eliminar este archivo? Esta acci\xF3n no se puede deshacer.","base.file.confirmDelete.confirm":"Eliminar","base.file.confirmDelete.cancel":"Cancelar","base.file.deleting":"Eliminando..."},en:{"checkCode.codeLabel":"Verification Code","checkCode.codePlaceholder":"Enter 6-digit code","checkCode.codeRequired":"Code is required","checkCode.emailLabel":"Email Address","checkCode.emailPlaceholder":"Enter your email address","checkCode.emailRequired":"Email address is required","checkCode.instructions":"Enter the 6-digit code we sent to your email address.","checkCode.invalidEmail":"Enter a valid email address","checkCode.resendCodeLink":"Resend code","checkCode.title":"Verify Code","checkCode.verifyButton":"Verify Code","base.btn.back":"Back","base.btn.cancel":"Cancel","error.app.config":"Configuration Error: {{message}}","error.app.initialization":"Error during final application initialization.","error.transaction":"Operation error","base.errors.errorUnknown":"An unknown error occurred.","errors.DUPLICATE":"The field <b>{{field}}</b> must be unique.","errors.FOREIGN_KEY_NOT_FOUND":"The field <b>{{field}}</b> must reference an existing item.","errors.INVALID_EMAIL":"The field <b>{{field}}</b> must be a valid email address.","errors.INVALID_OBJECT_ID":"The field <b>{{field}}</b> must be a valid value.","errors.IN_USE":"The item is currently in use and cannot be deleted.","errors.MAX_LENGTH":"The field <b>{{field}}</b> must not exceed <b>{{maxLength}}</b> characters.","errors.MIN_LENGTH":"The field <b>{{field}}</b> must have at least <b>{{minLength}}</b> characters.","errors.MUST_NOT_BE_EMAIL":"The field <b>{{field}}</b> must not be an email address.","errors.NO_PERMISSION":"You do not have permission to perform this action.","errors.NO_SPACES":"The field <b>{{field}}</b> must not contain spaces.","errors.ONE_OR_MORE_OPERATIONS_FAILED":"Operation error","errors.REQUIRED":"The field <b>{{field}}</b> is required.","errors.TOKEN_HAS_EXPIRED":"Your session has expired, please log in again.","errors.TOO_MANY_REQUESTS":"Request limit reached. Please try again later.","errors.UNAUTHORIZED":"You are not authorized to perform this action.","errors.all_password_fields_required":"All password fields are required","errors.auth.INVALID_API_KEY":"Invalid API key","errors.auth.INVALID_CREDENTIALS":"Incorrect username and/or password","errors.auth.NO_PERMISSION":"Insufficient permissions","errors.auth.SESSION_EXPIRED":"Your session has expired. Please log in again.","errors.auth.TOO_MANY_REQUESTS":"Too many attempts. Please wait 15 minutes and try again","errors.auth.UNAUTHORIZED":"You don't have permission to perform this action","errors.auth.USER_NOT_ACTIVE":"User account is not active","errors.auth.USER_NOT_FOUND":"User not found","errors.data.BAD_REQUEST":"Invalid request","errors.data.FIELD_ERROR":"Error in the provided data","errors.data.IN_USE":"The item is in use and cannot be deleted","errors.data.ITEM_NOT_FOUND":"The requested item was not found","errors.data.NOT_FOUND":"The requested resource was not found","errors.internal_error_changing_password":"Internal error changing password. Please try again","errors.password_min_length":"Password must be at least 8 characters","errors.password_mismatch":"Passwords do not match","errors.password_must_be_different":"New password must be different from current password","errors.system.DATABASE_CONNECTION_ERROR":"Connection error. Please check your internet connection.","errors.system.INTERNAL_SERVER_ERROR":"Internal server error. Please try again.","errors.system.INVALID_CONFIGURATION":"System configuration error","errors.system.TOO_MANY_REQUESTS":"Too many requests. Please wait a moment and try again","errors.system.UNKNOWN_OPERATION":"Unrecognized operation","errors.users_module_not_configured":"Users module not configured","footer.copyright":"Nocios S.R.L. All Rights Reserved.","footer.version":"Version","forgotPassword.checkEmailInstructions":"Check your inbox for the verification code","forgotPassword.codeAlreadyExistsMessage":"A code was already sent and is still valid","forgotPassword.emailLabel":"Email Address","forgotPassword.emailPlaceholder":"Enter your email address","forgotPassword.emailRequired":"Email address is required","forgotPassword.emailSentMessage":"Code sent successfully","forgotPassword.enterCodeLink":"Enter Code","forgotPassword.instructions":"Enter your email address and we'll send you a code to reset your password.","forgotPassword.invalidEmail":"Enter a valid email address","forgotPassword.sendCodeButton":"Send Code","forgotPassword.title":"Reset Password","base.loading.configInitial":"Loading initial configuration...","base.loading.pleaseWait":"Loading, please wait...","base.loading.starting":"Starting application...","base.loading.themeSetup":"Generating theme...","base.loading.validatingSession":"Validating session...","login.alreadyHaveCodeLink":"Already have a code?","login.forgotPasswordLink":"Forgot Password?","login.initializationError":"Initialization error","login.initializing":"Initializing...","login.loginButton":"Log In","login.logoAlt":"Logo","login.noAccountPrompt":"Don't have an account?","login.notInitialized":"System not initialized","login.passwordLabel":"Password","login.passwordPlaceholder":"Enter your password","login.passwordRequired":"Password is required","login.signUpLink":"Sign up","login.usernameOrEmailLabel":"Username or Email","login.usernameOrEmailPlaceholder":"Enter your username or email","login.usernameRequired":"Username or email is required","resetPassword.codeExpiredOrInvalid":"Code expired or invalid","resetPassword.confirmPasswordLabel":"Confirm Password","resetPassword.confirmPasswordPlaceholder":"Confirm your new password","resetPassword.confirmPasswordRequired":"Confirm your password","resetPassword.goToLoginButton":"Go to Login","resetPassword.instructions":"Enter your new password.","resetPassword.invalidCode":"The verification code is invalid. Please check the link or request a new one.","resetPassword.missingParameters":"Missing required parameters","resetPassword.newPasswordLabel":"New Password","resetPassword.newPasswordPlaceholder":"Enter your new password","resetPassword.newPasswordRequired":"New password is required","resetPassword.passwordTooShort":"Password must be at least 8 characters","resetPassword.passwordsDoNotMatch":"Passwords do not match","resetPassword.requestNewCodeButton":"Request New Code","resetPassword.resetPasswordButton":"Reset Password","resetPassword.successInstructions":"You can now log in with your new password","resetPassword.successMessage":"Password reset successfully","resetPassword.title":"New Password","resetPassword.validatingCode":"Validating code...","resetPassword.passwordRequirementsNotMet":"Password does not meet all requirements","passwordRequirements.minLength":"Minimum 8 characters","passwordRequirements.uppercase":"One uppercase letter","passwordRequirements.lowercase":"One lowercase letter","passwordRequirements.number":"One number","passwordRequirements.special":"One special character (!@#$%...)","base.btn.showPassword":"Show password","base.btn.hidePassword":"Hide password","publicPolicies.fields.conditions.customEdit":"Custom Edit","base.file.clickToPreview":"Click to preview","base.file.clickToDownload":"Click to download","base.file.privateFile":"Private file","base.file.noPreview":"No preview","base.file.dropHere":"Drop file here","base.file.dragOrClick":"Drag files here or click to select","base.file.uploading":"Uploading files...","base.file.restore":"Restore","base.file.delete":"Delete","base.file.pendingDeletion":"Pending deletion","base.file.allowedTypes":"Allowed types: {{types}}","base.file.maxSize":"Max {{size}} per file","base.file.maxFiles":"Max {{count}} files","base.file.validation.minFilesRequired":"At least one file is required","base.file.validation.minFilesRequiredPlural":"At least {{count}} files are required","base.file.validation.maxFilesExceeded":"Maximum {{count}} files allowed","base.file.validation.filesWithErrors":"Some files have errors","base.file.confirmDelete.title":"Delete file","base.file.confirmDelete.message":"Are you sure you want to delete this file? This action cannot be undone.","base.file.confirmDelete.confirm":"Delete","base.file.deleting":"Deleting...","base.file.confirmDelete.cancel":"Cancel"}},xi=()=>Object.keys(ge),Pi=e=>ge[e]||ge.es;import Qe from"@nocios/crudify-sdk";var ro="crudify_translations_",yt=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&&P.debug("[TranslationService] Waiting for crudify initialization..."),this.initializationPromise):(this.enableDebug&&P.debug("[TranslationService] Initializing crudify SDK..."),this.initializationPromise=(async()=>{try{let t=Qe.getTokenData();if(t&&t.endpoint){this.enableDebug&&P.debug("[TranslationService] Crudify already initialized"),this.isInitialized=!0;return}Qe.config(o);let a=await Qe.init(r,this.enableDebug?"debug":"none");if(a.success===!1)throw new Error(`Failed to initialize crudify: ${JSON.stringify(a.errors||"Unknown error")}`);this.isInitialized=!0,this.enableDebug&&P.debug("[TranslationService] Crudify SDK initialized successfully")}catch(t){throw P.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:a="stg",urlTranslations:n}=r;this.enableDebug&&P.debug("[TranslationService] fetchTranslations called with:",{apiKeyHash:oo(o),crudifyEnv:a,featureKeys:t,hasUrlTranslations:!!n});let l=this.getFromCache(o),i=l?this.isCacheExpired(l):!0;if(l&&!i)return this.enableDebug&&P.debug("[TranslationService] Using cached translations"),this.mergeWithUrlTranslations(l.data.translations,n);try{await this.ensureCrudifyInitialized(o,a)}catch(u){return P.error("[TranslationService] Failed to initialize crudify",u instanceof Error?u:{message:String(u)}),l?(P.warn("[TranslationService] Using expired cache (init failed)"),this.mergeWithUrlTranslations(l.data.translations,n)):(P.warn("[TranslationService] Using critical bundle (init failed)"),this.getCriticalTranslationsOnly())}try{this.enableDebug&&P.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&&P.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 P.error("[TranslationService] API fetch failed",u instanceof Error?u:{message:String(u)}),l?(P.warn("[TranslationService] Using expired cache as fallback"),this.mergeWithUrlTranslations(l.data.translations,n)):(P.warn("[TranslationService] Using critical bundle translations"),this.getCriticalTranslationsOnly())}}async fetchFromAPI(r){let o=await Qe.getTranslation(r);if(!o.success)throw new Error(`Crudify API error: ${o.errors?JSON.stringify(o.errors):"Unknown error"}`);if(!o.data)throw new Error("No translation data in response");return o.data}mergeWithUrlTranslations(r,o){if(!o||Object.keys(o).length===0)return r;let t={};return Object.keys(r).forEach(a=>{t[a]={...r[a],...o}}),t}hasDataChanged(r,o){if(!r||r.data.timestamp!==o.timestamp)return!0;let t=this.hashData(o.translations);return r.dataHash!==t}hashData(r){let o=JSON.stringify(r),t=0;for(let a=0;a<o.length;a++){let n=o.charCodeAt(a);t=(t<<5)-t+n,t=t&t}return t.toString(36)}saveToCache(r,o){try{let t=this.getCacheKey(r),a={data:o,cachedAt:Date.now(),dataHash:this.hashData(o.translations)};localStorage.setItem(t,JSON.stringify(a)),this.enableDebug&&P.debug("[TranslationService] Saved to cache:",{cacheKey:t})}catch(t){P.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 P.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){P.error("[TranslationService] Failed to refresh cache timestamp",o instanceof Error?o:{message:String(o)})}}isCacheExpired(r){return Date.now()-r.cachedAt>yt}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&&P.debug("[TranslationService] Cache invalidated:",{cacheKey:o})}async prefetchTranslations(r){try{await this.fetchTranslations(r),this.enableDebug&&P.debug("[TranslationService] Prefetch completed")}catch(o){P.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&&P.debug(`[TranslationService] Cleared ${o.length} cache entries`)}catch(r){P.error("[TranslationService] Failed to clear caches",r instanceof Error?r:{message:String(r)})}}},Ze=mr.getInstance();import{createContext as bt,useContext as wt,useEffect as so,useState as Fe,useMemo as to,useCallback as xt}from"react";import{Fragment as Ct,jsx as rr}from"react/jsx-runtime";var er=null,fr=!1,io=bt(null);function no(e,r,o){return{...e,...r,...o||{}}}function Pt(e,r,o,t,a){so(()=>{if(!t||!e||!r)return;let n=o||typeof window<"u"&&window.i18next||typeof window<"u"&&window.i18n;if(!n||!n.addResourceBundle){a&&P.debug("[TranslationsProvider] i18next not found, skipping auto-sync");return}a&&P.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),a&&P.debug(`[TranslationsProvider] Synced ${Object.keys(e[l]).length} keys for language: ${l}`))}),n.language!==r&&n.changeLanguage&&(n.changeLanguage(r),a&&P.debug(`[TranslationsProvider] Changed i18next language to: ${r}`))},[e,r,o,t,a])}var _i=({children:e,apiKey:r,crudifyEnv:o="prod",featureKeys:t,language:a="es",devTranslations:n,translationUrl:l,enableDebug:i=!1,skipAutoInit:u=!0,autoSyncI18n:y=!0,i18nInstance:d,loadingFallback:b,waitForInitialLoad:w=!0})=>{let c=to(()=>Kr({publicApiKey:r,env:o,featureKeys:t,enableDebug:i}),[r,o,t,i]),s=c.publicApiKey||"",h=c.env||o||"prod",m=c.featureKeys||t,[g,f]=Fe({}),[C,S]=Fe(!0),[B,p]=Fe(!0),[x,k]=Fe(null),[A,J]=Fe(void 0),[le,Z]=Fe(!1),ne=xt(async()=>{if(!s){i&&P.debug("[TranslationsProvider] No apiKey - skipping translation fetch"),S(!1),p(!1);return}if(le){i&&P.debug("[TranslationsProvider] Skipping reload - using fallback translations");return}if(Ze.hasValidCache(s)&&B&&(i&&P.debug("[TranslationsProvider] Valid cache found - not blocking initial render"),p(!1)),fr&&er){i&&P.debug("[TranslationsProvider] Fetch already in progress, waiting for existing promise");try{let T=await er;f(T),S(!1);return}catch{i&&P.warn("[TranslationsProvider] Global fetch failed, retrying")}}fr=!0,S(!0),k(null);let W;if(l)try{i&&P.debug(`[TranslationsProvider] Fetching translations from URL: ${l}`);let T=await fetch(l);if(!T.ok)throw new Error(`Failed to fetch translations: ${T.statusText}`);W=await T.json(),J(W),i&&P.debug("[TranslationsProvider] URL translations loaded:",{keysCount:W?Object.keys(W).length:0})}catch(T){P.error("[TranslationsProvider] Failed to load URL translations",T instanceof Error?T:{message:String(T)}),W=void 0,J(void 0)}let ee=(async()=>{try{Ze.setDebug(i);let T=await Ze.fetchTranslations({apiKey:s,crudifyEnv:h,featureKeys:m,urlTranslations:W}),R={};return Object.keys(T).forEach(q=>{let se=ge[q]||{},re=T[q]||{};R[q]=no(se,re,n)}),i&&P.debug("[TranslationsProvider] Loaded translations:",{languages:Object.keys(R),keysCount:Object.keys(R[a]||{}).length}),R}catch(T){P.error("[TranslationsProvider] Failed to load",T instanceof Error?T:{message:String(T)}),k(T instanceof Error?T.message:String(T)),Z(!0);let R={};return Object.keys(ge).forEach(q=>{let se=ge[q],re=W||A||{};R[q]=no(se,re,n)}),i&&P.debug("[TranslationsProvider] Using fallback translations (critical + URL)"),R}})();er=ee;try{let T=await ee;f(T)}finally{S(!1),p(!1),fr=!1,setTimeout(()=>{er=null},1e3)}},[s,h,m,l,n,i,a,le]);so(()=>{ne();let V=setInterval(ne,3600*1e3);return()=>clearInterval(V)},[ne]);let ze=to(()=>(V,W)=>{let T=(g[a]||{})[V];if(!T){let R=Object.keys(g);for(let q of R)if(g[q][V]){T=g[q][V];break}}return T||(i&&P.warn(`[TranslationsProvider] Missing translation: "${V}"`),T=V),W&&typeof T=="string"&&Object.entries(W).forEach(([R,q])=>{let se=new RegExp(`{{${R}}}`,"g");T=T.replace(se,String(q))}),T},[g,a,i]);Pt(g,a,d,y,i);let ke={t:ze,language:a,availableLanguages:Object.keys(g),translations:g,isLoading:C,error:x,refreshTranslations:ne};return s?w&&B&&C?b||rr("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:rr("div",{children:"Loading translations..."})}):rr(io.Provider,{value:ke,children:e}):(i&&P.warn("[TranslationsProvider] No API key available. Skipping translations. Provide apiKey via props or ensure cookies are set by Lambda."),rr(Ct,{children:e}))},Me=()=>{let e=wt(io);if(!e)throw new Error("useTranslations must be used within TranslationsProvider");return e};import{Box as ao,Typography as vt}from"@mui/material";import Et from"@mui/icons-material/CheckCircle";import Tt from"@mui/icons-material/RadioButtonUnchecked";import{jsx as qe,jsxs as It}from"react/jsx-runtime";var Rt=({message:e,valid:r})=>It(ao,{sx:{display:"flex",alignItems:"center",gap:.5,py:.25},children:[r?qe(Et,{sx:{fontSize:16,color:"success.main"}}):qe(Tt,{sx:{fontSize:16,color:"text.disabled"}}),qe(vt,{variant:"caption",sx:{color:r?"success.main":"text.secondary",transition:"color 0.2s ease"},children:e})]}),St=({requirements:e,show:r=!0})=>!r||e.length===0?null:qe(ao,{sx:{mt:.5,mb:1,px:.5},children:e.map((o,t)=>qe(Rt,{message:o.message,valid:o.valid},t))}),lo=St;var kt=/[A-Z]/,At=/[a-z]/,Lt=/[0-9]/,Ft=/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/,_t=/^[A-Za-z0-9]+$/;function co(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&&_t.test(e);break;case"uppercase":t=kt.test(e);break;case"lowercase":t=At.test(e);break;case"number":t=Lt.test(e);break;case"special":t=Ft.test(e);break;default:t=!0}return{message:o.message,valid:t,enforce:!!o.enforce}})}function uo(e){return e.filter(r=>r.enforce).every(r=>r.valid)}var po=[{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 xn,Typography as Pn}from"@mui/material";import{createContext as Ot,useContext as Bt,useMemo as yr}from"react";import{useState as hr,useEffect as Dt}from"react";var go=(e,r)=>{let[o,t]=hr({}),[a,n]=hr(!1),[l,i]=hr(null);return Dt(()=>{if(r&&Object.keys(r).length>0){t(r),n(!1),i(null);return}if(!e){t({}),n(!1),i(null);return}let u=!1;return n(!0),i(null),fetch(e).then(y=>{if(!y.ok)throw new Error(`Failed to load translations: ${y.status}`);return y.json()}).then(y=>{u||(t(y),n(!1))}).catch(y=>{u||(P.error("[I18nProvider] Failed to load translations from URL",y instanceof Error?y:{message:String(y),url:e}),i(y instanceof Error?y.message:String(y)),t({}),n(!1))}),()=>{u=!0}},[e,r]),{translations:o,loading:a,error:l}};import{jsx as mo}from"react/jsx-runtime";var fo=Ot(null),Nt=()=>{try{return Me()}catch{return null}},zt=(e,r)=>{if(r.includes(".")){let o=r.split(".").reduce((t,a)=>t&&typeof t=="object"?t[a]:void 0,e);if(o!==void 0)return o}if(e&&e[r])return e[r]},ho=({children:e,translations:r,translationsUrl:o,language:t="en"})=>{let n=Nt()?.translations?.[t]||{},{translations:l,loading:i}=go(o,r),u=yr(()=>({...n,...l,...r||{}}),[n,l,r]),y=yr(()=>(b,w)=>{let c=zt(u,b);return c==null&&(c=b),w&&typeof c=="string"&&Object.entries(w).forEach(([s,h])=>{c=c.replace(new RegExp(`{{${s}}}`,"g"),h)}),typeof c=="string"?c:b},[u]),d=yr(()=>({t:y,language:t}),[y,t]);return i?mo("div",{children:"Loading translations..."}):mo(fo.Provider,{value:d,children:e})},oe=()=>{let e=Bt(fo);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};import{createContext as Ut,useContext as Mt,useReducer as qt,useEffect as br,useCallback as Vt}from"react";import{jsx as Ht}from"react/jsx-runtime";var yo={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function Wt(e,r){switch(r.type){case"SET_SCREEN":let o={...e,currentScreen:r.payload.screen,searchParams:r.payload.params||e.searchParams,errors:{global:[]}},t=new URLSearchParams(o.searchParams),a=t.toString()?`?${t.toString()}`:window.location.pathname;try{window.history.replaceState({},"",a)}catch{}return o;case"SET_SEARCH_PARAMS":return{...e,searchParams:r.payload};case"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:yo.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 bo=Ut(void 0),wo=({children:e,initialScreen:r="login",config:o,autoReadFromCookies:t=!0})=>{let[a,n]=qt(Wt,{...yo,currentScreen:r});br(()=>{n({type:"INIT_CONFIG",payload:(()=>{let s={};if(t)try{let h=jr();h.configSource!=="none"&&h.logo&&(s.logo=h.logo)}catch(h){P.error("Error reading configuration",h instanceof Error?h:{message:String(h)})}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((h,m)=>{s[m]=h}),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")&&(P.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}})},i=c=>{n({type:"UPDATE_FORM_DATA",payload:c})},u=(c,s)=>{n({type:"SET_ERRORS",payload:{[c]:s}})},y=()=>{n({type:"CLEAR_ERRORS"})},d=c=>{n({type:"SET_LOADING",payload:c})},b=Vt(()=>{n({type:"CLEAR_SEARCH_PARAMS"})},[]),w={state:a,dispatch:n,setScreen:l,updateFormData:i,setFieldError:u,clearErrors:y,setLoading:d,clearSearchParams:b};return Ht(bo.Provider,{value:w,children:e})},or=()=>{let e=Mt(bo);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};import{useEffect as $t,useRef as jt}from"react";import{Typography as wr,TextField as xo,Button as Kt,Box as Ve,CircularProgress as Gt,Alert as Yt,Link as Po}from"@mui/material";import{Fragment as Jt,jsx as te,jsxs as We}from"react/jsx-runtime";var Xt=({onScreenChange:e,onExternalNavigate:r,onLoginSuccess:o,onError:t,redirectUrl:a="/"})=>{let{state:n,updateFormData:l,setFieldError:i,clearErrors:u,setLoading:y}=or(),{login:d}=be(),b=oe(),{t:w}=b,c="i18n"in b?b.i18n:void 0,s=jt(null),h=Yr(w,{currentLanguage:c?.language,enableDebug:!1}),m=()=>{if(n.searchParams.redirect)try{let p=decodeURIComponent(n.searchParams.redirect);if(p.startsWith("/")&&!p.startsWith("//"))return p}catch{}return a||"/"};$t(()=>{let p=setTimeout(()=>{s.current&&s.current.focus()},100);return()=>clearTimeout(p)},[]);let g=p=>h.translateError({code:p.code,message:p.message,field:p.field}),f=async()=>{if(!n.loading){if(!n.formData.username.trim()){i("username",w("login.usernameRequired"));return}if(!n.formData.password.trim()){i("password",w("login.passwordRequired"));return}u(),y(!0);try{let p=await d(n.formData.username,n.formData.password);if(y(!1),p.success){let x=m();o&&o(p.data,x)}else{let x=p.rawResponse||p;C(x)}}catch(p){y(!1);let k=X(p).map(g);i("global",k),t&&t(k.join(", "))}}},C=p=>{let x=X(p),k=[];x.forEach(A=>{A.field?i(A.field,g(A)):k.push(g(A))}),k.length>0&&i("global",k)};return We(Jt,{children:[We(Ve,{component:"form",noValidate:!0,onSubmit:p=>{p.preventDefault(),f()},onKeyDown:p=>{p.key==="Enter"&&!n.loading&&(p.preventDefault(),f())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[We(Ve,{sx:{mb:1},children:[te(wr,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:w("login.usernameOrEmailLabel")}),te(xo,{fullWidth:!0,id:"email",name:"email",type:"email",value:n.formData.username,disabled:n.loading,onChange:p=>l({username:p.target.value}),error:!!n.errors.username,helperText:n.errors.username,autoComplete:"email",placeholder:w("login.usernameOrEmailPlaceholder"),inputRef:s,required:!0})]}),We(Ve,{sx:{mb:1},children:[te(wr,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:w("login.passwordLabel")}),te(xo,{fullWidth:!0,id:"password",name:"password",type:"password",value:n.formData.password,disabled:n.loading,onChange:p=>l({password:p.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(Ve,{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(Kt,{disabled:n.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:n.loading?te(Gt,{size:20}):w("login.loginButton")})]}),te(Ve,{children:n.errors.global&&n.errors.global.length>0&&n.errors.global.map((p,x)=>te(Yt,{variant:"filled",sx:{mt:2},severity:"error",children:te("div",{children:p})},x))}),n.config.loginActions?.includes("createUser")&&We(wr,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[w("login.noAccountPrompt")," ",te(Po,{sx:{cursor:"pointer"},onClick:()=>{let x=`/public/users/create${Object.keys(n.searchParams).length>0?`?${new URLSearchParams(n.searchParams).toString()}`:""}`;r?.(x)},fontWeight:"medium",color:"secondary",children:w("login.signUpLink")})]})]})},Co=Xt;import{useState as _e,useEffect as Qt,useRef as Zt}from"react";import{Typography as De,TextField as en,Button as vo,Box as we,CircularProgress as rn,Alert as on,Link as xr}from"@mui/material";import{Fragment as Eo,jsx as M,jsxs as Re}from"react/jsx-runtime";var tn=({onScreenChange:e,onError:r})=>{let{crudify:o}=ye(),[t,a]=_e(""),[n,l]=_e(!1),[i,u]=_e([]),[y,d]=_e(null),[b,w]=_e(!1),[c,s]=_e(!1),h=Zt(null),{t:m}=oe();Qt(()=>{h.current&&!b&&!c&&h.current.focus()},[b,c]);let g=x=>{let k=[`errors.auth.${x.code}`,`errors.data.${x.code}`,`errors.system.${x.code}`,`errors.${x.code}`,`forgotPassword.${x.code.toLowerCase()}`];for(let A of k){let J=m(A);if(J!==A)return J}return x.message||m("base.errors.errorUnknown")},f=x=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(x),C=async()=>{if(!(n||!o)){if(u([]),d(null),!t){d(m("forgotPassword.emailRequired"));return}if(!f(t)){d(m("forgotPassword.invalidEmail"));return}l(!0);try{let x=[{operation:"requestPasswordReset",data:{email:t}}],k=await o.transaction(x);if(k.success)k.data&&k.data.existingCodeValid?s(!0):w(!0);else{let J=X(k).map(g);u(J)}}catch(x){let A=X(x).map(g);u(A),r&&r(A.join(", "))}finally{l(!1)}}},S=()=>{e?.("login")},B=()=>{if(b||c){e?.("checkCode",{email:t});return}if(!t){d(m("forgotPassword.emailRequired"));return}if(!f(t)){d(m("forgotPassword.invalidEmail"));return}e?.("checkCode",{email:t})};return b||c?M(Eo,{children:Re(we,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[Re(we,{sx:{mb:2},children:[M(De,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:m(c?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),M(De,{variant:"body2",sx:{color:c?"success.main":"grey.600"},children:m("forgotPassword.checkEmailInstructions")})]}),M(vo,{type:"button",onClick:B,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:m("forgotPassword.enterCodeLink")}),M(we,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:M(xr,{sx:{cursor:"pointer"},onClick:S,variant:"body2",color:"secondary",children:m("base.btn.back")})})]})}):Re(Eo,{children:[Re(we,{component:"form",noValidate:!0,onSubmit:x=>{x.preventDefault(),C()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Re(we,{sx:{mb:2},children:[M(De,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:m("forgotPassword.title")}),M(De,{variant:"body2",sx:{color:"grey.600"},children:m("forgotPassword.instructions")})]}),Re(we,{sx:{mb:1},children:[M(De,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:m("forgotPassword.emailLabel")}),M(en,{fullWidth:!0,id:"email",name:"email",type:"email",value:t,disabled:n,onChange:x=>a(x.target.value),error:!!y,helperText:y,autoComplete:"email",placeholder:m("forgotPassword.emailPlaceholder"),required:!0,autoFocus:!0,inputRef:h})]}),M(vo,{disabled:n,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?M(rn,{size:20}):m("forgotPassword.sendCodeButton")}),Re(we,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[M(xr,{sx:{cursor:"pointer"},onClick:S,variant:"body2",color:"secondary",children:m("base.btn.back")}),M(De,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),M(xr,{sx:{cursor:"pointer"},onClick:B,variant:"body2",color:"secondary",children:m("login.alreadyHaveCodeLink")})]})]}),M(we,{children:i.length>0&&i.map((x,k)=>M(on,{variant:"filled",sx:{mt:2},severity:"error",children:x},k))})]})},To=tn;import{useState as H,useEffect as Ro,useMemo as Pr}from"react";import{Typography as tr,TextField as So,Button as nn,Box as xe,CircularProgress as Io,Alert as ko,Link as sn,IconButton as Ao,InputAdornment as Lo}from"@mui/material";import Fo from"@mui/icons-material/Visibility";import _o from"@mui/icons-material/VisibilityOff";import{Fragment as ln,jsx as F,jsxs as He}from"react/jsx-runtime";var an=({onScreenChange:e,onError:r,searchParams:o,onResetSuccess:t,passwordRules:a})=>{let{crudify:n}=ye(),[l,i]=H(""),[u,y]=H(""),[d,b]=H(!1),[w,c]=H([]),[s,h]=H(null),[m,g]=H(null),[f,C]=H(""),[S,B]=H(""),[p,x]=H(!1),[k,A]=H(!0),[J,le]=H(!1),[Z,ne]=H(null),[ze,ke]=H(!1),[V,W]=H(!1),[ee,T]=H(!1),{t:R}=oe(),q=Pr(()=>(a||po).map(_=>({..._,message:R(_.message)})),[a,R]),se=Pr(()=>co(l,q),[l,q]),re=Pr(()=>uo(se),[se]),Ue=l===u,Te=I=>{let _=[`errors.auth.${I.code}`,`errors.data.${I.code}`,`errors.system.${I.code}`,`errors.${I.code}`,`resetPassword.${I.code.toLowerCase()}`];for(let U of _){let K=R(U);if(K!==U)return K}return I.message||R("base.errors.errorUnknown")},Ae=I=>o?o instanceof URLSearchParams?o.get(I):o[I]||null:null;Ro(()=>{if(o){if(o){let I=Ae("fromCodeVerification"),_=Ae("email"),U=Ae("code");if(I==="true"&&_&&U){C(_),B(U),x(!0),le(!0),A(!1);return}let K=Ae("link");if(K)try{let G=decodeURIComponent(K),[Y,he]=G.split("/");if(Y&&he&&Y.length===6){B(Y),C(he),x(!1),ne({email:he,code:Y});return}}catch{}if(_&&U){C(_),B(U),x(!1),ne({email:_,code:U});return}}c([R("resetPassword.invalidCode")]),A(!1),setTimeout(()=>e?.("forgotPassword"),3e3)}},[o,n,R,e]),Ro(()=>{n&&Z&&!ze&&(ke(!0),(async(_,U)=>{try{let K=[{operation:"validatePasswordResetCode",data:{email:_,codePassword:U}}],G=await n.transaction(K);if(G.data&&Array.isArray(G.data)){let Y=G.data[0];if(Y&&Y.response&&Y.response.status==="OK"){le(!0);return}}if(G.success)le(!0);else{let he=X(G).map(Te);c(he),setTimeout(()=>e?.("forgotPassword"),3e3)}}catch(K){let Y=X(K).map(Te);c(Y),setTimeout(()=>e?.("forgotPassword"),3e3)}finally{A(!1),ne(null),ke(!1)}})(Z.email,Z.code))},[n,Z,R,e]);let Xe=async()=>{if(d||!n)return;c([]),h(null),g(null);let I=!1;if(l?re||(h(R("resetPassword.passwordRequirementsNotMet")),I=!0):(h(R("resetPassword.newPasswordRequired")),I=!0),u?Ue||(g(R("resetPassword.passwordsDoNotMatch")),I=!0):(g(R("resetPassword.confirmPasswordRequired")),I=!0),!I){b(!0);try{let _=[{operation:"validateAndResetPassword",data:{email:f,codePassword:S,newPassword:l}}],U=await n.transaction(_);if(U.success)c([]),setTimeout(()=>{t?.()},1e3);else{let G=X(U).map(Te);c(G)}}catch(_){let K=X(_).map(Te);c(K),r&&r(K.join(", "))}b(!1)}},Nr=()=>{p?e?.("checkCode",{email:f}):e?.("forgotPassword")};return k?F(xe,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:F(Io,{})}):J?He(ln,{children:[He(xe,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[He(xe,{sx:{mb:2},children:[F(tr,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:R("resetPassword.title")}),F(tr,{variant:"body2",sx:{color:"grey.600"},children:R("resetPassword.instructions")})]}),He(xe,{sx:{mb:1},children:[F(tr,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:R("resetPassword.newPasswordLabel")}),F(So,{fullWidth:!0,id:"newPassword",name:"newPassword",type:V?"text":"password",value:l,disabled:d,onChange:I=>i(I.target.value),error:!!s,helperText:s,autoComplete:"new-password",placeholder:R("resetPassword.newPasswordPlaceholder"),required:!0,InputProps:{endAdornment:F(Lo,{position:"end",children:F(Ao,{"aria-label":R(V?"base.btn.hidePassword":"base.btn.showPassword"),onClick:()=>W(!V),edge:"end",size:"small",disabled:d,children:V?F(_o,{}):F(Fo,{})})})}}),F(lo,{requirements:se,show:l.length>0})]}),He(xe,{sx:{mb:1},children:[F(tr,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:R("resetPassword.confirmPasswordLabel")}),F(So,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:ee?"text":"password",value:u,disabled:d,onChange:I=>y(I.target.value),error:!!m,helperText:m,autoComplete:"new-password",placeholder:R("resetPassword.confirmPasswordPlaceholder"),required:!0,InputProps:{endAdornment:F(Lo,{position:"end",children:F(Ao,{"aria-label":R(ee?"base.btn.hidePassword":"base.btn.showPassword"),onClick:()=>T(!ee),edge:"end",size:"small",disabled:d,children:ee?F(_o,{}):F(Fo,{})})})}})]}),F(nn,{disabled:d||!re||!Ue||!l||!u,type:"button",onClick:Xe,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:d?F(Io,{size:20}):R("resetPassword.resetPasswordButton")}),F(xe,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:F(sn,{sx:{cursor:"pointer"},onClick:Nr,variant:"body2",color:"secondary",children:R("base.btn.back")})})]}),F(xe,{children:w.length>0&&w.map((I,_)=>F(ko,{variant:"filled",sx:{mt:2},severity:"error",children:I},_))})]}):F(xe,{children:w.length>0&&w.map((I,_)=>F(ko,{variant:"filled",sx:{mt:2},severity:"error",children:I},_))})},Do=an;import{useState as $e,useEffect as Oo,useRef as cn}from"react";import{Typography as Cr,TextField as dn,Button as un,Box as je,CircularProgress as pn,Alert as gn,Link as mn}from"@mui/material";import{Fragment as hn,jsx as de,jsxs as nr}from"react/jsx-runtime";var fn=({onScreenChange:e,onError:r,searchParams:o})=>{let{crudify:t}=ye(),[a,n]=$e(""),[l,i]=$e(!1),[u,y]=$e([]),[d,b]=$e(null),[w,c]=$e(""),s=cn(null),{t:h}=oe(),m=p=>o?o instanceof URLSearchParams?o.get(p):o[p]||null:null,g=p=>{let x=[`errors.auth.${p.code}`,`errors.data.${p.code}`,`errors.system.${p.code}`,`errors.${p.code}`,`checkCode.${p.code.toLowerCase()}`];for(let k of x){let A=h(k);if(A!==k)return A}return p.message||h("base.errors.errorUnknown")};Oo(()=>{let p=m("email");p?c(p):e?.("forgotPassword")},[o,e]),Oo(()=>{s.current&&s.current.focus()},[]);let f=async()=>{if(!(l||!t)){if(y([]),b(null),!a){b(h("checkCode.codeRequired"));return}if(a.length!==6){b(h("checkCode.codeRequired"));return}i(!0);try{let p=[{operation:"validatePasswordResetCode",data:{email:w,codePassword:a}}],x=await t.transaction(p);if(x.success)e?.("resetPassword",{email:w,code:a,fromCodeVerification:"true"});else{let A=X(x).map(g);y(A),i(!1)}}catch(p){let k=X(p).map(g);y(k),i(!1),r&&r(k.join(", "))}}},C=()=>{e?.("forgotPassword")},S=p=>{let x=p.target.value.replace(/\D/g,"").slice(0,6);n(x)};return nr(hn,{children:[nr(je,{component:"form",noValidate:!0,onSubmit:p=>{p.preventDefault(),f()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[nr(je,{sx:{mb:2},children:[de(Cr,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:h("checkCode.title")}),de(Cr,{variant:"body2",sx:{color:"grey.600"},children:h("checkCode.instructions")})]}),nr(je,{sx:{mb:1},children:[de(Cr,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:h("checkCode.codeLabel")}),de(dn,{fullWidth:!0,id:"code",name:"code",type:"text",value:a,disabled:l,onChange:S,error:!!d,helperText:d,placeholder:h("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0,autoFocus:!0,inputRef:s})]}),de(un,{disabled:l||a.length!==6,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:l?de(pn,{size:20}):h("checkCode.verifyButton")}),de(je,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:de(mn,{sx:{cursor:"pointer"},onClick:C,variant:"body2",color:"secondary",children:h("base.btn.back")})})]}),de(je,{children:u.length>0&&u.map((p,x)=>de(gn,{sx:{mt:2},severity:"error",children:p},x))})]})},Bo=fn;import{Box as yn,CircularProgress as bn,Alert as No,Typography as vr}from"@mui/material";import{Fragment as wn,jsx as Oe,jsxs as zo}from"react/jsx-runtime";var Uo=({children:e,fallback:r})=>{let{isLoading:o,error:t,isInitialized:a}=ye(),{t:n}=oe();return o?r||zo(yn,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[Oe(bn,{}),Oe(vr,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):t?Oe(No,{severity:"error",sx:{mt:2},children:zo(vr,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",t]})}):a?Oe(wn,{children:e}):Oe(No,{severity:"warning",sx:{mt:2},children:Oe(vr,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as ie,jsxs as En}from"react/jsx-runtime";var Cn=({onScreenChange:e,onExternalNavigate:r,onLoginSuccess:o,onError:t,redirectUrl:a="/",passwordRules:n})=>{let{t:l}=oe(),{state:i,setScreen:u}=or(),{config:y}=be(),{showNotification:d}=Xr(),b=(c,s)=>{let h=s;c==="login"?h={}:c==="forgotPassword"&&!s&&(h={}),u(c,h),e?.(c,h)},w=()=>{let c={onScreenChange:b,onExternalNavigate:r,onError:t,redirectUrl:a};switch(i.currentScreen){case"forgotPassword":return ie(To,{...c});case"checkCode":return ie(Bo,{...c,searchParams:i.searchParams});case"resetPassword":return ie(Do,{...c,searchParams:i.searchParams,passwordRules:n,onResetSuccess:()=>{let s=l("resetPassword.successMessage");d(s,"success"),b("login")}});default:return ie(Co,{...c,onLoginSuccess:o})}};return En(Uo,{children:[ie(xn,{sx:{display:"flex",justifyContent:"center",mb:3},children:ie("img",{src:y.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"}})}),!y.logo&&y.appName&&ie(Pn,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:y.appName}),w()]})},vn=({translations:e,translationsUrl:r,language:o="en",initialScreen:t="login",autoReadFromCookies:a=!0,...n})=>{let{config:l}=be();return ie(ho,{translations:e,translationsUrl:r,language:o,children:ie(Jr,{config:l,children:ie(wo,{config:l,initialScreen:t,autoReadFromCookies:a,children:ie(Cn,{...n})})})})},ol=vn;import{Box as Q,Card as Mo,CardContent as qo,Typography as ae,Chip as sr,Avatar as Tn,Divider as Rn,CircularProgress as Sn,Alert as Vo,List as In,ListItem as Er,ListItemText as Tr,ListItemIcon as kn,Collapse as An,IconButton as Rr}from"@mui/material";import{Person as Ln,Email as Fn,Badge as _n,Security as Dn,Schedule as On,AccountCircle as Bn,ExpandMore as Nn,ExpandLess as zn,Info as Un}from"@mui/icons-material";import{useState as Mn}from"react";import{Fragment as Wn,jsx as E,jsxs as D}from"react/jsx-runtime";var qn=({showExtendedData:e=!0,showProfileCard:r=!0,autoRefresh:o=!0})=>{let{userProfile:t,loading:a,error:n,extendedData:l,refreshProfile:i}=Qr({autoFetch:o,retryOnError:!0,maxRetries:3}),[u,y]=Mn(!1);if(a)return D(Q,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[E(Sn,{}),E(ae,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return D(Vo,{severity:"error",action:E(Rr,{color:"inherit",size:"small",onClick:i,children:E(ae,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!t)return E(Vo,{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,C)=>C==null?"No disponible":typeof C=="boolean"?C?"S\xED":"No":Array.isArray(C)?C.length>0?C.join(", "):"Ninguno":typeof C=="object"?JSON.stringify(C,null,2):String(C),s=[{key:"id",label:"ID",icon:E(_n,{})},{key:"email",label:"Email",icon:E(Fn,{})},{key:"username",label:"Usuario",icon:E(Ln,{})},{key:"fullName",label:"Nombre completo",icon:E(Bn,{})},{key:"role",label:"Rol",icon:E(Dn,{})}],h=[{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"}],m=[...s.map(f=>f.key),...h.map(f=>f.key),"permissions"],g=Object.keys(d).filter(f=>!m.includes(f)).map(f=>({key:f,label:f}));return D(Q,{children:[r&&E(Mo,{sx:{mb:2},children:D(qo,{children:[D(Q,{display:"flex",alignItems:"center",mb:2,children:[E(Tn,{src:d.avatar,sx:{width:56,height:56,mr:2},children:d.fullName?.[0]||d.username?.[0]||d.email?.[0]}),D(Q,{children:[E(ae,{variant:"h6",children:d.fullName||d.username||d.email}),E(ae,{variant:"body2",color:"text.secondary",children:d.role||"Usuario"}),d.isActive!==void 0&&E(sr,{label:d.isActive?"Activo":"Inactivo",color:d.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),E(Q,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:s.map(({key:f,label:C,icon:S})=>d[f]?D(Q,{display:"flex",alignItems:"center",children:[E(Q,{sx:{mr:1,color:"text.secondary"},children:S}),D(Q,{children:[E(ae,{variant:"caption",color:"text.secondary",children:C}),E(ae,{variant:"body2",children:c(f,d[f])})]})]},f):null)}),d.permissions&&Array.isArray(d.permissions)&&d.permissions.length>0&&D(Q,{mt:2,children:[E(ae,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),D(Q,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[d.permissions.slice(0,5).map((f,C)=>E(sr,{label:f,size:"small",variant:"outlined"},C)),d.permissions.length>5&&E(sr,{label:`+${d.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&E(Mo,{children:D(qo,{children:[D(Q,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[D(ae,{variant:"h6",display:"flex",alignItems:"center",children:[E(Un,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),E(sr,{label:`${b} campos totales`,size:"small"})]}),D(In,{dense:!0,children:[h.map(({key:f,label:C})=>d[f]!==void 0&&D(Er,{divider:!0,children:[E(kn,{children:E(On,{fontSize:"small"})}),E(Tr,{primary:C,secondary:f.includes("At")||f.includes("Login")?w(d[f]):c(f,d[f])})]},f)),g.length>0&&D(Wn,{children:[E(Rn,{sx:{my:1}}),E(Er,{children:E(Tr,{primary:D(Q,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[D(ae,{variant:"subtitle2",children:["Campos Personalizados (",g.length,")"]}),E(Rr,{size:"small",onClick:()=>y(!u),children:u?E(zn,{}):E(Nn,{})})]})})}),E(An,{in:u,children:g.map(({key:f,label:C})=>E(Er,{sx:{pl:4},children:E(Tr,{primary:C,secondary:c(f,d[f])})},f))})]})]}),D(Q,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[D(ae,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",w(d.updatedAt)]}),E(Rr,{size:"small",onClick:i,disabled:a,children:E(ae,{variant:"caption",children:"Actualizar"})})]})]})})]})},Vn=qn;var Wo=["create","read","update","delete"],Ho=["create","read","update","delete"];import{useRef as ps}from"react";import{useTranslation as gs}from"react-i18next";import{Box as lr,Typography as Jo,Button as ms,Stack as fs,Alert as Qo,Divider as hs}from"@mui/material";import{Add as ys}from"@mui/icons-material";import{forwardRef as Zn}from"react";import{useTranslation as es}from"react-i18next";import{Box as Se,FormControl as rs,InputLabel as os,Select as ts,MenuItem as ns,IconButton as ss,Typography as Be,FormHelperText as is,Stack as ar,Paper as Xo,Divider as as,Button as Ar}from"@mui/material";import{Delete as ls,SelectAll as cs,ClearAll as ds}from"@mui/icons-material";import{useState as $o,useEffect as jo,useRef as Ko}from"react";import{useTranslation as Hn}from"react-i18next";import{Box as ir,Typography as Ke,Button as Go,Stack as Sr,FormControlLabel as $n,FormHelperText as Yo,Switch as jn,ToggleButton as Ir,ToggleButtonGroup as Kn}from"@mui/material";import{CheckCircle as Gn,Cancel as Yn,SelectAll as Xn,ClearAll as Jn}from"@mui/icons-material";import{jsx as N,jsxs as Pe}from"react/jsx-runtime";var Qn=({value:e,onChange:r,availableFields:o,error:t,disabled:a=!1})=>{let{t:n}=Hn(),[l,i]=$o("custom"),[u,y]=$o(!1),d=Ko(null);jo(()=>{u&&d.current?.scrollIntoView({behavior:"smooth",block:"start"})},[u]);let b=Ko(!1);jo(()=>{let m=e||{allow:[],owner_allow:[],deny:[]},g=new Set(o),f=(m.allow||[]).filter(p=>g.has(p)),C=(m.owner_allow||[]).filter(p=>g.has(p)),S=(m.deny||[]).filter(p=>g.has(p));o.forEach(p=>{!f.includes(p)&&!C.includes(p)&&!S.includes(p)&&S.push(p)});let B={allow:f,owner_allow:C,deny:S};JSON.stringify(B)!==JSON.stringify(m)&&r(B),f.length===o.length?i("all"):S.length===o.length?i("none"):i("custom")},[o,e]);let w=()=>{b.current=!0,r({allow:[...o],owner_allow:[],deny:[]}),i("all"),setTimeout(()=>{b.current=!1},0)},c=()=>{b.current=!0,r({allow:[],owner_allow:[],deny:[...o]}),i("none"),setTimeout(()=>{b.current=!1},0)},s=m=>e?.allow?.includes(m)?"allow":e?.owner_allow?.includes(m)?"owner_allow":"deny",h=(m,g)=>{b.current=!0;let f=new Set(e?.allow||[]),C=new Set(e?.owner_allow||[]),S=new Set(e?.deny||[]);f.delete(m),C.delete(m),S.delete(m),g==="allow"&&f.add(m),g==="owner_allow"&&C.add(m),g==="deny"&&S.add(m),r({allow:Array.from(f),owner_allow:Array.from(C),deny:Array.from(S)}),i("custom"),setTimeout(()=>{b.current=!1},0)};return o.length===0?Pe(ir,{children:[N(Ke,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("publicPolicies.fields.conditions.label")}),N(Ke,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("publicPolicies.fields.conditions.noFieldsAvailable")}),t&&N(Yo,{error:!0,sx:{mt:1},children:t})]}):Pe(ir,{children:[N(Ke,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("publicPolicies.fields.conditions.label")}),Pe(Sr,{direction:"row",spacing:1,alignItems:"center",sx:{mb:u?3:1},children:[N(Go,{variant:l==="all"?"contained":"outlined",startIcon:N(Xn,{}),onClick:w,disabled:a,size:"small",sx:{minWidth:120,...l==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("publicPolicies.fields.conditions.allFields")}),N(Go,{variant:l==="none"?"contained":"outlined",startIcon:N(Jn,{}),onClick:c,disabled:a,size:"small",sx:{minWidth:120,...l==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("publicPolicies.fields.conditions.noFields")}),N(ir,{sx:{display:"flex",alignItems:"center",px:1.5,py:.35,borderRadius:"999px",backgroundColor:"#f3f4f6",border:"1px solid #d1d9e0"},children:N($n,{control:N(jn,{size:"small",checked:u,onChange:()=>y(m=>!m),disabled:a,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&&Pe(ir,{ref:d,sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[N(Ke,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("publicPolicies.fields.conditions.help")}),N(Sr,{spacing:1,children:o.map(m=>{let g=s(m);return Pe(Sr,{direction:"row",spacing:1,alignItems:"center",children:[N(Ke,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:m}),Pe(Kn,{value:g,exclusive:!0,size:"small",children:[Pe(Ir,{value:"allow",onClick:()=>h(m,"allow"),disabled:a,sx:{px:2,color:g==="allow"?"#ffffff":"#6b7280",backgroundColor:g==="allow"?"#16a34a":"#f3f4f6",borderColor:g==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:g==="allow"?"#15803d":"#e5e7eb",borderColor:g==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[N(Gn,{sx:{fontSize:16,mr:.5}}),n("publicPolicies.fields.conditions.states.allow")]}),N(Ir,{value:"owner_allow",onClick:()=>h(m,"owner_allow"),disabled:a,sx:{px:2,color:g==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:g==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:g==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:g==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:g==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("publicPolicies.fields.conditions.states.ownerAllow")}),Pe(Ir,{value:"deny",onClick:()=>h(m,"deny"),disabled:a,sx:{px:2,color:g==="deny"?"#ffffff":"#6b7280",backgroundColor:g==="deny"?"#dc2626":"#f3f4f6",borderColor:g==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:g==="deny"?"#b91c1c":"#e5e7eb",borderColor:g==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[N(Yn,{sx:{fontSize:16,mr:.5}}),n("publicPolicies.fields.conditions.states.deny")]})]})]},m)})})]}),t&&N(Yo,{error:!0,sx:{mt:1},children:t})]})},kr=Qn;import{jsx as z,jsxs as $}from"react/jsx-runtime";var us=Zn(({policy:e,onChange:r,onRemove:o,availableFields:t,isSubmitting:a=!1,usedActions:n,error:l},i)=>{let{t:u}=es(),y=new Set(Array.from(n||[]));y.delete(e.action);let d=Wo.map(b=>({value:b,label:u(`publicPolicies.fields.action.options.${b}`)}));return $(Xo,{ref:i,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[$(Se,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[z(Be,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:u("publicPolicies.policyTitle")}),z(ss,{onClick:o,size:"small",disabled:a,"aria-label":u("publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:z(ls,{})})]}),$(ar,{spacing:1,children:[z(ar,{direction:{xs:"column",md:"row"},spacing:2,children:z(Se,{sx:{flex:1,minWidth:200},children:$(rs,{fullWidth:!0,children:[z(os,{children:u("publicPolicies.fields.action.label")}),z(ts,{value:e.action,label:u("publicPolicies.fields.action.label"),disabled:a,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=y.has(b.value);return z(ns,{value:b.value,disabled:w,children:b.label},b.value)})}),l&&z(is,{error:!0,children:l})]})})}),e.action==="delete"?$(Se,{children:[z(Be,{variant:"body2",color:"text.secondary",sx:{mb:2},children:u("publicPolicies.fields.conditions.label")}),$(ar,{direction:"row",spacing:1,sx:{mb:1},children:[z(Ar,{variant:e.permission==="*"?"contained":"outlined",startIcon:z(cs,{}),onClick:()=>r({...e,permission:"*"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:u("publicPolicies.fields.conditions.allFields")}),z(Ar,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>r({...e,permission:"owner"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:u("publicPolicies.fields.conditions.states.ownerAllow")}),z(Ar,{variant:e.permission==="deny"?"contained":"outlined",startIcon:z(ds,{}),onClick:()=>r({...e,permission:"deny"}),disabled:a,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:u("publicPolicies.fields.conditions.noFields")})]})]}):z(kr,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:b=>r({...e,fields:b}),availableFields:t,disabled:a}),z(Xo,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?$(Be,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[$(Se,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[u("publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):$(ar,{spacing:.5,divider:z(as,{sx:{borderColor:"#e5e7eb"}}),children:[$(Be,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[$(Se,{component:"span",sx:{color:"#16a34a"},children:[u("publicPolicies.fields.conditions.states.allow"),":"]})," ",(e?.fields?.allow||[]).join(", ")||"-"]}),$(Be,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[$(Se,{component:"span",sx:{color:"#0ea5e9"},children:[u("publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(e?.fields?.owner_allow||[]).join(", ")||"-"]}),$(Be,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[$(Se,{component:"span",sx:{color:"#dc2626"},children:[u("publicPolicies.fields.conditions.states.deny"),":"]})," ",(e?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),Lr=us;import{Fragment as xs,jsx as ue,jsxs as cr}from"react/jsx-runtime";var bs=()=>typeof globalThis<"u"&&globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,ws=({policies:e,onChange:r,availableFields:o,errors:t,isSubmitting:a=!1})=>{let{t:n}=gs(),l=ps({}),i=new Set((e||[]).map(s=>s.action).filter(Boolean)),u=Ho.filter(s=>!i.has(s)),y=u.length>0,d=()=>{let s=u[0]||"create",h={id:bs(),action:s};s==="delete"?h.permission="deny":h.fields={allow:[],owner_allow:[],deny:o};let m=[...e||[],h];r(m),setTimeout(()=>{let g=m.length-1,f=l.current[g];f&&f.scrollIntoView({behavior:"smooth",block:"center"})},100)},b=s=>{let h=[...e];h.splice(s,1),r(h)},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 cr(xs,{children:[ue(hs,{sx:{borderColor:"#e0e4e7"}}),cr(lr,{children:[ue(lr,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:cr(lr,{children:[ue(Jo,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("publicPolicies.title")}),ue(Jo,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("publicPolicies.description")})]})}),w&&ue(Qo,{severity:"error",sx:{mb:3},children:w}),cr(fs,{spacing:3,children:[(e||[]).length===0?ue(Qo,{severity:"info",children:n("publicPolicies.noPolicies")}):e.map((s,h)=>ue(Lr,{ref:m=>{l.current[h]=m},policy:s,onChange:m=>{let g=[...e];g[h]=m,r(g)},onRemove:()=>b(h),availableFields:o,isSubmitting:a,usedActions:c,error:typeof t=="object"&&t!==null&&!("_error"in t)&&s.id in t?t[s.id]:void 0},s.id)),y&&ue(lr,{children:ue(ms,{type:"button",variant:"outlined",startIcon:ue(ys,{}),onClick:d,disabled:a,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("publicPolicies.addPolicy")})})]})]})]})},Ml=ws;import{useState as Fr}from"react";import{Button as dr,TextField as Zo,Box as Ne,Alert as Ge,Typography as Ce,CircularProgress as _r}from"@mui/material";import{jsx as O,jsxs as me}from"react/jsx-runtime";function Kl(){let[e,r]=Fr(""),[o,t]=Fr(""),[a,n]=Fr(!1),{isAuthenticated:l,isLoading:i,error:u,login:y,logout:d,refreshTokens:b,clearError:w,isExpiringSoon:c,expiresIn:s}=be(),h=async f=>{if(f.preventDefault(),!e||!o)return;(await y(e,o)).success&&(r(""),t(""),n(!1))},m=async()=>{await d()},g=async()=>{await b()};return l?me(Ne,{sx:{maxWidth:600,mx:"auto",p:3},children:[O(Ce,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),O(Ge,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),me(Ne,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[O(Ce,{variant:"h6",gutterBottom:!0,children:"Token Status"}),me(Ce,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(s/1e3/60)," minutes"]}),c&&O(Ge,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),me(Ne,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[O(dr,{variant:"contained",onClick:g,disabled:i,startIcon:i?O(_r,{size:16}):null,children:"Refresh Tokens"}),O(dr,{variant:"outlined",color:"error",onClick:m,disabled:i,children:"Logout"})]}),u&&O(Ge,{severity:"error",sx:{mt:2},onClose:w,children:u})]}):me(Ne,{sx:{maxWidth:400,mx:"auto",p:3},children:[O(Ce,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),O(Ge,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),a?me("form",{onSubmit:h,children:[O(Zo,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:f=>r(f.target.value),margin:"normal",required:!0,autoComplete:"email"}),O(Zo,{fullWidth:!0,label:"Password",type:"password",value:o,onChange:f=>t(f.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),O(dr,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:i,startIcon:i?O(_r,{size:16}):null,sx:{mt:3,mb:2},children:i?"Logging in...":"Login"})]}):O(dr,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),u&&O(Ge,{severity:"error",sx:{mt:2},onClose:w,children:u})]})}function Gl(){let{isAuthenticated:e,isLoading:r,isExpiringSoon:o,expiresIn:t}=be();return r?me(Ne,{sx:{display:"flex",alignItems:"center",gap:1},children:[O(_r,{size:16}),O(Ce,{variant:"caption",children:"Loading session..."})]}):e?me(Ne,{children:[O(Ce,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),o&&me(Ce,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(t/1e3/60)," min"]})]}):O(Ce,{variant:"caption",color:"text.secondary",children:"Not logged in"})}import Ps from"@mui/material/TextField";import Cs from"@mui/material/CircularProgress";import et from"@mui/material/InputAdornment";import vs from"@mui/material/IconButton";import Es from"@mui/icons-material/Refresh";import{jsx as ve}from"react/jsx-runtime";var Ts=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),Rs=({html:e})=>ve("span",{dangerouslySetInnerHTML:{__html:Ts(e)}}),tc=({config:e,value:r,onChange:o,label:t,error:a=!1,helperText:n,readOnly:l=!1,disabled:i=!1})=>{let{value:u,loading:y,error:d,regenerate:b}=Zr(e,{autoFetch:!r,onSuccess:g=>{o?.(g)}}),w=r||u,c=a||!!d,s=d||n,h=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 ve(Ps,{label:t,fullWidth:!0,value:w,error:c,helperText:s?ve(Rs,{html:s}):" ",disabled:i,InputProps:{readOnly:!0,startAdornment:y?ve(et,{position:"start",children:ve(Cs,{size:20})}):void 0,endAdornment:h&&!y?ve(et,{position:"end",children:ve(vs,{edge:"end",onClick:async()=>{!i&&!y&&await b()},disabled:i,size:"small",color:"error","aria-label":"regenerar c\xF3digo",title:"Regenerar c\xF3digo",children:ve(Es,{})})}):void 0}})};import Dr,{useCallback as fe,useRef as rt,useState as Ye}from"react";import Ie from"@mui/material/Box";import Ee from"@mui/material/Typography";import Or from"@mui/material/IconButton";import Ss from"@mui/material/LinearProgress";import ur from"@mui/material/CircularProgress";import tt from"@mui/material/Chip";import Is from"@mui/material/Paper";import ks from"@mui/material/List";import As from"@mui/material/ListItem";import Ls from"@mui/material/ListItemText";import Fs from"@mui/material/ListItemSecondaryAction";import _s from"@mui/material/FormHelperText";import Ds from"@mui/material/Dialog";import Os from"@mui/material/DialogTitle";import Bs from"@mui/material/DialogContent";import Ns from"@mui/material/DialogActions";import ot from"@mui/material/Button";import zs from"@mui/icons-material/CloudUpload";import Us from"@mui/icons-material/InsertDriveFile";import Ms from"@mui/icons-material/Image";import qs from"@mui/icons-material/PictureAsPdf";import Vs from"@mui/icons-material/Delete";import Ws from"@mui/icons-material/Refresh";import Hs from"@mui/icons-material/Restore";import $s from"@mui/icons-material/CheckCircle";import js from"@mui/icons-material/Error";import Oc from"@mui/icons-material/BrokenImage";import{jsx as v,jsxs as pe}from"react/jsx-runtime";var Ks=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),Gs=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]}`},Ys=e=>e.startsWith("image/")?v(Ms,{color:"primary"}):e==="application/pdf"?v(qs,{color:"error"}):v(Us,{color:"action"}),Xs=(e,r)=>{switch(e){case"completed":return v($s,{color:"success",fontSize:"small"});case"error":return v(js,{color:"error",fontSize:"small"});case"uploading":case"pending":return v(ur,{size:16});case"removing":return v(ur,{size:16,color:"error"});case"pendingDeletion":return v(tt,{label:r("base.file.pendingDeletion"),size:"small",color:"warning",variant:"outlined",sx:{fontSize:"0.65rem",height:20}});default:return null}},Js=({file:e,baseUrl:r,disabled:o,onRemove:t,onRestore:a,onRetry:n})=>{let{t:l}=Me(),[i,u]=Ye(!1),y=e.status==="pendingDeletion",d=!o&&e.status!=="uploading"&&e.status!=="removing"&&!y,b=!o&&y,w=!o&&e.status==="error"&&e.file,c=e.contentType.startsWith("image/"),s=e.visibility==="public"||e.filePath?.startsWith("public/")||e.filePath?.startsWith(r),m=!e.filePath||!s?null:e.filePath.startsWith("http://")||e.filePath.startsWith("https://")||e.filePath.startsWith(r)?e.filePath:`${r}${e.filePath}`,g=e.status==="completed"&&m,f=()=>c&&g&&!i?v(Ie,{component:g?"a":"div",href:m||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:g?"pointer":"default",transition:"all 0.2s ease",flexShrink:0,"&:hover":g?{borderColor:"primary.main",transform:"scale(1.05)"}:{}},children:v("img",{src:m,alt:e.name,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>u(!0)})}):v(Ie,{component:g?"a":"div",href:m||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:g?"pointer":"default",transition:"all 0.2s ease",flexShrink:0,textDecoration:"none","&:hover":g?{borderColor:"primary.main",bgcolor:"action.hover"}:{}},children:Ys(e.contentType)});return pe(As,{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(),v(Ls,{primary:pe(Ie,{sx:{display:"flex",alignItems:"center",gap:1},children:[v(Ee,{variant:"body2",noWrap:!0,sx:{maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",textDecoration:y?"line-through":"none",opacity:y?.6:1},children:e.name}),Xs(e.status,l)]}),secondary:pe(Ie,{sx:{opacity:y?.6:1},children:[e.size>0&&v(Ee,{variant:"caption",color:"text.secondary",children:Gs(e.size)}),e.status==="uploading"&&v(Ss,{variant:"determinate",value:e.progress,sx:{mt:.5,height:4,borderRadius:2}}),e.status==="error"&&e.errorMessage&&v(Ee,{variant:"caption",color:"error",display:"block",children:e.errorMessage}),g&&v(Ee,{variant:"caption",color:"primary",display:"block",component:"a",href:m||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(Fs,{children:[w&&v(Or,{edge:"end",size:"small",onClick:()=>n(e.id),color:"primary",title:l("base.file.restore"),children:v(Ws,{fontSize:"small"})}),b&&v(Or,{edge:"end",size:"small",onClick:()=>a(e.id),color:"primary",title:l("base.file.restore"),children:v(Hs,{fontSize:"small"})}),d&&v(Or,{edge:"end",size:"small",onClick:()=>t(e.id),color:"error",title:l("base.file.delete"),children:v(Vs,{fontSize:"small"})})]})]})};var zc=({label:e,accept:r,maxFileSize:o=10*1024*1024,multiple:t=!1,maxFiles:a,minFiles:n=0,required:l=!1,disabled:i=!1,error:u=!1,helperText:y,onChange:d,onValidation:b,initialFiles:w,placeholder:c,showFileList:s=!0,visibility:h="private",showPreview:m=!0,baseUrl:g,onDeletionHandlersReady:f,mode:C="create"})=>{let{t:S}=Me(),B=rt(null),[p,x]=Ye(!1),[k,A]=Ye(!1),[J,le]=Ye(null),[Z,ne]=Ye(!1),ze=t?a:1,ke=l?Math.max(n,1):n,V={acceptedTypes:r,maxFileSize:o,maxFiles:ze,minFiles:ke,visibility:h,mode:C,onFilesChange:L=>{let ce=L.filter(Je=>Je.status==="completed"&&Je.filePath).map(Je=>{let Le=Je.filePath;return Le.startsWith(g)||Le.startsWith("http://")||Le.startsWith("https://")?Le:g?`${g}${Le}`:Le});d?.(ce)}},{files:W,isUploading:ee,addFiles:T,removeFile:R,restoreFile:q,retryUpload:se,isValid:re,validationError:Ue,validationErrorKey:Te,validationErrorParams:Ae,initializeFiles:Xe,isTouched:Nr,markAsTouched:I,isSubmitted:_,markAsSubmitted:U,getPreviewUrl:K,commitDeletions:G,restorePendingDeletions:Y,hasPendingDeletions:he,deleteFileImmediately:zr,activeFiles:bi,activeFileCount:at,waitForUploads:Ur,completedFilePaths:Mr}=eo(V),qr=fe(()=>Mr,[Mr]),Vr=rt(!1);Dr.useEffect(()=>{w&&w.length>0&&!Vr.current&&(Vr.current=!0,Xe(w,g))},[w,Xe,g]),Dr.useEffect(()=>{b?.(re,Ue)},[re,Ue,b]),Dr.useEffect(()=>{f?.({commitDeletions:G,restorePendingDeletions:Y,hasPendingDeletions:he,markAsSubmitted:U,isValid:re,isUploading:ee,waitForUploads:Ur,getCompletedFilePaths:qr})},[f,G,Y,he,U,re,ee,Ur,qr]);let lt=fe(L=>{I();let ce=L.target.files;ce&&ce.length>0&&T(ce),B.current&&(B.current.value="")},[T,I]),ct=fe(()=>{i||B.current?.click()},[i]),dt=fe(L=>{L.preventDefault(),L.stopPropagation(),i||x(!0)},[i]),ut=fe(L=>{L.preventDefault(),L.stopPropagation(),x(!1)},[]),pt=fe(L=>{if(L.preventDefault(),L.stopPropagation(),x(!1),i)return;I();let ce=L.dataTransfer.files;ce&&ce.length>0&&T(ce)},[i,T,I]),gt=fe(async L=>{(await R(L)).needsConfirmation&&(le(L),A(!0))},[R]),mt=fe(async()=>{if(J){ne(!0);try{let L=await zr(J);L.success||P.error("Error deleting file",{error:L.error})}finally{ne(!1),A(!1),le(null)}}},[J,zr]),Wr=fe(()=>{A(!1),le(null)},[]),ft=r?.join(",")||"",ht=!i&&(t||at===0),Hr=_&&!re,gr=u||Hr,$r=y||(Hr&&Te?S(Te,Ae):null);return pe(Ie,{sx:{width:"100%"},children:[e&&pe(Ee,{variant:"body2",sx:{mb:1,fontWeight:500,color:gr?"error.main":"text.primary"},children:[e,l&&v("span",{style:{color:"red"},children:" *"})]}),v("input",{ref:B,type:"file",accept:ft,multiple:t,onChange:lt,disabled:i,style:{display:"none"}}),ht&&pe(Is,{variant:"outlined",onClick:ct,onDragOver:dt,onDragLeave:ut,onDrop:pt,sx:{p:3,textAlign:"center",cursor:i?"not-allowed":"pointer",borderStyle:"dashed",borderWidth:2,borderColor:p?"primary.main":gr?"error.main":"divider",bgcolor:p?"primary.lighter":i?"action.disabledBackground":"background.paper",transition:"all 0.2s ease","&:hover":i?{}:{borderColor:"primary.main",bgcolor:"action.hover"}},children:[v(zs,{sx:{fontSize:48,color:p?"primary.main":i?"action.disabled":"action.active",mb:1}}),v(Ee,{variant:"body2",color:i?"text.disabled":"text.secondary",children:c||S(p?"base.file.dropHere":"base.file.dragOrClick")}),r&&r.length>0&&!p&&v(Ie,{sx:{mt:1,display:"flex",gap:.5,justifyContent:"center",flexWrap:"wrap"},children:r.map(L=>v(tt,{label:L.split("/")[1]?.toUpperCase()||L,size:"small",variant:"outlined",sx:{fontSize:"0.7rem"}},L))})]}),s&&W.length>0&&v(ks,{dense:!0,sx:{mt:1,p:0},children:W.map(L=>v(Js,{file:L,baseUrl:g,disabled:i,onRemove:gt,onRestore:q,onRetry:se},L.id))}),ee&&pe(Ie,{sx:{display:"flex",alignItems:"center",gap:1,mt:1},children:[v(ur,{size:16}),v(Ee,{variant:"caption",color:"text.secondary",children:S("base.file.uploading")})]}),$r&&v(_s,{error:gr,sx:{mt:.5},dangerouslySetInnerHTML:{__html:Ks($r)}}),pe(Ds,{open:k,onClose:Z?void 0:Wr,children:[v(Os,{children:S("base.file.confirmDelete.title")}),v(Bs,{children:v(Ee,{children:S("base.file.confirmDelete.message")})}),pe(Ns,{children:[v(ot,{onClick:Wr,disabled:Z,children:S("base.file.confirmDelete.cancel")}),v(ot,{onClick:mt,color:"error",variant:"contained",disabled:Z,startIcon:Z?v(ur,{size:16,color:"inherit"}):void 0,children:S(Z?"base.file.deleting":"base.file.confirmDelete.confirm")})]})]})]})};import{useCallback as Qs,useRef as Zs,useEffect as ei}from"react";import nt from"@mui/material/Box";import st from"@mui/material/Typography";import it from"@mui/material/FormHelperText";import{MDXEditor as ri,headingsPlugin as oi,listsPlugin as ti,quotePlugin as ni,thematicBreakPlugin as si,markdownShortcutPlugin as ii,linkPlugin as ai,linkDialogPlugin as li,tablePlugin as ci,toolbarPlugin as di,UndoRedo as ui,BoldItalicUnderlineToggles as pi,BlockTypeSelect as gi,CreateLink as mi,InsertTable as fi,ListsToggle as hi,Separator as pr}from"@mdxeditor/editor";import"@mdxeditor/editor/style.css";import{Fragment as yi,jsx as j,jsxs as Br}from"react/jsx-runtime";var Gc=({label:e,value:r="",onChange:o,required:t=!1,disabled:a=!1,error:n=!1,helperText:l,placeholder:i="Write here...",minHeight:u=200,maxHeight:y=500})=>{let d=Zs(null);ei(()=>{d.current&&d.current.getMarkdown()!==r&&d.current.setMarkdown(r||"")},[r]);let b=Qs(w=>{o?.(w)},[o]);return Br(nt,{sx:{width:"100%"},children:[e&&Br(st,{component:"label",sx:{display:"block",mb:.5,fontSize:"0.875rem",fontWeight:500,color:n?"error.main":"text.primary"},children:[e,t&&j(st,{component:"span",color:"error.main",sx:{ml:.5},children:"*"})]}),j(nt,{sx:{border:1,borderColor:n?"error.main":"divider",borderRadius:1,overflow:"hidden",opacity:a?.6:1,pointerEvents:a?"none":"auto","& .mdxeditor":{minHeight:u,maxHeight:y,overflow:"auto"},"& .mdxeditor-toolbar":{borderBottom:1,borderColor:"divider",backgroundColor:"background.default"},"& .mdxeditor-root-contenteditable":{padding:2,minHeight:u-50}},children:j(ri,{ref:d,markdown:r||"",onChange:b,placeholder:i,readOnly:a,plugins:[oi(),ti(),ni(),si(),ii(),ai(),li(),ci(),di({toolbarContents:()=>Br(yi,{children:[j(ui,{}),j(pr,{}),j(pi,{}),j(pr,{}),j(gi,{}),j(pr,{}),j(hi,{}),j(pr,{}),j(mi,{}),j(fi,{})]})})]})}),l&&j(it,{error:n,sx:{mx:0,mt:.5},children:l}),!l&&j(it,{sx:{mx:0,mt:.5},children:"\xA0"})]})};export{ge as a,xi as b,Pi as c,mr as d,Ze as e,_i as f,Me as g,lo as h,co as i,uo as j,po as k,ol as l,Vn as m,Wo as n,Ho as o,Ml as p,Kl as q,Gl as r,tc as s,zc as t,Gc as u};
|