@nocios/crudify-components 2.0.12 → 2.0.16

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.
@@ -23,30 +23,30 @@
23
23
  <div class='clearfix'>
24
24
 
25
25
  <div class='fl pad1y space-right2'>
26
- <span class="strong">59.04% </span>
26
+ <span class="strong">58.82% </span>
27
27
  <span class="quiet">Statements</span>
28
- <span class='fraction'>9824/16639</span>
28
+ <span class='fraction'>9860/16763</span>
29
29
  </div>
30
30
 
31
31
 
32
32
  <div class='fl pad1y space-right2'>
33
- <span class="strong">81.31% </span>
33
+ <span class="strong">81.39% </span>
34
34
  <span class="quiet">Branches</span>
35
- <span class='fraction'>1327/1632</span>
35
+ <span class='fraction'>1330/1634</span>
36
36
  </div>
37
37
 
38
38
 
39
39
  <div class='fl pad1y space-right2'>
40
- <span class="strong">80.71% </span>
40
+ <span class="strong">80% </span>
41
41
  <span class="quiet">Functions</span>
42
- <span class='fraction'>272/337</span>
42
+ <span class='fraction'>272/340</span>
43
43
  </div>
44
44
 
45
45
 
46
46
  <div class='fl pad1y space-right2'>
47
- <span class="strong">59.04% </span>
47
+ <span class="strong">58.82% </span>
48
48
  <span class="quiet">Lines</span>
49
- <span class='fraction'>9824/16639</span>
49
+ <span class='fraction'>9860/16763</span>
50
50
  </div>
51
51
 
52
52
 
@@ -95,17 +95,17 @@
95
95
 
96
96
  <tr>
97
97
  <td class="file medium" data-value="src/components"><a href="src/components/index.html">src/components</a></td>
98
- <td data-value="65.83" class="pic medium">
98
+ <td data-value="65.84" class="pic medium">
99
99
  <div class="chart"><div class="cover-fill" style="width: 65%"></div><div class="cover-empty" style="width: 35%"></div></div>
100
100
  </td>
101
- <td data-value="65.83" class="pct medium">65.83%</td>
102
- <td data-value="2236" class="abs medium">1472/2236</td>
103
- <td data-value="75.92" class="pct medium">75.92%</td>
104
- <td data-value="216" class="abs medium">164/216</td>
101
+ <td data-value="65.84" class="pct medium">65.84%</td>
102
+ <td data-value="2237" class="abs medium">1473/2237</td>
103
+ <td data-value="76.27" class="pct medium">76.27%</td>
104
+ <td data-value="215" class="abs medium">164/215</td>
105
105
  <td data-value="71.87" class="pct medium">71.87%</td>
106
106
  <td data-value="32" class="abs medium">23/32</td>
107
- <td data-value="65.83" class="pct medium">65.83%</td>
108
- <td data-value="2236" class="abs medium">1472/2236</td>
107
+ <td data-value="65.84" class="pct medium">65.84%</td>
108
+ <td data-value="2237" class="abs medium">1473/2237</td>
109
109
  </tr>
110
110
 
111
111
  <tr>
@@ -160,8 +160,8 @@
160
160
  </td>
161
161
  <td data-value="80.26" class="pct high">80.26%</td>
162
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>
163
+ <td data-value="87.95" class="pct high">87.95%</td>
164
+ <td data-value="83" class="abs high">73/83</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
167
  <td data-value="80.26" class="pct high">80.26%</td>
@@ -320,17 +320,17 @@
320
320
 
321
321
  <tr>
322
322
  <td class="file medium" data-value="src/core"><a href="src/core/index.html">src/core</a></td>
323
- <td data-value="64.1" class="pic medium">
324
- <div class="chart"><div class="cover-fill" style="width: 64%"></div><div class="cover-empty" style="width: 36%"></div></div>
323
+ <td data-value="61.01" class="pic medium">
324
+ <div class="chart"><div class="cover-fill" style="width: 61%"></div><div class="cover-empty" style="width: 39%"></div></div>
325
325
  </td>
326
- <td data-value="64.1" class="pct medium">64.1%</td>
327
- <td data-value="1368" class="abs medium">877/1368</td>
326
+ <td data-value="61.01" class="pct medium">61.01%</td>
327
+ <td data-value="1485" class="abs medium">906/1485</td>
328
328
  <td data-value="70.49" class="pct medium">70.49%</td>
329
329
  <td data-value="122" class="abs medium">86/122</td>
330
- <td data-value="77.08" class="pct medium">77.08%</td>
331
- <td data-value="48" class="abs medium">37/48</td>
332
- <td data-value="64.1" class="pct medium">64.1%</td>
333
- <td data-value="1368" class="abs medium">877/1368</td>
330
+ <td data-value="72.54" class="pct medium">72.54%</td>
331
+ <td data-value="51" class="abs medium">37/51</td>
332
+ <td data-value="61.01" class="pct medium">61.01%</td>
333
+ <td data-value="1485" class="abs medium">906/1485</td>
334
334
  </tr>
335
335
 
336
336
  <tr>
@@ -380,17 +380,17 @@
380
380
 
381
381
  <tr>
382
382
  <td class="file high" data-value="src/hooks/useSession/hooks"><a href="src/hooks/useSession/hooks/index.html">src/hooks/useSession/hooks</a></td>
383
- <td data-value="87.92" class="pic high">
384
- <div class="chart"><div class="cover-fill" style="width: 87%"></div><div class="cover-empty" style="width: 13%"></div></div>
383
+ <td data-value="88.08" class="pic high">
384
+ <div class="chart"><div class="cover-fill" style="width: 88%"></div><div class="cover-empty" style="width: 12%"></div></div>
385
385
  </td>
386
- <td data-value="87.92" class="pct high">87.92%</td>
387
- <td data-value="588" class="abs high">517/588</td>
386
+ <td data-value="88.08" class="pct high">88.08%</td>
387
+ <td data-value="596" class="abs high">525/596</td>
388
388
  <td data-value="89.42" class="pct high">89.42%</td>
389
389
  <td data-value="104" class="abs high">93/104</td>
390
390
  <td data-value="87.5" class="pct high">87.5%</td>
391
391
  <td data-value="8" class="abs high">7/8</td>
392
- <td data-value="87.92" class="pct high">87.92%</td>
393
- <td data-value="588" class="abs high">517/588</td>
392
+ <td data-value="88.08" class="pct high">88.08%</td>
393
+ <td data-value="596" class="abs high">525/596</td>
394
394
  </tr>
395
395
 
396
396
  <tr>
@@ -399,13 +399,13 @@
399
399
  <div class="chart"><div class="cover-fill cover-full" style="width: 100%"></div><div class="cover-empty" style="width: 0%"></div></div>
400
400
  </td>
401
401
  <td data-value="100" class="pct high">100%</td>
402
- <td data-value="173" class="abs high">173/173</td>
402
+ <td data-value="178" class="abs high">178/178</td>
403
403
  <td data-value="100" class="pct high">100%</td>
404
- <td data-value="36" class="abs high">36/36</td>
404
+ <td data-value="38" class="abs high">38/38</td>
405
405
  <td data-value="100" class="pct high">100%</td>
406
406
  <td data-value="9" class="abs high">9/9</td>
407
407
  <td data-value="100" class="pct high">100%</td>
408
- <td data-value="173" class="abs high">173/173</td>
408
+ <td data-value="178" class="abs high">178/178</td>
409
409
  </tr>
410
410
 
411
411
  <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="92.47" class="pic high">
473
+ <td data-value="92.45" class="pic high">
474
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="92.47" class="pct high">92.47%</td>
477
- <td data-value="3068" class="abs high">2837/3068</td>
476
+ <td data-value="92.45" class="pct high">92.45%</td>
477
+ <td data-value="3061" class="abs high">2830/3061</td>
478
478
  <td data-value="86.7" class="pct high">86.7%</td>
479
479
  <td data-value="519" class="abs high">450/519</td>
480
480
  <td data-value="89.71" class="pct high">89.71%</td>
481
481
  <td data-value="107" class="abs high">96/107</td>
482
- <td data-value="92.47" class="pct high">92.47%</td>
483
- <td data-value="3068" class="abs high">2837/3068</td>
482
+ <td data-value="92.45" class="pct high">92.45%</td>
483
+ <td data-value="3061" class="abs high">2830/3061</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-09T11:21:12.149Z
494
+ at 2026-01-17T08:00:53.623Z
495
495
  </div>
496
496
  <script src="prettify.js"></script>
497
497
  <script>
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkCR5KJUSTjs = require('./chunk-CR5KJUST.js');var Me="crudify_storage_version",He=2,a=class a{static setStorageType(e){a.storageType=e}static async initialize(){if(!(a.encryptionKey&&a.salt))return a.initPromise||(a.initPromise=(async()=>{let t=null;for(let i=1;i<=3;i++)try{a.checkStorageVersion(),a.salt=a.getOrCreateSalt(),a.fingerprint=await a.generateFingerprint(),a.encryptionKey=await _chunkCR5KJUSTjs.h.call(void 0, a.fingerprint,a.salt);return}catch(n){t=n instanceof Error?n:new Error(String(n)),i<3&&await new Promise(s=>setTimeout(s,100*i))}throw _chunkCR5KJUSTjs.a.error("Crudify: Failed to initialize encryption after retries",_nullishCoalesce(t, () => ({message:"Unknown error"}))),t})()),a.initPromise}static checkStorageVersion(){try{if(parseInt(localStorage.getItem(Me)||"1",10)<He){let t=a.getStorage();t&&t.removeItem(a.TOKEN_KEY),localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY),localStorage.setItem(Me,He.toString()),_chunkCR5KJUSTjs.a.info("Crudify: Storage upgraded to v2, tokens cleared for security")}}catch (e2){}}static getOrCreateSalt(){try{let t=localStorage.getItem(a.SALT_KEY);if(t){let i=atob(t),n=new Uint8Array(i.length);for(let s=0;s<i.length;s++)n[s]=i.charCodeAt(s);return n}}catch (e3){}let e=_chunkCR5KJUSTjs.k.call(void 0, );try{let t="";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);localStorage.setItem(a.SALT_KEY,btoa(t))}catch (e4){_chunkCR5KJUSTjs.a.warn("Crudify: Cannot persist salt, encryption may not persist across sessions")}return e}static async generateFingerprint(){try{let n=localStorage.getItem(a.ENCRYPTION_KEY_STORAGE);if(n&&n.length>=32)return n}catch (e5){}let t=[navigator.userAgent,navigator.language,navigator.platform||"unknown",String(screen.width),String(screen.height),String(screen.colorDepth||24),String(new Date().getTimezoneOffset()),"crudify-session-v3"].join("|"),i=await _chunkCR5KJUSTjs.g.call(void 0, t);try{localStorage.setItem(a.ENCRYPTION_KEY_STORAGE,i)}catch (e6){_chunkCR5KJUSTjs.a.warn("Crudify: Cannot persist encryption key hash, session may not survive page reload")}return i}static isStorageAvailable(e){try{let t=window[e],i="__storage_test__";return t.setItem(i,"test"),t.removeItem(i),!0}catch (e7){return!1}}static getStorage(){return a.storageType==="none"?null:a.isStorageAvailable(a.storageType)?window[a.storageType]:(_chunkCR5KJUSTjs.a.warn(`Crudify: ${a.storageType} not available, tokens won't persist`),null)}static async encryptData(e){if(await a.initialize(),!a.encryptionKey||!a.salt)throw new Error("Encryption not initialized");return _chunkCR5KJUSTjs.i.call(void 0, e,a.encryptionKey,a.salt)}static async decryptData(e){if(await a.initialize(),!a.fingerprint)throw new Error("Encryption not initialized");return _chunkCR5KJUSTjs.l.call(void 0, e)?_chunkCR5KJUSTjs.j.call(void 0, e,a.fingerprint):(_chunkCR5KJUSTjs.a.warn("Crudify: Legacy encrypted data detected, cannot decrypt"),null)}static async saveTokens(e){let t=a.getStorage();if(t)try{let i={accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt,savedAt:Date.now()},n=await a.encryptData(JSON.stringify(i));t.setItem(a.TOKEN_KEY,n),_chunkCR5KJUSTjs.a.debug("Crudify: Tokens saved successfully")}catch(i){_chunkCR5KJUSTjs.a.error("Crudify: Failed to save tokens",i instanceof Error?i:{message:String(i)})}}static async getTokens(){let e=a.getStorage();if(!e)return null;try{let t=e.getItem(a.TOKEN_KEY);if(!t)return null;let i=await a.decryptData(t);if(!i)return _chunkCR5KJUSTjs.a.warn("Crudify: Failed to decrypt tokens, clearing storage"),await a.clearTokens(),null;let n=JSON.parse(i);return!n.accessToken||!n.refreshToken||!n.expiresAt||!n.refreshExpiresAt?(_chunkCR5KJUSTjs.a.warn("Crudify: Incomplete token data found, clearing storage"),await a.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(_chunkCR5KJUSTjs.a.info("Crudify: Refresh token expired, clearing storage"),await a.clearTokens(),null):{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,refreshExpiresAt:n.refreshExpiresAt}}catch(t){return _chunkCR5KJUSTjs.a.error("Crudify: Failed to retrieve tokens",t instanceof Error?t:{message:String(t)}),await a.clearTokens(),null}}static async clearTokens(){let e=a.getStorage();if(e)try{e.removeItem(a.TOKEN_KEY),_chunkCR5KJUSTjs.a.debug("Crudify: Tokens cleared from storage")}catch(t){_chunkCR5KJUSTjs.a.error("Crudify: Failed to clear tokens",t instanceof Error?t:{message:String(t)})}}static async rotateEncryptionKey(){try{await a.clearTokens(),a.encryptionKey=null,a.salt=null,a.fingerprint=null,a.initPromise=null;try{localStorage.removeItem(a.ENCRYPTION_KEY_STORAGE),localStorage.removeItem(a.SALT_KEY)}catch (e8){}_chunkCR5KJUSTjs.a.info("Crudify: Encryption key rotated successfully")}catch(e){_chunkCR5KJUSTjs.a.error("Crudify: Failed to rotate encryption key",e instanceof Error?e:{message:String(e)})}}static async hasValidTokens(){return await a.getTokens()!==null}static async ensureInitialized(){await a.initialize()}static async getExpirationInfo(){let e=await a.getTokens();if(!e)return null;let t=Date.now();return{accessExpired:t>=e.expiresAt,refreshExpired:t>=e.refreshExpiresAt,accessExpiresIn:Math.max(0,e.expiresAt-t),refreshExpiresIn:Math.max(0,e.refreshExpiresAt-t)}}static async updateAccessToken(e,t){let i=await a.getTokens();if(!i){_chunkCR5KJUSTjs.a.warn("Crudify: Cannot update access token, no existing tokens found");return}await a.saveTokens({...i,accessToken:e,expiresAt:t})}static createSyncEvent(e,t,i){return{type:e,tokens:t,hadPreviousTokens:i}}static markLocalChange(){a.ignoreNextStorageEvent=!0,a.ignoreStorageEventTimeout&&clearTimeout(a.ignoreStorageEventTimeout),a.ignoreStorageEventTimeout=setTimeout(()=>{a.ignoreNextStorageEvent=!1},100)}static markSuccessfulLogin(){a.lastSuccessfulLoginTime=Date.now()}static isWithinLoginGracePeriod(){return a.lastSuccessfulLoginTime===0?!1:Date.now()-a.lastSuccessfulLoginTime<a.LOGIN_GRACE_PERIOD_MS}static subscribeToChanges(e){let t=async i=>{if(i.key!==a.TOKEN_KEY)return;if(a.ignoreNextStorageEvent){a.ignoreNextStorageEvent=!1;return}if(i.newValue===null&&a.isWithinLoginGracePeriod())return;if(i.newValue===null){let l=_optionalChain([a, 'access', _2 => _2.getStorage, 'call', _3 => _3(), 'optionalAccess', _4 => _4.getItem, 'call', _5 => _5(a.TOKEN_KEY)]);if(l!==null&&l!=="")return}let n=i.oldValue!==null&&i.oldValue!=="";if(i.newValue===null){_chunkCR5KJUSTjs.a.debug("Crudify: Tokens removed in another tab"),e(null,a.SYNC_EVENTS.TOKENS_CLEARED,n);return}if(i.newValue){_chunkCR5KJUSTjs.a.debug("Crudify: Tokens updated in another tab");let s=await a.getTokens();e(s,a.SYNC_EVENTS.TOKENS_UPDATED,n)}};return window.addEventListener("storage",t),()=>{window.removeEventListener("storage",t)}}};a.TOKEN_KEY="crudify_tokens",a.ENCRYPTION_KEY_STORAGE="crudify_enc_key",a.SALT_KEY="crudify_enc_salt",a.encryptionKey=null,a.salt=null,a.fingerprint=null,a.storageType="localStorage",a.initPromise=null,a.lastSuccessfulLoginTime=0,a.LOGIN_GRACE_PERIOD_MS=5e3,a.SYNC_EVENTS={TOKENS_CLEARED:"TOKENS_CLEARED",TOKENS_UPDATED:"TOKENS_UPDATED"},a.ignoreNextStorageEvent=!1,a.ignoreStorageEventTimeout=null;var v=a;var K=class K{constructor(){this.broadcastChannel=null;this.CHANNEL_NAME="crudify-session-sync";this.listeners=new Set;this.isInitialized=!1;this.tabId=K.generateTabId(),this.initialize()}static generateTabId(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,9);return`tab_${e}_${t}`}static getInstance(){return K.instance||(K.instance=new K),K.instance}static resetInstance(){K.instance&&(K.instance.destroy(),K.instance=null)}initialize(){if(!this.isInitialized)try{typeof BroadcastChannel<"u"?(this.broadcastChannel=new BroadcastChannel(this.CHANNEL_NAME),this.broadcastChannel.onmessage=e=>{this.handleMessage(e.data)},this.broadcastChannel.onmessageerror=()=>{_chunkCR5KJUSTjs.a.warn("Crudify: CrossTabSync message error")},_chunkCR5KJUSTjs.a.debug("Crudify: CrossTabSync initialized with BroadcastChannel")):_chunkCR5KJUSTjs.a.debug("Crudify: BroadcastChannel not available, using localStorage fallback"),this.isInitialized=!0}catch(e){_chunkCR5KJUSTjs.a.warn("Crudify: Failed to initialize CrossTabSync",{message:e instanceof Error?e.message:String(e)})}}destroy(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.listeners.clear(),this.isInitialized=!1}getTabId(){return this.tabId}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyLogin(){this.broadcast({type:"SESSION_STARTED",tabId:this.tabId,timestamp:Date.now()})}notifyLogout(){this.broadcast({type:"SESSION_ENDED",tabId:this.tabId,timestamp:Date.now()})}notifyTokenRefreshed(){this.broadcast({type:"TOKEN_REFRESHED",tabId:this.tabId,timestamp:Date.now()})}ping(){this.broadcast({type:"SESSION_PING",tabId:this.tabId,timestamp:Date.now()})}broadcast(e){this.isInitialized||this.initialize();try{this.broadcastChannel&&(this.broadcastChannel.postMessage(e),_chunkCR5KJUSTjs.a.debug(`Crudify: CrossTab broadcast ${e.type}`))}catch(t){_chunkCR5KJUSTjs.a.warn("Crudify: Failed to broadcast cross-tab message",{message:t instanceof Error?t.message:String(t)})}}handleMessage(e){e.tabId!==this.tabId&&(_chunkCR5KJUSTjs.a.debug(`Crudify: CrossTab received ${e.type} from ${e.tabId}`),e.type==="SESSION_PING"&&this.broadcast({type:"SESSION_PONG",tabId:this.tabId,timestamp:Date.now(),payload:{respondingTo:e.tabId}}),this.listeners.forEach(t=>{try{t(e)}catch(i){_chunkCR5KJUSTjs.a.error("Crudify: CrossTab listener error",{message:i instanceof Error?i.message:String(i)})}}))}};K.instance=null;var Ee=K,$= exports.c =Ee.getInstance();var _crudifysdk = require('@nocios/crudify-sdk'); var _crudifysdk2 = _interopRequireDefault(_crudifysdk);var se="crudify_auth",Se=r=>{if(r==="dev"||typeof window>"u"||!window.location)return"";if(!r){let e=window.location.hostname;return e?e.endsWith(".nocios.link")||e==="nocios.link"?".nocios.link":e.endsWith(".crudia.com")||e==="crudia.com"?".crudia.com":"":""}return r==="prod"||r==="api"?".crudia.com":".nocios.link"},Ot=(r,e,t)=>{if(typeof document>"u"){_chunkCR5KJUSTjs.a.debug("[CookieSync] No document available (SSR), skipping cookie set");return}if(!r){_chunkCR5KJUSTjs.a.warn("[CookieSync] Attempted to set cookie with empty token");return}try{let i=Se(t),n=Date.now(),s=Math.max(0,Math.floor((e-n)/1e3)),l=[`${se}=${encodeURIComponent(r)}`,"path=/","SameSite=Lax",`max-age=${s}`];typeof window<"u"&&window.location.protocol==="https:"&&l.push("Secure"),i&&l.push(`domain=${i}`),document.cookie=l.join("; "),_chunkCR5KJUSTjs.a.debug("[CookieSync] Cookie set successfully",{domain:i||"(current host)",maxAgeSeconds:s,tokenLength:r.length})}catch(i){_chunkCR5KJUSTjs.a.error("[CookieSync] Failed to set cookie",i instanceof Error?i:{message:String(i)})}},Ft=r=>{if(typeof document>"u"){_chunkCR5KJUSTjs.a.debug("[CookieSync] No document available (SSR), skipping cookie clear");return}try{let e=Se(r),t=[`${se}=`,"path=/","max-age=0","expires=Thu, 01 Jan 1970 00:00:00 GMT"];e&&t.push(`domain=${e}`),document.cookie=t.join("; "),document.cookie=`${se}=; path=/; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 GMT`,_chunkCR5KJUSTjs.a.debug("[CookieSync] Cookie cleared successfully",{domain:e||"(current host)"})}catch(e){_chunkCR5KJUSTjs.a.error("[CookieSync] Failed to clear cookie",e instanceof Error?e:{message:String(e)})}},zt=()=>{if(typeof document>"u")return null;try{let e=document.cookie.split(";").map(i=>i.trim()).find(i=>i.startsWith(`${se}=`));if(!e)return null;let t=e.split("=")[1];return t?decodeURIComponent(t):null}catch(r){return _chunkCR5KJUSTjs.a.error("[CookieSync] Failed to read cookie",r instanceof Error?r:{message:String(r)}),null}},j={setCrossSubdomainCookie:Ot,clearCrossSubdomainCookie:Ft,getCrossSubdomainCookie:zt,getCookieDomain:Se};var oe=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null;this.isSessionActive=!1;this.isColdStartRestore=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(e={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...e},v.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),_crudifysdk2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let t=await v.getTokens();t?await v.saveTokens({...t,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):await v.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(e,t){try{let i=await _crudifysdk2.default.login(e,t);if(!i.success)return{success:!1,error:this.formatError(i.errors),rawResponse:i};let n=await v.getTokens(),s=i.data,l={accessToken:s.token,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt,apiEndpointAdmin:_optionalChain([n, 'optionalAccess', _6 => _6.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([n, 'optionalAccess', _7 => _7.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return await v.saveTokens(l),v.markSuccessfulLogin(),this.lastActivityTime=Date.now(),this.isSessionActive=!0,this.isColdStartRestore=!1,j.setCrossSubdomainCookie(l.accessToken,l.expiresAt,this.config.env),$.notifyLogin(),_optionalChain([this, 'access', _8 => _8.config, 'access', _9 => _9.onLoginSuccess, 'optionalCall', _10 => _10(l)]),{success:!0,tokens:l,data:s}}catch(i){return _chunkCR5KJUSTjs.a.error("[SessionManager] Login error",i instanceof Error?i:{message:String(i)}),{success:!1,error:i instanceof Error?i.message:"Unknown error"}}}async logout(){this.isSessionActive=!1;try{this.log("Logging out..."),_chunkCR5KJUSTjs.f.emit("LOGOUT",{message:"User logged out",source:"SessionManager.logout"}),j.clearCrossSubdomainCookie(this.config.env),await _crudifysdk2.default.logout(),await v.clearTokens(),$.notifyLogout(),this.log("Logout successful"),_optionalChain([this, 'access', _11 => _11.config, 'access', _12 => _12.onLogout, 'optionalCall', _13 => _13()])}catch(e){this.log("Logout error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),$.notifyLogout()}}async restoreSession(){try{this.isColdStartRestore=!0,this.log("Attempting to restore session (cold start)...");let e=await v.getTokens();if(!e)return this.log("No valid tokens found in storage"),this.isColdStartRestore=!1,!1;if(Date.now()>=e.refreshExpiresAt)return this.log("Refresh token expired, clearing storage (cold start - no notification)"),await v.clearTokens(),this.isColdStartRestore=!1,!1;if(_crudifysdk2.default.setTokens({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt}),_crudifysdk2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<e.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting silent refresh..."),await this.refreshTokensSilent())){this.log("Session restored successfully via silent token refresh"),this.isSessionActive=!0,this.isColdStartRestore=!1;let n=await v.getTokens();return n&&_optionalChain([this, 'access', _14 => _14.config, 'access', _15 => _15.onSessionRestored, 'optionalCall', _16 => _16(n)]),!0}return this.log("Could not restore session, clearing tokens (cold start - no notification)"),await v.clearTokens(),await _crudifysdk2.default.logout(),this.isColdStartRestore=!1,!1}return this.log("Session restored successfully"),this.isSessionActive=!0,this.isColdStartRestore=!1,this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _17 => _17.config, 'access', _18 => _18.onSessionRestored, 'optionalCall', _19 => _19(e)]),!0}catch(e){return this.log("Session restore error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),await _crudifysdk2.default.logout(),this.isColdStartRestore=!1,!1}}async isAuthenticated(){return _crudifysdk2.default.isLogin()||await v.hasValidTokens()}async getTokenInfo(){let e=_crudifysdk2.default.getTokenData(),t=await v.getExpirationInfo(),i=await v.getTokens();return{isLoggedIn:await this.isAuthenticated(),crudifyTokens:e,storageInfo:t,hasValidTokens:await v.hasValidTokens(),apiEndpointAdmin:_optionalChain([i, 'optionalAccess', _20 => _20.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([i, 'optionalAccess', _21 => _21.apiKeyEndpointAdmin])}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let e=await _crudifysdk2.default.refreshAccessToken();if(!e.success)return this.log("Token refresh failed",{errors:e.errors}),await v.clearTokens(),this.isSessionActive&&!this.isColdStartRestore&&_optionalChain([this, 'access', _22 => _22.config, 'access', _23 => _23.showNotification, 'optionalCall', _24 => _24(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _25 => _25.config, 'access', _26 => _26.onSessionExpired, 'optionalCall', _27 => _27()]),this.isSessionActive=!1,!1;let t=e.data,i={accessToken:t.token,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt};return await v.saveTokens(i),this.log("Tokens refreshed and saved successfully"),j.setCrossSubdomainCookie(i.accessToken,i.expiresAt,this.config.env),this.lastActivityTime=Date.now(),$.notifyTokenRefreshed(),!0}catch(e){return this.log("Token refresh error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),this.isSessionActive&&!this.isColdStartRestore&&_optionalChain([this, 'access', _28 => _28.config, 'access', _29 => _29.showNotification, 'optionalCall', _30 => _30(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _31 => _31.config, 'access', _32 => _32.onSessionExpired, 'optionalCall', _33 => _33()]),this.isSessionActive=!1,!1}}isRefreshing(){return this.isRefreshingLocally}async refreshTokensSilent(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Silent refresh: waiting for existing refresh promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefreshSilent();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefreshSilent(){try{this.log("Starting silent token refresh (cold start)...");let e=await _crudifysdk2.default.refreshAccessToken();if(!e.success)return this.log("Silent token refresh failed",{errors:e.errors}),await v.clearTokens(),!1;let t=e.data,i={accessToken:t.token,refreshToken:t.refreshToken,expiresAt:t.expiresAt,refreshExpiresAt:t.refreshExpiresAt};return await v.saveTokens(i),this.log("Tokens refreshed silently and saved successfully"),j.setCrossSubdomainCookie(i.accessToken,i.expiresAt,this.config.env),this.lastActivityTime=Date.now(),$.notifyTokenRefreshed(),!0}catch(e){return this.log("Silent token refresh error",{error:e instanceof Error?e.message:String(e)}),await v.clearTokens(),!1}}getIsSessionActive(){return this.isSessionActive}setupResponseInterceptor(){_crudifysdk2.default.setResponseInterceptor(async e=>{this.updateLastActivity();let t=this.detectAuthorizationError(e);if(t.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:t.errorType,shouldLogout:t.shouldTriggerLogout}),t.isRefreshTokenInvalid||t.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),_chunkCR5KJUSTjs.f.emit("TOKEN_REFRESH_FAILED",{message:t.userFriendlyMessage,error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"}),e;t.shouldTriggerLogout&&(await v.hasValidTokens()&&!t.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunkCR5KJUSTjs.f.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),_chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:t.userFriendlyMessage,error:t.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return e}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let e=_crudifysdk2.default.getTokenData();if(e&&e.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let t=this.config.env||"stg";_crudifysdk2.default.config(t);let i=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none",s=await _crudifysdk2.default.init(i,n);if(s&&s.success===!1&&s.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(e){throw _chunkCR5KJUSTjs.a.error("[SessionManager] Failed to initialize crudify",e instanceof Error?e:{message:String(e)}),e}}detectAuthorizationError(e){let t={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(e.errors&&Array.isArray(e.errors)){let i=e.errors.find(n=>n.errorType==="Unauthorized"||_optionalChain([n, 'access', _34 => _34.message, 'optionalAccess', _35 => _35.includes, 'call', _36 => _36("Unauthorized")])||_optionalChain([n, 'access', _37 => _37.message, 'optionalAccess', _38 => _38.includes, 'call', _39 => _39("Not Authorized")])||_optionalChain([n, 'access', _40 => _40.message, 'optionalAccess', _41 => _41.includes, 'call', _42 => _42("NOT_AUTHORIZED")])||_optionalChain([n, 'access', _43 => _43.message, 'optionalAccess', _44 => _44.includes, 'call', _45 => _45("Token")])||_optionalChain([n, 'access', _46 => _46.message, 'optionalAccess', _47 => _47.includes, 'call', _48 => _48("TOKEN")])||_optionalChain([n, 'access', _49 => _49.message, 'optionalAccess', _50 => _50.includes, 'call', _51 => _51("Authentication")])||_optionalChain([n, 'access', _52 => _52.message, 'optionalAccess', _53 => _53.includes, 'call', _54 => _54("UNAUTHENTICATED")])||_optionalChain([n, 'access', _55 => _55.extensions, 'optionalAccess', _56 => _56.code])==="UNAUTHENTICATED"||_optionalChain([n, 'access', _57 => _57.extensions, 'optionalAccess', _58 => _58.code])==="FORBIDDEN");i&&(t.isAuthError=!0,t.errorType="GraphQL Array",t.errorDetails=i,t.shouldTriggerLogout=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(_optionalChain([i, 'access', _59 => _59.message, 'optionalAccess', _60 => _60.includes, 'call', _61 => _61("TOKEN")])||_optionalChain([i, 'access', _62 => _62.message, 'optionalAccess', _63 => _63.includes, 'call', _64 => _64("Token")]))&&(t.isTokenExpired=!0),_optionalChain([i, 'access', _65 => _65.extensions, 'optionalAccess', _66 => _66.code])==="UNAUTHENTICATED"&&(t.isUnauthorized=!0))}if(!t.isAuthError&&e.errors&&typeof e.errors=="object"&&!Array.isArray(e.errors)){let n=Object.values(e.errors).flat().find(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.includes("INVALID_TOKEN")));n&&typeof n=="string"&&(t.isAuthError=!0,t.errorType="GraphQL Object",t.errorDetails=e.errors,t.shouldTriggerLogout=!0,n.includes("TOKEN_REFRESH_FAILED")?(t.isTokenRefreshFailed=!0,t.isRefreshTokenInvalid=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("TOKEN_HAS_EXPIRED")||n.includes("SESSION_EXPIRED")?(t.isTokenExpired=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("INVALID_TOKEN")?(t.isTokenExpired=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!t.isAuthError&&_optionalChain([e, 'access', _67 => _67.data, 'optionalAccess', _68 => _68.response, 'optionalAccess', _69 => _69.status])){let i=e.data.response.status.toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED")&&(t.isAuthError=!0,t.errorType="Status",t.errorDetails=e.data.response,t.isUnauthorized=!0,t.shouldTriggerLogout=!0,t.isIrrecoverable=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!t.isAuthError&&_optionalChain([e, 'access', _70 => _70.data, 'optionalAccess', _71 => _71.response, 'optionalAccess', _72 => _72.data]))try{let i=typeof e.data.response.data=="string"?JSON.parse(e.data.response.data):e.data.response.data;(i.error==="REFRESH_TOKEN_INVALID"||i.error==="TOKEN_EXPIRED"||i.error==="INVALID_TOKEN")&&(t.isAuthError=!0,t.errorType="Parsed Data",t.errorDetails=i,t.shouldTriggerLogout=!0,t.isIrrecoverable=!0,i.error==="REFRESH_TOKEN_INVALID"?(t.isRefreshTokenInvalid=!0,t.isTokenRefreshFailed=!0,t.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(t.isTokenExpired=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch (e9){}if(!t.isAuthError&&e.errorCode){let i=String(e.errorCode).toUpperCase();(i==="UNAUTHORIZED"||i==="UNAUTHENTICATED"||i==="TOKEN_EXPIRED"||i==="INVALID_TOKEN")&&(t.isAuthError=!0,t.errorType="Error Code",t.errorDetails={errorCode:i},t.shouldTriggerLogout=!0,i==="TOKEN_EXPIRED"?t.isTokenExpired=!0:t.isUnauthorized=!0,t.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return t}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let e=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let t=1800*1e3;return e>t?(this.log(`Inactivity timeout: ${Math.floor(e/6e4)} minutes since last activity`),"logout"):"none"}async clearSession(){j.clearCrossSubdomainCookie(this.config.env),await v.clearTokens(),await _crudifysdk2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunkCR5KJUSTjs.m.call(void 0, "SESSION_EXPIRED",{translateFn:this.config.translateFn,enableDebug:this.config.enableLogging}):"Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."}log(e,t){this.config.enableLogging&&_chunkCR5KJUSTjs.a.debug(`[SessionManager] ${e}`,t)}formatError(e){return e?typeof e=="string"?e:typeof e=="object"?Object.values(e).flat().map(String).join(", "):"Authentication failed":"Unknown error"}};var _react = require('react'); var _react2 = _interopRequireDefault(_react);var Ge={isAuthenticated:!1,isLoading:!0,isLoggingOut:!1,isInitialized:!1,tokens:null,error:null};function _e(){let[r,e]=_react.useState.call(void 0, Ge),t=_react.useCallback.call(void 0, o=>{e(f=>({...f,isLoading:o}))},[]),i=_react.useCallback.call(void 0, (o,f)=>{e(E=>({...E,isAuthenticated:o,tokens:f,error:o?null:E.error}))},[]),n=_react.useCallback.call(void 0, o=>{e(f=>({...f,isLoggingOut:o}))},[]),s=_react.useCallback.call(void 0, o=>{e(f=>({...f,error:o}))},[]),l=_react.useCallback.call(void 0, o=>{e(f=>({...f,isInitialized:o}))},[]);return{state:r,setState:e,setLoading:t,setAuthenticated:i,setLoggingOut:n,setError:s,setInitialized:l}}var ae={AGGRESSIVE:3e4,MODERATE:6e4,RELAXED:12e4},Te={AGGRESSIVE:300*1e3,MODERATE:1800*1e3},Ve=.5;function $e(r){return r?r.expiresAt-Date.now()<3e5:!1}function Ye(r){return r?Math.max(0,r.expiresAt-Date.now()):0}function We(r){return r?Math.max(0,r.refreshExpiresAt-Date.now()):0}function Y(r){return r.crudifyTokens.accessToken?{accessToken:r.crudifyTokens.accessToken,refreshToken:r.crudifyTokens.refreshToken||"",expiresAt:r.crudifyTokens.expiresAt,refreshExpiresAt:r.crudifyTokens.refreshExpiresAt}:null}function Be(r){let{sessionManager:e,stateManager:t}=r,i=_react.useCallback.call(void 0, async(o,f)=>{t.setState(E=>({...E,isLoading:!0,isLoggingOut:!1,error:null}));try{let E=await e.login(o,f);return E.success&&E.tokens?t.setState(b=>({...b,isAuthenticated:!0,tokens:E.tokens,isLoading:!1,isLoggingOut:!1,error:null})):t.setState(b=>({...b,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:null})),E}catch(E){let b=E instanceof Error?E.message:"Login failed";_chunkCR5KJUSTjs.a.error("[useSession] Login error",E instanceof Error?E:{message:b});let S=b.includes("INVALID_CREDENTIALS")||b.includes("Invalid email")||b.includes("Invalid password")||b.includes("credentials");return t.setState(m=>({...m,isAuthenticated:!1,tokens:null,isLoading:!1,isLoggingOut:!1,error:S?null:b})),{success:!1,error:b}}},[e,t]),n=_react.useCallback.call(void 0, async()=>{t.setState(o=>({...o,isLoading:!0,isLoggingOut:!0}));try{await e.logout(),t.setState(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(o){t.setState(f=>({...f,isAuthenticated:!1,tokens:null,isLoading:!1,error:o instanceof Error?o.message:"Logout error"}))}},[e,t]),s=_react.useCallback.call(void 0, async()=>{try{let o=await e.refreshTokens();if(o){let f=await e.getTokenInfo();t.setState(E=>({...E,tokens:Y(f),error:null}))}else t.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return o}catch(o){return t.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:o instanceof Error?o.message:"Token refresh failed"})),!1}},[e,t]),l=_react.useCallback.call(void 0, ()=>{t.setError(null)},[t]);return{login:i,logout:n,refreshTokens:s,clearError:l}}function _t(r){return r<Te.AGGRESSIVE?ae.AGGRESSIVE:r<Te.MODERATE?ae.MODERATE:ae.RELAXED}function Xe(r){let{isAuthenticated:e,tokens:t,sessionManager:i,onTokensRefreshed:n,onSessionExpired:s,onSetLoading:l,logout:o}=r,f=_react.useCallback.call(void 0, ()=>{i.updateLastActivity()},[i]);_react.useEffect.call(void 0, ()=>{if(!e||!t)return;let b=_chunkCR5KJUSTjs.q.getInstance().subscribe(f);window.addEventListener("popstate",f);let S,m=!0,I=async()=>{if(!m)return;let k=(await i.getTokenInfo()).crudifyTokens.expiresIn||0,R=_t(k);S=setTimeout(async()=>{if(!m)return;if(i.isRefreshing()){I();return}let x=await i.getTokenInfo(),O=x.crudifyTokens.expiresIn||0,z=((x.crudifyTokens.expiresAt||0)-(Date.now()-O))*Ve;if(O>0&&O<=z)if(l(!0),await i.refreshTokens()){let Z=await i.getTokenInfo();n(Y(Z)),l(!1)}else n(null),s(),l(!1);i.getTimeSinceLastActivity()>18e5?await o():m&&I()},R)};return I(),()=>{m=!1,clearTimeout(S),window.removeEventListener("popstate",f),b()}},[e,t,i,f,n,s,l,o])}function Ze(r){let{sessionManager:e,onTokensUpdated:t,onSessionExpired:i,onSetLoading:n,onSetError:s}=r;_react.useEffect.call(void 0, ()=>{let l=_chunkCR5KJUSTjs.f.subscribe(async o=>{if(o.type==="TOKEN_EXPIRED"){if(e.isRefreshing())return;n(!0);try{if(await e.refreshTokens()){let E=await e.getTokenInfo();t(Y(E)),n(!1)}else _chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(f){_chunkCR5KJUSTjs.f.emit("SESSION_EXPIRED",{message:f instanceof Error?f.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(o.type==="SESSION_EXPIRED"||o.type==="TOKEN_REFRESH_FAILED")&&(t(null),n(!1),_optionalChain([o, 'access', _73 => _73.details, 'optionalAccess', _74 => _74.isColdStart])!==!0&&_optionalChain([o, 'access', _75 => _75.details, 'optionalAccess', _76 => _76.shouldShowNotification])!==!1&&s(_optionalChain([o, 'access', _77 => _77.details, 'optionalAccess', _78 => _78.message, 'optionalAccess', _79 => _79.toString, 'call', _80 => _80()])||"Session expired"),i())});return()=>l()},[e,t,i,n,s])}function je(r){let{isAuthenticated:e,onTokensUpdated:t,onSessionExpired:i}=r;_react.useEffect.call(void 0, ()=>{let n=async l=>{switch(l.type){case"SESSION_STARTED":case"TOKEN_REFRESHED":try{await v.ensureInitialized();let o=await v.getTokens();o&&(_chunkCR5KJUSTjs.a.debug(`[useCrossTabSync] Syncing ${l.type} from tab ${l.tabId}`),t(o))}catch(o){_chunkCR5KJUSTjs.a.warn("[useCrossTabSync] Failed to read tokens after cross-tab event",{error:o instanceof Error?o.message:String(o)})}break;case"SESSION_ENDED":try{await v.hasValidTokens()||(_chunkCR5KJUSTjs.a.debug(`[useCrossTabSync] Syncing SESSION_ENDED from tab ${l.tabId}`),t(null),e&&i())}catch(o){_chunkCR5KJUSTjs.a.warn("[useCrossTabSync] Failed to verify tokens after logout event",{error:o instanceof Error?o.message:String(o)})}break;case"SESSION_PING":case"SESSION_PONG":break}},s=$.subscribe(n);return()=>s()},[e,t,i]),_react.useEffect.call(void 0, ()=>{let n=v.subscribeToChanges(async(s,l,o)=>{if(l===v.SYNC_EVENTS.TOKENS_CLEARED){if(await v.hasValidTokens())return;o&&e?(t(null),i()):o&&t(null)}else l===v.SYNC_EVENTS.TOKENS_UPDATED&&s&&t(s)});return()=>n()},[e,t,i])}async function Je(r){let{sessionManager:e,options:t,stateActions:i}=r;try{i.setState(o=>({...o,isLoading:!0,error:null}));let n={autoRestore:_nullishCoalesce(t.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(t.enableLogging, () => (!1)),showNotification:t.showNotification,translateFn:t.translateFn,apiEndpointAdmin:t.apiEndpointAdmin,apiKeyEndpointAdmin:t.apiKeyEndpointAdmin,publicApiKey:t.publicApiKey,env:t.env||"stg",onSessionExpired:()=>{let o=e.getIsSessionActive();i.setState(f=>({...f,isAuthenticated:!1,tokens:null,error:o?"Session expired":null})),_optionalChain([t, 'access', _81 => _81.onSessionExpired, 'optionalCall', _82 => _82()])},onSessionRestored:o=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:o,error:null})),_optionalChain([t, 'access', _83 => _83.onSessionRestored, 'optionalCall', _84 => _84(o)])},onLoginSuccess:o=>{i.setState(f=>({...f,isAuthenticated:!0,tokens:o,error:null}))},onLogout:()=>{i.setState(o=>({...o,isAuthenticated:!1,tokens:null,error:null}))}};await e.initialize(n),e.setupResponseInterceptor();let s=await e.isAuthenticated(),l=await e.getTokenInfo();i.setState(o=>({...o,isAuthenticated:s,isInitialized:!0,isLoading:!1,isLoggingOut:!1,tokens:Y(l)}))}catch(n){let s=n instanceof Error?n.message:"Initialization failed";_chunkCR5KJUSTjs.a.error("[useSession] Initialize failed",n instanceof Error?n:{message:s}),i.setState(l=>({...l,isLoading:!1,isInitialized:!0,isLoggingOut:!1,error:s}))}}function ve(r={}){let e=oe.getInstance(),t=_e(),{state:i}=t,{login:n,logout:s,refreshTokens:l,clearError:o}=Be({sessionManager:e,stateManager:t}),f=_react.useCallback.call(void 0, g=>{t.setAuthenticated(!!g,g)},[t]),E=_react.useCallback.call(void 0, ()=>{t.setAuthenticated(!1,null),_optionalChain([r, 'access', _85 => _85.onSessionExpired, 'optionalCall', _86 => _86()])},[t,r.onSessionExpired]),b=_react.useCallback.call(void 0, g=>{t.setLoading(g)},[t]),S=_react.useCallback.call(void 0, g=>{t.setError(g)},[t]);_react.useEffect.call(void 0, ()=>{Je({sessionManager:e,options:r,stateActions:t})},[]),Xe({isAuthenticated:i.isAuthenticated,tokens:i.tokens,sessionManager:e,onTokensRefreshed:f,onSessionExpired:E,onSetLoading:b,logout:s}),Ze({sessionManager:e,onTokensUpdated:f,onSessionExpired:E,onSetLoading:b,onSetError:S}),je({isAuthenticated:i.isAuthenticated,onTokensUpdated:f,onSessionExpired:E});let m=_react.useCallback.call(void 0, ()=>{e.updateLastActivity()},[e]),I=_react.useCallback.call(void 0, async()=>e.getTokenInfo(),[e]);return{...i,login:n,logout:s,refreshTokens:l,clearError:o,getTokenInfo:I,updateActivity:m,isExpiringSoon:$e(i.tokens),expiresIn:Ye(i.tokens),refreshExpiresIn:We(i.tokens)}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var _jsxruntime = require('react/jsx-runtime');var et=_react.createContext.call(void 0, null),ei=r=>_dompurify2.default.sanitize(r,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),be= exports.f =({children:r,maxNotifications:e=5,defaultAutoHideDuration:t=6e3,position:i={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[l,o]=_react.useState.call(void 0, []),f=_react.useCallback.call(void 0, (m,I="info",g)=>{if(!n)return"";if(!m||typeof m!="string")return _chunkCR5KJUSTjs.a.warn("GlobalNotificationProvider: Invalid message provided"),"";m.length>1e3&&(_chunkCR5KJUSTjs.a.warn("GlobalNotificationProvider: Message too long, truncating"),m=m.substring(0,1e3)+"...");let k=_uuid.v4.call(void 0, ),R={id:k,message:m,severity:I,autoHideDuration:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _87 => _87.autoHideDuration]), () => (t)),persistent:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _88 => _88.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([g, 'optionalAccess', _89 => _89.allowHtml]), () => (s))};return o(x=>[...x.length>=e?x.slice(-(e-1)):x,R]),k},[e,t,n,s]),E=_react.useCallback.call(void 0, m=>{o(I=>I.filter(g=>g.id!==m))},[]),b=_react.useCallback.call(void 0, ()=>{o([])},[]),S={showNotification:f,hideNotification:E,clearAllNotifications:b};return _jsxruntime.jsxs.call(void 0, et.Provider,{value:S,children:[r,n&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[i.vertical]:(i.vertical==="top",24),[i.horizontal]:i.horizontal==="right"||i.horizontal==="left"?24:"50%",...i.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:i.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:l.map(m=>_jsxruntime.jsx.call(void 0, ti,{notification:m,onClose:()=>E(m.id)},m.id))})})]})},ti=({notification:r,onClose:e})=>{let[t,i]=_react.useState.call(void 0, !0),n=_react.useCallback.call(void 0, (s,l)=>{l!=="clickaway"&&(i(!1),setTimeout(e,300))},[e]);return _react.useEffect.call(void 0, ()=>{if(!r.persistent&&r.autoHideDuration){let s=setTimeout(()=>{n()},r.autoHideDuration);return()=>clearTimeout(s)}},[r.autoHideDuration,r.persistent,n]),_jsxruntime.jsx.call(void 0, _material.Snackbar,{open:t,onClose:n,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:_jsxruntime.jsx.call(void 0, _material.Alert,{variant:"filled",severity:r.severity,onClose:n,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?_jsxruntime.jsx.call(void 0, "span",{dangerouslySetInnerHTML:{__html:ei(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},tt= exports.g =()=>{let r=_react.useContext.call(void 0, et);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var Ie=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(e){this.credentials=e,this.isReady=!0,this.listeners.forEach(t=>{try{t(e)}catch(i){_chunkCR5KJUSTjs.a.error("[CredentialsEventBus] Error in listener",i instanceof Error?i:{message:String(i)})}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(e=>{this.listeners.push(e)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},ue= exports.h =Ie.getInstance();var it=_react.createContext.call(void 0, void 0),rt= exports.i =({config:r,children:e})=>{let[t,i]=_react.useState.call(void 0, !0),[n,s]=_react.useState.call(void 0, null),[l,o]=_react.useState.call(void 0, !1),[f,E]=_react.useState.call(void 0, ""),[b,S]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){s("No publicApiKey provided"),i(!1),o(!1);return}let I=`${r.publicApiKey}-${r.env}`;if(I===f&&l){i(!1);return}(async()=>{i(!0),s(null),o(!1);try{_crudifysdk2.default.config(r.env||"prod");let k=await _crudifysdk2.default.init(r.publicApiKey,"none");if(S(k),typeof _crudifysdk2.default.transaction=="function"&&typeof _crudifysdk2.default.login=="function")o(!0),E(I),k.apiEndpointAdmin&&k.apiKeyEndpointAdmin&&ue.notifyCredentialsReady({apiUrl:k.apiEndpointAdmin,apiKey:k.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(k){let R=k instanceof Error?k.message:"Failed to initialize Crudify";_chunkCR5KJUSTjs.a.error("[CrudifyProvider] Initialization error",k instanceof Error?k:{message:String(k)}),s(R),o(!1)}finally{i(!1)}})()},[r.publicApiKey,r.env,f,l]);let m={crudify:l?_crudifysdk2.default:null,isLoading:t,error:n,isInitialized:l,adminCredentials:b};return _jsxruntime.jsx.call(void 0, it.Provider,{value:m,children:e})},nt= exports.j =()=>{let r=_react.useContext.call(void 0, it);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var ot=_react.createContext.call(void 0, void 0);function st({children:r,options:e={},config:t,showNotifications:i=!1,notificationOptions:n={}}){let s;try{let{showNotification:g}=tt();s=g}catch (e10){}let l={};try{let g=nt();g.isInitialized&&g.adminCredentials&&(l=g.adminCredentials)}catch (e11){}let o=_react.useMemo.call(void 0, ()=>{let g=_chunkCR5KJUSTjs.d.call(void 0, {publicApiKey:_optionalChain([t, 'optionalAccess', _90 => _90.publicApiKey]),env:_optionalChain([t, 'optionalAccess', _91 => _91.env]),enableDebug:_optionalChain([e, 'optionalAccess', _92 => _92.enableLogging])});return{publicApiKey:g.publicApiKey,env:g.env||"prod"}},[t,_optionalChain([e, 'optionalAccess', _93 => _93.enableLogging])]),f=_react2.default.useMemo(()=>({...e,showNotification:s,apiEndpointAdmin:l.apiEndpointAdmin,apiKeyEndpointAdmin:l.apiKeyEndpointAdmin,publicApiKey:o.publicApiKey,env:o.env,onSessionExpired:()=>{_optionalChain([e, 'access', _94 => _94.onSessionExpired, 'optionalCall', _95 => _95()])}}),[e,s,l.apiEndpointAdmin,l.apiKeyEndpointAdmin,o]),E=ve(f),b=_react.useMemo.call(void 0, ()=>{let g=_chunkCR5KJUSTjs.d.call(void 0, {publicApiKey:_optionalChain([t, 'optionalAccess', _96 => _96.publicApiKey]),env:_optionalChain([t, 'optionalAccess', _97 => _97.env]),appName:_optionalChain([t, 'optionalAccess', _98 => _98.appName]),logo:_optionalChain([t, 'optionalAccess', _99 => _99.logo]),loginActions:_optionalChain([t, 'optionalAccess', _100 => _100.loginActions]),enableDebug:_optionalChain([e, 'optionalAccess', _101 => _101.enableLogging])});return{publicApiKey:g.publicApiKey,env:g.env,appName:g.appName,loginActions:g.loginActions,logo:g.logo}},[t,_optionalChain([e, 'optionalAccess', _102 => _102.enableLogging])]),S=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([E, 'access', _103 => _103.tokens, 'optionalAccess', _104 => _104.accessToken])||!E.isAuthenticated)return null;try{let g=_chunkCR5KJUSTjs.r.call(void 0, E.tokens.accessToken);if(g&&g.sub&&g.email&&g.subscriber){let k={_id:g.sub,email:g.email,subscriberKey:g.subscriber};return Object.keys(g).forEach(R=>{["sub","email","subscriber"].includes(R)||(k[R]=g[R])}),k}}catch(g){_chunkCR5KJUSTjs.a.error("Error decoding JWT token for sessionData",g instanceof Error?g:{message:String(g)})}return null},[_optionalChain([E, 'access', _105 => _105.tokens, 'optionalAccess', _106 => _106.accessToken]),E.isAuthenticated]),m={...E,sessionData:S,config:b},I={enabled:i,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, ot.Provider,{value:m,children:r})}function Jr(r){let e={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _107 => _107.notificationOptions, 'optionalAccess', _108 => _108.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _109 => _109.notificationOptions, 'optionalAccess', _110 => _110.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _111 => _111.notificationOptions, 'optionalAccess', _112 => _112.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _113 => _113.notificationOptions, 'optionalAccess', _114 => _114.allowHtml])||!1};return _optionalChain([r, 'access', _115 => _115.config, 'optionalAccess', _116 => _116.publicApiKey])?_jsxruntime.jsx.call(void 0, rt,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:_jsxruntime.jsx.call(void 0, be,{...e,children:_jsxruntime.jsx.call(void 0, st,{...r})})}):_jsxruntime.jsx.call(void 0, be,{...e,children:_jsxruntime.jsx.call(void 0, st,{...r})})}function ui(){let r=_react.useContext.call(void 0, ot);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Qr(){let r=ui();return r.isInitialized?_jsxruntime.jsxs.call(void 0, "div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[_jsxruntime.jsx.call(void 0, "h4",{children:"Session Debug Info"}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),_jsxruntime.jsxs.call(void 0, "div",{children:[_jsxruntime.jsx.call(void 0, "strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):_jsxruntime.jsx.call(void 0, "div",{children:"Session not initialized"})}var on=(r={})=>{let{autoFetch:e=!0,retryOnError:t=!1,maxRetries:i=3}=r,[n,s]=_react.useState.call(void 0, null),[l,o]=_react.useState.call(void 0, !1),[f,E]=_react.useState.call(void 0, null),[b,S]=_react.useState.call(void 0, {}),m=_react.useRef.call(void 0, null),I=_react.useRef.call(void 0, !0),g=_react.useRef.call(void 0, 0),k=_react.useRef.call(void 0, 0),R=_react.useCallback.call(void 0, ()=>{s(null),E(null),o(!1),S({})},[]),x=_react.useCallback.call(void 0, async()=>{let O=_chunkCR5KJUSTjs.s.call(void 0, );if(!O){I.current&&(E("No user email available"),o(!1));return}m.current&&m.current.abort();let C=new AbortController;m.current=C;let F=++g.current;try{I.current&&(o(!0),E(null));let z=await _crudifysdk2.default.readItems("users",{filter:{email:O},pagination:{limit:1}});if(F===g.current&&I.current&&!C.signal.aborted){let L=z.data;if(z.success&&L&&L.length>0){let T=L[0];s(T);let Z={fullProfile:T,totalFields:Object.keys(T).length,displayData:{id:T.id,email:T.email,username:T.username,firstName:T.firstName,lastName:T.lastName,fullName:T.fullName||`${T.firstName||""} ${T.lastName||""}`.trim(),role:T.role,permissions:T.permissions||[],isActive:T.isActive,lastLogin:T.lastLogin,createdAt:T.createdAt,updatedAt:T.updatedAt,...Object.keys(T).filter(V=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(V)).reduce((V,ne)=>({...V,[ne]:T[ne]}),{})}};S(Z),E(null),k.current=0}else E("User profile not found"),s(null),S({})}}catch(z){if(F===g.current&&I.current){let L=z;if(L.name==="AbortError")return;t&&k.current<i&&(_optionalChain([L, 'access', _117 => _117.message, 'optionalAccess', _118 => _118.includes, 'call', _119 => _119("Network Error")])||_optionalChain([L, 'access', _120 => _120.message, 'optionalAccess', _121 => _121.includes, 'call', _122 => _122("Failed to fetch")]))?(k.current++,setTimeout(()=>{I.current&&x()},1e3*k.current)):(E("Failed to load user profile"),s(null),S({}))}}finally{F===g.current&&I.current&&o(!1),m.current===C&&(m.current=null)}},[t,i]);return _react.useEffect.call(void 0, ()=>{e&&x()},[e,x]),_react.useEffect.call(void 0, ()=>(I.current=!0,()=>{I.current=!1,m.current&&(m.current.abort(),m.current=null)}),[]),{userProfile:n,loading:l,error:f,extendedData:b,refreshProfile:x,clearProfile:R}};var un=(r,e={})=>{let{autoFetch:t=!0,onSuccess:i,onError:n}=e,{prefix:s,padding:l=0,separator:o=""}=r,[f,E]=_react.useState.call(void 0, ""),[b,S]=_react.useState.call(void 0, !1),[m,I]=_react.useState.call(void 0, null),g=_react.useRef.call(void 0, !1),k=_react.useCallback.call(void 0, C=>{let F=String(C).padStart(l,"0");return`${s}${o}${F}`},[s,l,o]),R=_react.useCallback.call(void 0, async()=>{S(!0),I(null);try{let C=await _crudifysdk2.default.getNextSequence(s),F=C.data;if(C.success&&_optionalChain([F, 'optionalAccess', _123 => _123.value])){let z=k(F.value);E(z),_optionalChain([i, 'optionalCall', _124 => _124(z)])}else{let z=_optionalChain([C, 'access', _125 => _125.errors, 'optionalAccess', _126 => _126._error, 'optionalAccess', _127 => _127[0]])||"Failed to generate code";I(z),_optionalChain([n, 'optionalCall', _128 => _128(z)])}}catch(C){let F=C instanceof Error?C.message:"Unknown error";I(F),_optionalChain([n, 'optionalCall', _129 => _129(F)])}finally{S(!1)}},[s,k,i,n]),x=_react.useCallback.call(void 0, async()=>{await R()},[R]),O=_react.useCallback.call(void 0, ()=>{I(null)},[]);return _react.useEffect.call(void 0, ()=>{t&&!f&&!g.current&&(g.current=!0,R())},[t,f,R]),{value:f,loading:b,error:m,regenerate:x,clearError:O}};var Ce=class r{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(e){let{priority:t,publicApiKey:i,env:n,enableLogging:s,requestedBy:l}=e;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==i&&_chunkCR5KJUSTjs.a.warn(`[CrudifyInitialization] ${l} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _130 => _130.state, 'access', _131 => _131.publicApiKey, 'optionalAccess', _132 => _132.slice, 'call', _133 => _133(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} waiting for ongoing initialization...`),this.initializationPromise;if(t==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(l),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(l),this.getState().status==="INITIALIZED"){s&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} found initialization completed by HIGH priority`);return}s&&_chunkCR5KJUSTjs.a.warn(`[CrudifyInitialization] ${l} timeout waiting for HIGH priority, initializing with LOW priority`)}t==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(_chunkCR5KJUSTjs.a.warn(`[CrudifyInitialization] HIGH priority request from ${l} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] ${l} starting initialization (${t} priority)...`),this.state.status="INITIALIZING",this.state.priority=t,this.state.initializedBy=l,this.initializationPromise=this.performInitialization(i,n,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=i,this.state.env=n,this.state.error=null,s&&_chunkCR5KJUSTjs.a.info(`[CrudifyInitialization] Successfully initialized by ${l} (${t} priority)`)}catch(o){throw this.state.status="ERROR",this.state.error=o instanceof Error?o:new Error(String(o)),this.initializationPromise=null,_chunkCR5KJUSTjs.a.error(`[CrudifyInitialization] Initialization failed for ${l}`,o instanceof Error?o:{message:String(o)}),o}}async waitForHighPriorityOrTimeout(e){return new Promise(t=>{let n=0,s=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),t();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),e&&_chunkCR5KJUSTjs.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),t())},10)})}async performInitialization(e,t,i){let n=_crudifysdk2.default.getTokenData();if(n&&n.endpoint){i&&_chunkCR5KJUSTjs.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifysdk2.default.config(t);let s=i?"debug":"none",l=await _crudifysdk2.default.init(e,s);if(l.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(l.errors||"Unknown error")}`);l.apiEndpointAdmin&&l.apiKeyEndpointAdmin&&ue.notifyCredentialsReady({apiUrl:l.apiEndpointAdmin,apiKey:l.apiKeyEndpointAdmin})}reset(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null},this.initializationPromise=null,this.highPriorityInitializerPresent=!1,this.waitingForHighPriority.clear()}isInitialized(){return this.state.status==="INITIALIZED"}getDiagnostics(){return{...this.state,waitingCount:this.waitingForHighPriority.size,waitingComponents:Array.from(this.waitingForHighPriority),hasActivePromise:this.initializationPromise!==null}}},re= exports.q =Ce.getInstance();var ut=r=>{let e=new Uint8Array(r);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").substring(0,r)},ct=()=>`file_${Date.now()}_${ut(7)}`,yi=r=>{let e=r.lastIndexOf("."),t=e>0?r.substring(e):"",i=Date.now(),n=ut(6);return`${i}_${n}${t}`},we=(r,e)=>{if(r.startsWith("http://")||r.startsWith("https://"))try{let t=new URL(r);return t.pathname.startsWith("/")?t.pathname.substring(1):t.pathname}catch (e12){if(e&&r.startsWith(e))return r.substring(e.length)}return e&&r.startsWith(e)?r.substring(e.length):r},Tn= exports.r =(r={})=>{let{acceptedTypes:e,maxFileSize:t=10*1024*1024,maxFiles:i,minFiles:n=0,visibility:s="private",onUploadComplete:l,onUploadError:o,onFileRemoved:f,onFilesChange:E,mode:b="edit"}=r,[S,m]=_react.useState.call(void 0, []),[I,g]=_react.useState.call(void 0, !1),[k,R]=_react.useState.call(void 0, !1),[x,O]=_react.useState.call(void 0, []),C=_react.useRef.call(void 0, new Map),F=_react.useCallback.call(void 0, ()=>{g(!0)},[]),z=_react.useCallback.call(void 0, ()=>{R(!0),g(!0)},[]),L=_react.useCallback.call(void 0, (u,p)=>{m(d=>d.map(y=>y.id===u?{...y,...p}:y))},[]),T=_react.useCallback.call(void 0, u=>{_optionalChain([E, 'optionalCall', _134 => _134(u)])},[E]),Z=_react.useCallback.call(void 0, u=>e&&e.length>0&&!e.includes(u.type)?{valid:!1,error:`File type not allowed: ${u.type}`}:u.size>t?{valid:!1,error:`File exceeds maximum size of ${(t/1048576).toFixed(1)}MB`}:{valid:!0},[e,t]),V=_react.useCallback.call(void 0, async(u,p)=>{try{if(!re.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let d=yi(p.name),h=await _crudifysdk2.default.generateSignedUrl({fileName:d,contentType:p.type,visibility:s});if(!h.success||!h.data)throw new Error("Failed to get upload URL");let y=h.data,{uploadUrl:w,s3Key:A,publicUrl:M}=y;if(!w||!A)throw new Error("Incomplete signed URL response");let W=A.indexOf("/"),Nt=W>0?A.substring(W+1):A;L(u.id,{status:"uploading",progress:0}),await new Promise((he,B)=>{let U=new XMLHttpRequest;U.upload.addEventListener("progress",_=>{if(_.lengthComputable){let Lt=Math.round(_.loaded/_.total*100);L(u.id,{progress:Lt})}}),U.addEventListener("load",()=>{U.status>=200&&U.status<300?he():B(new Error(`Upload failed with status ${U.status}`))}),U.addEventListener("error",()=>{B(new Error("Network error during upload"))}),U.addEventListener("abort",()=>{B(new Error("Upload cancelled"))}),U.open("PUT",w),U.setRequestHeader("Content-Type",p.type),U.send(p)});let Dt={status:"completed",progress:100,filePath:Nt,visibility:s,publicUrl:s==="public"?M:void 0,file:void 0};m(he=>{let B=he.map(_=>_.id===u.id?{..._,...Dt}:_);T(B);let U=B.find(_=>_.id===u.id);return U&&_optionalChain([l, 'optionalCall', _135 => _135(U)]),B})}catch(d){let h=d instanceof Error?d.message:"Unknown error";L(u.id,{status:"error",progress:0,errorMessage:h}),m(y=>{let w=y.find(A=>A.id===u.id);return w&&_optionalChain([o, 'optionalCall', _136 => _136(w,h)]),y})}},[L,l,o,s]),ne=_react.useCallback.call(void 0, async u=>{let p=Array.from(u),d=[];m(h=>{if(i!==void 0){let A=h.filter(W=>W.status!=="pendingDeletion"&&W.status!=="error").length,M=i-A;if(M<=0)return _chunkCR5KJUSTjs.a.warn(`File limit of ${i} already reached`),h;p.length>M&&(p=p.slice(0,M),_chunkCR5KJUSTjs.a.warn(`Only ${M} files will be added to not exceed limit`))}let y=[];for(let A of p){let M=Z(A),W={id:ct(),name:A.name,size:A.size,contentType:A.type,status:M.valid?"pending":"error",progress:0,createdAt:Date.now(),file:M.valid?A:void 0,errorMessage:M.error,isExisting:!1};y.push(W)}d=y;let w=[...h,...y];return T(w),w}),setTimeout(()=>{let h=d.filter(y=>y.status==="pending"&&y.file);for(let y of h)if(y.file){let w=V(y,y.file);C.current.set(y.id,w),w.finally(()=>{C.current.delete(y.id)})}},0)},[i,Z,V,T]),dt=_react.useCallback.call(void 0, async u=>{let p=S.find(h=>h.id===u);if(!p)return{needsConfirmation:!1,isExisting:!1};let d=p.isExisting===!0;return b==="create"||!d?{needsConfirmation:!0,isExisting:d}:(O(h=>[...h,u]),m(h=>{let y=h.map(A=>A.id===u?{...A,status:"pendingDeletion"}:A),w=y.filter(A=>A.status!=="pendingDeletion");return T(w),y}),{needsConfirmation:!1,isExisting:d})},[S,b,T]),ft=_react.useCallback.call(void 0, async u=>{let p=S.find(d=>d.id===u);if(!p)return{success:!1,error:"File not found"};if(!p.filePath)return m(d=>{let h=d.filter(y=>y.id!==u);return T(h),h}),{success:!0};try{if(!re.isInitialized())return{success:!1,error:"Crudify not initialized"};let d=we(p.filePath);return(await _crudifysdk2.default.disableFile({filePath:d})).success?(m(y=>{let w=y.filter(A=>A.id!==u);return T(w),w}),_optionalChain([f, 'optionalCall', _137 => _137(p)]),{success:!0}):{success:!1,error:"Failed to delete file"}}catch(d){return{success:!1,error:d instanceof Error?d.message:"Unknown error"}}},[S,T,f]),gt=_react.useCallback.call(void 0, u=>{let p=S.find(d=>d.id===u);return!p||!p.isExisting?!1:(O(d=>d.filter(h=>h!==u)),m(d=>{let h=d.map(y=>y.id===u?{...y,status:"completed"}:y);return T(h),h}),!0)},[S,T]),pt=_react.useCallback.call(void 0, ()=>{x.length!==0&&(m(u=>{let p=u.map(d=>x.includes(d.id)?{...d,status:"completed"}:d);return T(p),p}),O([]))},[x,T]),mt=_react.useCallback.call(void 0, async()=>{if(x.length===0)return{success:!0,errors:[]};let u=[],p=[];if(!re.isInitialized())return{success:!1,errors:["Crudify is not initialized. Please wait for the application to finish loading."]};for(let d of x){let h=S.find(y=>y.id===d);if(!_optionalChain([h, 'optionalAccess', _138 => _138.filePath])){p.push(d);continue}try{let y=we(h.filePath);(await _crudifysdk2.default.disableFile({filePath:y})).success?(p.push(d),_optionalChain([f, 'optionalCall', _139 => _139(h)])):u.push(`Failed to delete ${h.name}`)}catch(y){u.push(`Error deleting ${h.name}: ${y instanceof Error?y.message:"Unknown error"}`)}}return p.length>0&&(m(d=>d.filter(y=>!p.includes(y.id))),O(d=>d.filter(h=>!p.includes(h)))),{success:u.length===0,errors:u}},[S,x,f]),ht=_react.useCallback.call(void 0, ()=>{m([]),T([])},[T]),yt=_react.useCallback.call(void 0, async u=>{let p=S.find(h=>h.id===u);if(!p||p.status!=="error"||!p.file){_chunkCR5KJUSTjs.a.warn("Cannot retry: file not found or no original file");return}L(u,{status:"pending",progress:0,errorMessage:void 0});let d=V(p,p.file);C.current.set(u,d),d.finally(()=>{C.current.delete(u)})},[S,L,V]),Et=_react.useCallback.call(void 0, async()=>{let u=Array.from(C.current.values());return u.length>0&&await Promise.allSettled(u),new Promise(p=>{setTimeout(()=>{m(d=>{let h=d.filter(y=>y.status==="completed"&&y.filePath).map(y=>y.filePath);return p(h),d})},0)})},[]),St=u=>{let p=_optionalChain([u, 'access', _140 => _140.split, 'call', _141 => _141("."), 'access', _142 => _142.pop, 'call', _143 => _143(), 'optionalAccess', _144 => _144.toLowerCase, 'call', _145 => _145()])||"";return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",csv:"text/csv",mp3:"audio/mpeg",wav:"audio/wav",mp4:"video/mp4",webm:"video/webm",zip:"application/zip",rar:"application/x-rar-compressed",json:"application/json",xml:"application/xml"}[p]||"application/octet-stream"},Tt=_react.useCallback.call(void 0, (u,p)=>{let d=u.map(h=>{let y=we(h.filePath,p),w=y.includes("/public/")||y.startsWith("public/")?"public":"private",A=h.contentType||St(h.name);return{id:ct(),name:h.name,size:h.size||0,contentType:A,status:"completed",progress:100,filePath:y,visibility:w,createdAt:Date.now(),isExisting:!0}});m(d),T(d)},[T]),vt=_react.useCallback.call(void 0, async u=>{let p=S.find(d=>d.id===u);if(!p||!p.filePath)return null;if(p.visibility==="public"&&p.publicUrl)return p.publicUrl;try{if(!re.isInitialized())return null;let d=await _crudifysdk2.default.getFileUrl({filePath:p.filePath,expiresIn:3600}),h=d.data;return d.success&&_optionalChain([h, 'optionalAccess', _146 => _146.url])?h.url:null}catch (e13){return null}},[S]),bt=_react.useMemo.call(void 0, ()=>S.some(u=>u.status==="uploading"||u.status==="pending"),[S]),It=_react.useMemo.call(void 0, ()=>S.filter(u=>u.status==="uploading"||u.status==="pending").length,[S]),kt=_react.useMemo.call(void 0, ()=>S.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[S]),q=_react.useMemo.call(void 0, ()=>S.filter(u=>u.status!=="pendingDeletion"),[S]),At=_react.useMemo.call(void 0, ()=>q.filter(u=>u.status==="completed"||u.status==="pending"||u.status==="uploading").length,[q]),{isValid:xt,validationError:Ct,validationErrorKey:wt,validationErrorParams:Rt}=_react.useMemo.call(void 0, ()=>{let u=q.filter(d=>d.status==="completed").length;if(u<n){let d=n===1?"file.validation.minFilesRequired":"file.validation.minFilesRequiredPlural";return{isValid:!1,validationError:d,validationErrorKey:d,validationErrorParams:{count:n}}}return i!==void 0&&u>i?{isValid:!1,validationError:"file.validation.maxFilesExceeded",validationErrorKey:"file.validation.maxFilesExceeded",validationErrorParams:{count:i}}:q.some(d=>d.status==="error")?{isValid:!1,validationError:"file.validation.filesWithErrors",validationErrorKey:"file.validation.filesWithErrors",validationErrorParams:{}}:{isValid:!0,validationError:null,validationErrorKey:null,validationErrorParams:{}}},[q,n,i]),Pt=x.length>0;return{files:S,activeFiles:q,activeFileCount:At,isUploading:bt,pendingCount:It,addFiles:ne,removeFile:dt,deleteFileImmediately:ft,restoreFile:gt,clearFiles:ht,retryUpload:yt,isValid:xt,validationError:Ct,validationErrorKey:wt,validationErrorParams:Rt,waitForUploads:Et,completedFilePaths:kt,initializeFiles:Tt,isTouched:I,markAsTouched:F,isSubmitted:k,markAsSubmitted:z,getPreviewUrl:vt,pendingDeletions:x,hasPendingDeletions:Pt,commitDeletions:mt,restorePendingDeletions:pt}};exports.a = v; exports.b = Ee; exports.c = $; exports.d = oe; exports.e = ve; exports.f = be; exports.g = tt; exports.h = ue; exports.i = rt; exports.j = nt; exports.k = Jr; exports.l = ui; exports.m = Qr; exports.n = on; exports.o = un; exports.p = Ce; exports.q = re; exports.r = Tn;
@@ -0,0 +1 @@
1
+ import{g as Jr,i as Yr,j as he,l as be,n as Zr,o as Qr,r as eo}from"./chunk-PTUSZGL4.mjs";import{g as J}from"./chunk-JAPL7EZJ.mjs";import{a as x,b as Kr,d as qr,f as Gr,p as Xr}from"./chunk-4ILUXVPW.mjs";var ge={es:{},en:{}},Rs=()=>Object.keys(ge),Ss=e=>ge[e]||ge.es;import Ye from"@nocios/crudify-sdk";var ro="crudify_translations_",xt=3600*1e3;function oo(e){let r=0;for(let o=0;o<e.length;o++){let t=e.charCodeAt(o);r=(r<<5)-r+t,r=r&r}return Math.abs(r).toString(36)}var mr=class e{constructor(){this.enableDebug=!1;this.initializationPromise=null;this.isInitialized=!1}static getInstance(){return e.instance||(e.instance=new e),e.instance}setDebug(r){this.enableDebug=r}async ensureCrudifyInitialized(r,o){if(!this.isInitialized)return this.initializationPromise?(this.enableDebug&&x.debug("[TranslationService] Waiting for crudify initialization..."),this.initializationPromise):(this.enableDebug&&x.debug("[TranslationService] Initializing crudify SDK..."),this.initializationPromise=(async()=>{try{let t=Ye.getTokenData();if(t&&t.endpoint){this.enableDebug&&x.debug("[TranslationService] Crudify already initialized"),this.isInitialized=!0;return}Ye.config(o);let i=await Ye.init(r,this.enableDebug?"debug":"none");if(i.success===!1)throw new Error(`Failed to initialize crudify: ${JSON.stringify(i.errors||"Unknown error")}`);this.isInitialized=!0,this.enableDebug&&x.debug("[TranslationService] Crudify SDK initialized successfully")}catch(t){throw x.error("[TranslationService] Failed to initialize crudify",t instanceof Error?t:{message:String(t)}),this.initializationPromise=null,t}})(),this.initializationPromise)}async fetchTranslations(r){let{apiKey:o,featureKeys:t,crudifyEnv:i="stg",urlTranslations:n}=r;this.enableDebug&&x.debug("[TranslationService] fetchTranslations called with:",{apiKeyHash:oo(o),crudifyEnv:i,featureKeys:t,hasUrlTranslations:!!n});let l=this.getFromCache(o),a=l?this.isCacheExpired(l):!0;if(l&&!a)return this.enableDebug&&x.debug("[TranslationService] Using cached translations"),this.mergeWithUrlTranslations(l.data.translations,n);try{await this.ensureCrudifyInitialized(o,i)}catch(u){return x.error("[TranslationService] Failed to initialize crudify",u instanceof Error?u:{message:String(u)}),l?(x.warn("[TranslationService] Using expired cache (init failed)"),this.mergeWithUrlTranslations(l.data.translations,n)):(x.warn("[TranslationService] Using critical bundle (init failed)"),this.getCriticalTranslationsOnly())}try{this.enableDebug&&x.debug("[TranslationService] Fetching from API via crudify SDK");let u=await this.fetchFromAPI(t);this.hasDataChanged(l,u)||!l?this.saveToCache(o,u):this.refreshCacheTimestamp(o);let d=this.mergeWithUrlTranslations(u.translations,n);return this.enableDebug&&x.debug("[TranslationService] Translations loaded:",{languages:Object.keys(d),keysCount:d[Object.keys(d)[0]]?Object.keys(d[Object.keys(d)[0]]).length:0}),d}catch(u){return x.error("[TranslationService] API fetch failed",u instanceof Error?u:{message:String(u)}),l?(x.warn("[TranslationService] Using expired cache as fallback"),this.mergeWithUrlTranslations(l.data.translations,n)):(x.warn("[TranslationService] Using critical bundle translations"),this.getCriticalTranslationsOnly())}}async fetchFromAPI(r){let o=await Ye.getTranslation(r);if(!o.success)throw new Error(`Crudify API error: ${o.errors?JSON.stringify(o.errors):"Unknown error"}`);if(!o.data)throw new Error("No translation data in response");return o.data}mergeWithUrlTranslations(r,o){if(!o||Object.keys(o).length===0)return r;let t={};return Object.keys(r).forEach(i=>{t[i]={...r[i],...o}}),t}hasDataChanged(r,o){if(!r||r.data.timestamp!==o.timestamp)return!0;let t=this.hashData(o.translations);return r.dataHash!==t}hashData(r){let o=JSON.stringify(r),t=0;for(let i=0;i<o.length;i++){let n=o.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return t.toString(36)}saveToCache(r,o){try{let t=this.getCacheKey(r),i={data:o,cachedAt:Date.now(),dataHash:this.hashData(o.translations)};localStorage.setItem(t,JSON.stringify(i)),this.enableDebug&&x.debug("[TranslationService] Saved to cache:",{cacheKey:t})}catch(t){x.error("[TranslationService] Failed to save cache",t instanceof Error?t:{message:String(t)})}}getFromCache(r){try{let o=this.getCacheKey(r),t=localStorage.getItem(o);return t?JSON.parse(t):null}catch(o){return x.error("[TranslationService] Failed to read cache",o instanceof Error?o:{message:String(o)}),null}}refreshCacheTimestamp(r){try{let o=this.getFromCache(r);if(o){o.cachedAt=Date.now();let t=this.getCacheKey(r);localStorage.setItem(t,JSON.stringify(o))}}catch(o){x.error("[TranslationService] Failed to refresh cache timestamp",o instanceof Error?o:{message:String(o)})}}isCacheExpired(r){return Date.now()-r.cachedAt>xt}hasValidCache(r){let o=this.getFromCache(r);return o?!this.isCacheExpired(o):!1}getCacheKey(r){return`${ro}${oo(r)}`}getCriticalTranslationsOnly(){return ge}invalidateCache(r){let o=this.getCacheKey(r);localStorage.removeItem(o),this.enableDebug&&x.debug("[TranslationService] Cache invalidated:",{cacheKey:o})}async prefetchTranslations(r){try{await this.fetchTranslations(r),this.enableDebug&&x.debug("[TranslationService] Prefetch completed")}catch(o){x.error("[TranslationService] Prefetch failed",o instanceof Error?o:{message:String(o)})}}clearAllCaches(){try{let o=Object.keys(localStorage).filter(t=>t.startsWith(ro));o.forEach(t=>localStorage.removeItem(t)),this.enableDebug&&x.debug(`[TranslationService] Cleared ${o.length} cache entries`)}catch(r){x.error("[TranslationService] Failed to clear caches",r instanceof Error?r:{message:String(r)})}}},Ze=mr.getInstance();import{createContext as wt,useContext as Ct,useEffect as io,useState as Le,useMemo as to,useCallback as vt}from"react";import{Fragment as Tt,jsx as er}from"react/jsx-runtime";var Qe=null,fr=!1,so=wt(null);function no(e,r,o){return{...e,...r,...o||{}}}function Pt(e,r,o,t,i){io(()=>{if(!t||!e||!r)return;let n=o||typeof window<"u"&&window.i18next||typeof window<"u"&&window.i18n;if(!n||!n.addResourceBundle){i&&x.debug("[TranslationsProvider] i18next not found, skipping auto-sync");return}i&&x.debug("[TranslationsProvider] Auto-syncing translations with i18next",{languages:Object.keys(e),currentLanguage:r}),Object.keys(e).forEach(l=>{e[l]&&Object.keys(e[l]).length>0&&(n.addResourceBundle(l,"translation",e[l],!0,!0),i&&x.debug(`[TranslationsProvider] Synced ${Object.keys(e[l]).length} keys for language: ${l}`))}),n.language!==r&&n.changeLanguage&&(n.changeLanguage(r),i&&x.debug(`[TranslationsProvider] Changed i18next language to: ${r}`))},[e,r,o,t,i])}var Us=({children:e,apiKey:r,crudifyEnv:o="prod",featureKeys:t,language:i="es",devTranslations:n,translationUrl:l,enableDebug:a=!1,skipAutoInit:u=!0,autoSyncI18n:h=!0,i18nInstance:d,loadingFallback:b,waitForInitialLoad:w=!0})=>{let c=to(()=>qr({publicApiKey:r,env:o,featureKeys:t,enableDebug:a}),[r,o,t,a]),s=c.publicApiKey||"",y=c.env||o||"prod",g=c.featureKeys||t,[m,f]=Le({}),[v,k]=Le(!0),[z,p]=Le(!0),[C,I]=Le(null),[A,Y]=Le(void 0),[le,Q]=Le(!1),ne=vt(async()=>{if(!s){a&&x.debug("[TranslationsProvider] No apiKey - skipping translation fetch"),k(!1),p(!1);return}if(le){a&&x.debug("[TranslationsProvider] Skipping reload - using fallback translations");return}if(Ze.hasValidCache(s)&&z&&(a&&x.debug("[TranslationsProvider] Valid cache found - not blocking initial render"),p(!1)),fr&&Qe){a&&x.debug("[TranslationsProvider] Fetch already in progress, waiting for existing promise");try{let R=await Qe;f(R),k(!1);return}catch{a&&x.warn("[TranslationsProvider] Global fetch failed, retrying")}}fr=!0,k(!0),I(null);let V;if(l)try{a&&x.debug(`[TranslationsProvider] Fetching translations from URL: ${l}`);let R=await fetch(l);if(!R.ok)throw new Error(`Failed to fetch translations: ${R.statusText}`);V=await R.json(),Y(V),a&&x.debug("[TranslationsProvider] URL translations loaded:",{keysCount:V?Object.keys(V).length:0})}catch(R){x.error("[TranslationsProvider] Failed to load URL translations",R instanceof Error?R:{message:String(R)}),V=void 0,Y(void 0)}let ee=(async()=>{try{Ze.setDebug(a);let R=await Ze.fetchTranslations({apiKey:s,crudifyEnv:y,featureKeys:g,urlTranslations:V}),S={};return Object.keys(R).forEach(W=>{let ie=ge[W]||{},re=R[W]||{};S[W]=no(ie,re,n)}),a&&x.debug("[TranslationsProvider] Loaded translations:",{languages:Object.keys(S),keysCount:Object.keys(S[i]||{}).length}),S}catch(R){x.error("[TranslationsProvider] Failed to load",R instanceof Error?R:{message:String(R)}),I(R instanceof Error?R.message:String(R)),Q(!0);let S={};return Object.keys(ge).forEach(W=>{let ie=ge[W],re=V||A||{};S[W]=no(ie,re,n)}),a&&x.debug("[TranslationsProvider] Using fallback translations (critical + URL)"),S}})();Qe=ee;try{let R=await ee;f(R)}finally{k(!1),p(!1),fr=!1,setTimeout(()=>{Qe=null},1e3)}},[s,y,g,l,n,a,i,le]);io(()=>{ne();let H=setInterval(ne,3600*1e3);return()=>clearInterval(H)},[ne]);let Oe=to(()=>(H,V)=>{let R=(m[i]||{})[H];if(!R){let S=Object.keys(m);for(let W of S)if(m[W][H]){R=m[W][H];break}}return R||(a&&x.warn(`[TranslationsProvider] Missing translation: "${H}"`),R=H),V&&typeof R=="string"&&Object.entries(V).forEach(([S,W])=>{let ie=new RegExp(`{{${S}}}`,"g");R=R.replace(ie,String(W))}),R},[m,i,a]);Pt(m,i,d,h,a);let Ie={t:Oe,language:i,availableLanguages:Object.keys(m),translations:m,isLoading:v,error:C,refreshTranslations:ne};return s?w&&z&&v?b||er("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:er("div",{children:"Loading translations..."})}):er(so.Provider,{value:Ie,children:e}):(a&&x.warn("[TranslationsProvider] No API key available. Skipping translations. Provide apiKey via props or ensure cookies are set by Lambda."),er(Tt,{children:e}))},Me=()=>{let e=Ct(so);if(!e)throw new Error("useTranslations must be used within TranslationsProvider");return e};var Rt=/^[a-zA-Z0-9\-_./\?=&%#]+$/,St=[/^https?:\/\//i,/^ftp:\/\//i,/^\/\//,/javascript:/i,/data:/i,/vbscript:/i,/about:/i,/\.\.\//,/\.\.\\/,/%2e%2e%2f/i,/%2e%2e%5c/i,/%2f%2f/i,/%5c%5c/i,/[\x00-\x1f\x7f-\x9f]/,/\\/],ao=(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return x.warn("Open redirect blocked (relative path)",{path:e}),r;if(!Rt.test(o))return x.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let n of St)if(n.test(t))return x.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let i=o.split("?")[0].split("/").filter(Boolean);if(i.length===0)return o;for(let n of i)if(n===".."||n.includes(":")||n.length>100)return x.warn("Open redirect blocked (suspicious path part)",{part:n}),r;return o},kt=[/^files\.nocios\.link$/,/^files\.crudia\.com$/,/^[a-z0-9][a-z0-9-]*\.nocios\.link$/,/^[a-z0-9][a-z0-9-]*\.crudia\.com$/],lo=(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(o.startsWith("/"))return ao(o,r);try{if(o.includes("..")||o.includes("//",8))return x.warn("Redirect blocked (dangerous path pattern)",{url:o}),r;let t=new URL(o);if(t.protocol!=="https:")return x.warn("Redirect blocked (non-HTTPS protocol)",{url:o}),r;let i=t.hostname.toLowerCase();return kt.some(l=>l.test(i))?o:(x.warn("Redirect blocked (untrusted domain)",{url:o,hostname:i}),r)}catch{return x.warn("Redirect blocked (invalid URL)",{url:o}),r}},Hs=(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let i=decodeURIComponent(t);return ao(i,r)}catch(o){return x.warn("Error parsing redirect parameter",o instanceof Error?{errorMessage:o.message}:{message:String(o)}),r}};import{Box as co,Typography as Et}from"@mui/material";import It from"@mui/icons-material/CheckCircle";import At from"@mui/icons-material/RadioButtonUnchecked";import{jsx as Ne,jsxs as Dt}from"react/jsx-runtime";var Lt=({message:e,valid:r})=>Dt(co,{sx:{display:"flex",alignItems:"center",gap:.5,py:.25},children:[r?Ne(It,{sx:{fontSize:16,color:"success.main"}}):Ne(At,{sx:{fontSize:16,color:"text.disabled"}}),Ne(Et,{variant:"caption",sx:{color:r?"success.main":"text.secondary",transition:"color 0.2s ease"},children:e})]}),Ft=({requirements:e,show:r=!0})=>!r||e.length===0?null:Ne(co,{sx:{mt:.5,mb:1,px:.5},children:e.map((o,t)=>Ne(Lt,{message:o.message,valid:o.valid},t))}),uo=Ft;var Bt=/[A-Z]/,_t=/[a-z]/,zt=/[0-9]/,Ot=/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/,Ut=/^[A-Za-z0-9]+$/;function po(e,r){return r.map(o=>{let t=!0;switch(o.type){case"minLength":t=e.length>=Number(o.value??0);break;case"alphanumeric":t=e.length>0&&Ut.test(e);break;case"uppercase":t=Bt.test(e);break;case"lowercase":t=_t.test(e);break;case"number":t=zt.test(e);break;case"special":t=Ot.test(e);break;default:t=!0}return{message:o.message,valid:t,enforce:!!o.enforce}})}function go(e){return e.filter(r=>r.enforce).every(r=>r.valid)}var mo=[{type:"minLength",value:8,message:"passwordRequirements.minLength",enforce:!0},{type:"uppercase",message:"passwordRequirements.uppercase",enforce:!0},{type:"lowercase",message:"passwordRequirements.lowercase",enforce:!0},{type:"number",message:"passwordRequirements.number",enforce:!0},{type:"special",message:"passwordRequirements.special",enforce:!0}];import{Box as Rn,Typography as Sn}from"@mui/material";import{createContext as Nt,useContext as Wt,useMemo as hr}from"react";import{useState as yr,useEffect as Mt}from"react";var fo=(e,r)=>{let[o,t]=yr({}),[i,n]=yr(!1),[l,a]=yr(null);return Mt(()=>{if(r&&Object.keys(r).length>0){t(r),n(!1),a(null);return}if(!e){t({}),n(!1),a(null);return}let u=!1;return n(!0),a(null),fetch(e).then(h=>{if(!h.ok)throw new Error(`Failed to load translations: ${h.status}`);return h.json()}).then(h=>{u||(t(h),n(!1))}).catch(h=>{u||(x.error("[I18nProvider] Failed to load translations from URL",h instanceof Error?h:{message:String(h),url:e}),a(h instanceof Error?h.message:String(h)),t({}),n(!1))}),()=>{u=!0}},[e,r]),{translations:o,loading:i,error:l}};import{jsx as yo}from"react/jsx-runtime";var ho=Nt(null),Ht=()=>{try{return Me()}catch{return null}},Vt=(e,r)=>{if(r.includes(".")){let o=r.split(".").reduce((t,i)=>t&&typeof t=="object"?t[i]:void 0,e);if(o!==void 0)return o}if(e&&e[r])return e[r]},bo=({children:e,translations:r,translationsUrl:o,language:t="en"})=>{let n=Ht()?.translations?.[t]||{},{translations:l,loading:a}=fo(o,r),u=hr(()=>({...n,...l,...r||{}}),[n,l,r]),h=hr(()=>(b,w)=>{let c=Vt(u,b);return c==null&&(c=b),w&&typeof c=="string"&&Object.entries(w).forEach(([s,y])=>{c=c.replace(new RegExp(`{{${s}}}`,"g"),y)}),typeof c=="string"?c:b},[u]),d=hr(()=>({t:h,language:t}),[h,t]);return a?yo("div",{children:"Loading translations..."}):yo(ho.Provider,{value:d,children:e})},oe=()=>{let e=Wt(ho);if(!e)throw new Error("useTranslation must be used within I18nProvider");return e};import{createContext as $t,useContext as jt,useReducer as Kt,useEffect as br,useCallback as qt}from"react";import{jsx as Xt}from"react/jsx-runtime";var xo={currentScreen:"login",searchParams:{},formData:{username:"",password:"",email:"",code:"",newPassword:"",confirmPassword:""},loading:!1,errors:{global:[]},emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1,config:{}};function Gt(e,r){switch(r.type){case"SET_SCREEN":let o={...e,currentScreen:r.payload.screen,searchParams:r.payload.params||e.searchParams,errors:{global:[]}},t=new URLSearchParams(o.searchParams),i=t.toString()?`?${t.toString()}`:window.location.pathname;try{window.history.replaceState({},"",i)}catch{}return o;case"SET_SEARCH_PARAMS":return{...e,searchParams:r.payload};case"CLEAR_SEARCH_PARAMS":return{...e,searchParams:{}};case"UPDATE_FORM_DATA":return{...e,formData:{...e.formData,...r.payload},errors:{...e.errors,...Object.keys(r.payload).reduce((n,l)=>({...n,[l]:void 0}),{})}};case"SET_LOADING":return{...e,loading:r.payload};case"SET_ERRORS":return{...e,errors:{...e.errors,...r.payload}};case"CLEAR_ERRORS":return{...e,errors:{global:[]}};case"SET_EMAIL_SENT":return{...e,emailSent:r.payload};case"SET_CODE_ALREADY_EXISTS":return{...e,codeAlreadyExists:r.payload};case"SET_CODE_VALIDATED":return{...e,codeValidated:r.payload};case"SET_FROM_CODE_VERIFICATION":return{...e,fromCodeVerification:r.payload};case"RESET_FORM":return{...e,formData:xo.formData,errors:{global:[]},loading:!1,emailSent:!1,codeAlreadyExists:!1,codeValidated:!1,fromCodeVerification:!1};case"INIT_CONFIG":return{...e,config:r.payload};default:return e}}var wo=$t(void 0),Co=({children:e,initialScreen:r="login",config:o,autoReadFromCookies:t=!0})=>{let[i,n]=Kt(Gt,{...xo,currentScreen:r});br(()=>{n({type:"INIT_CONFIG",payload:(()=>{let s={};if(t)try{let y=Kr();y.configSource!=="none"&&y.logo&&(s.logo=y.logo)}catch(y){x.error("Error reading configuration",y instanceof Error?y:{message:String(y)})}return{publicApiKey:o?.publicApiKey,env:o?.env,appName:o?.appName,logo:o?.logo||s.logo,loginActions:o?.loginActions}})()})},[o,t]),br(()=>{let c=new URLSearchParams(window.location.search),s={};c.forEach((y,g)=>{s[g]=y}),Object.keys(s).length>0&&n({type:"SET_SEARCH_PARAMS",payload:s}),r==="checkCode"&&s.email&&n({type:"UPDATE_FORM_DATA",payload:{email:s.email,code:s.code||""}}),r==="resetPassword"&&s.link&&n({type:"SET_SEARCH_PARAMS",payload:s})},[r]),br(()=>{let c=Gr.subscribe(s=>{(s.type==="LOGOUT"||s.type==="SESSION_EXPIRED")&&(x.debug("LoginStateProvider: Clearing state due to auth event",{type:s.type}),n({type:"CLEAR_SEARCH_PARAMS"}),n({type:"RESET_FORM"}))});return()=>c()},[]);let l=(c,s)=>{n({type:"SET_SCREEN",payload:{screen:c,params:s}})},a=c=>{n({type:"UPDATE_FORM_DATA",payload:c})},u=(c,s)=>{n({type:"SET_ERRORS",payload:{[c]:s}})},h=()=>{n({type:"CLEAR_ERRORS"})},d=c=>{n({type:"SET_LOADING",payload:c})},b=qt(()=>{n({type:"CLEAR_SEARCH_PARAMS"})},[]),w={state:i,dispatch:n,setScreen:l,updateFormData:a,setFieldError:u,clearErrors:h,setLoading:d,clearSearchParams:b};return Xt(wo.Provider,{value:w,children:e})},rr=()=>{let e=jt(wo);if(e===void 0)throw new Error("useLoginState must be used within a LoginStateProvider");return e};import{useEffect as Jt,useRef as Yt}from"react";import{Typography as xr,TextField as vo,Button as Zt,Box as We,CircularProgress as Qt,Alert as en,Link as Po}from"@mui/material";import{Fragment as on,jsx as te,jsxs as He}from"react/jsx-runtime";var rn=({onScreenChange:e,onExternalNavigate:r,onLoginSuccess:o,onError:t,redirectUrl:i="/"})=>{let{state:n,updateFormData:l,setFieldError:a,clearErrors:u,setLoading:h}=rr(),{login:d}=be(),b=oe(),{t:w}=b,c="i18n"in b?b.i18n:void 0,s=Yt(null),y=Xr(w,{currentLanguage:c?.language,enableDebug:!1}),g=()=>{if(n.searchParams.redirect)try{let p=decodeURIComponent(n.searchParams.redirect);return lo(p,i||"/")}catch{}return i||"/"};Jt(()=>{let p=setTimeout(()=>{s.current&&s.current.focus()},100);return()=>clearTimeout(p)},[]);let m=p=>y.translateError({code:p.code,message:p.message,field:p.field}),f=async()=>{if(!n.loading){if(!n.formData.username.trim()){a("username",w("login.usernameRequired"));return}if(!n.formData.password.trim()){a("password",w("login.passwordRequired"));return}u(),h(!0);try{let p=await d(n.formData.username,n.formData.password);if(h(!1),p.success){let C=g();o&&o(p.data,C)}else{let C=p.rawResponse||p;v(C)}}catch(p){h(!1);let I=J(p).map(m);a("global",I),t&&t(I.join(", "))}}},v=p=>{let C=J(p),I=[];C.forEach(A=>{A.field?a(A.field,m(A)):I.push(m(A))}),I.length>0&&a("global",I)};return He(on,{children:[He(We,{component:"form",noValidate:!0,onSubmit:p=>{p.preventDefault(),f()},onKeyDown:p=>{p.key==="Enter"&&!n.loading&&(p.preventDefault(),f())},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[He(We,{sx:{mb:1},children:[te(xr,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:w("login.usernameOrEmailLabel")}),te(vo,{fullWidth:!0,id:"email",name:"email",type:"email",value:n.formData.username,disabled:n.loading,onChange:p=>l({username:p.target.value}),error:!!n.errors.username,helperText:n.errors.username,autoComplete:"email",placeholder:w("login.usernameOrEmailPlaceholder"),inputRef:s,required:!0})]}),He(We,{sx:{mb:1},children:[te(xr,{variant:"body2",component:"label",htmlFor:"password",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:w("login.passwordLabel")}),te(vo,{fullWidth:!0,id:"password",name:"password",type:"password",value:n.formData.password,disabled:n.loading,onChange: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(We,{sx:{display:"flex",justifyContent:"flex-end",alignItems:"center"},children:te(Po,{sx:{cursor:"pointer"},onClick:()=>{e?.("forgotPassword",n.searchParams)},variant:"body2",color:"secondary",children:w("login.forgotPasswordLink")})}),te(Zt,{disabled:n.loading,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:1,mb:2},children:n.loading?te(Qt,{size:20}):w("login.loginButton")})]}),te(We,{children:n.errors.global&&n.errors.global.length>0&&n.errors.global.map((p,C)=>te(en,{variant:"filled",sx:{mt:2},severity:"error",children:te("div",{children:p})},C))}),n.config.loginActions?.includes("createUser")&&He(xr,{variant:"body2",align:"center",sx:{color:"text.secondary",mt:3},children:[w("login.noAccountPrompt")," ",te(Po,{sx:{cursor:"pointer"},onClick:()=>{let C=`/public/users/create${Object.keys(n.searchParams).length>0?`?${new URLSearchParams(n.searchParams).toString()}`:""}`;r?.(C)},fontWeight:"medium",color:"secondary",children:w("login.signUpLink")})]})]})},To=rn;import{useState as Fe,useEffect as tn,useRef as nn}from"react";import{Typography as De,TextField as sn,Button as Ro,Box as xe,CircularProgress as an,Alert as ln,Link as wr}from"@mui/material";import{Fragment as So,jsx as N,jsxs as Se}from"react/jsx-runtime";var cn=({onScreenChange:e,onError:r})=>{let{crudify:o}=he(),[t,i]=Fe(""),[n,l]=Fe(!1),[a,u]=Fe([]),[h,d]=Fe(null),[b,w]=Fe(!1),[c,s]=Fe(!1),y=nn(null),{t:g}=oe();tn(()=>{y.current&&!b&&!c&&y.current.focus()},[b,c]);let m=C=>{let I=[`errors.auth.${C.code}`,`errors.data.${C.code}`,`errors.system.${C.code}`,`errors.${C.code}`,`forgotPassword.${C.code.toLowerCase()}`];for(let A of I){let Y=g(A);if(Y!==A)return Y}return C.message||g("base.errors.errorUnknown")},f=C=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(C),v=async()=>{if(!(n||!o)){if(u([]),d(null),!t){d(g("forgotPassword.emailRequired"));return}if(!f(t)){d(g("forgotPassword.invalidEmail"));return}l(!0);try{let C=[{operation:"requestPasswordReset",data:{email:t}}],I=await o.transaction(C);if(I.success)I.data&&I.data.existingCodeValid?s(!0):w(!0);else{let Y=J(I).map(m);u(Y)}}catch(C){let A=J(C).map(m);u(A),r&&r(A.join(", "))}finally{l(!1)}}},k=()=>{e?.("login")},z=()=>{if(b||c){e?.("checkCode",{email:t});return}if(!t){d(g("forgotPassword.emailRequired"));return}if(!f(t)){d(g("forgotPassword.invalidEmail"));return}e?.("checkCode",{email:t})};return b||c?N(So,{children:Se(xe,{sx:{width:"100%",display:"flex",flexDirection:"column",gap:2,textAlign:"center"},children:[Se(xe,{sx:{mb:2},children:[N(De,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:g(c?"forgotPassword.codeAlreadyExistsMessage":"forgotPassword.emailSentMessage")}),N(De,{variant:"body2",sx:{color:c?"success.main":"grey.600"},children:g("forgotPassword.checkEmailInstructions")})]}),N(Ro,{type:"button",onClick:z,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:g("forgotPassword.enterCodeLink")}),N(xe,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:N(wr,{sx:{cursor:"pointer"},onClick:k,variant:"body2",color:"secondary",children:g("base.btn.back")})})]})}):Se(So,{children:[Se(xe,{component:"form",noValidate:!0,onSubmit:C=>{C.preventDefault(),v()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Se(xe,{sx:{mb:2},children:[N(De,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:g("forgotPassword.title")}),N(De,{variant:"body2",sx:{color:"grey.600"},children:g("forgotPassword.instructions")})]}),Se(xe,{sx:{mb:1},children:[N(De,{variant:"body2",component:"label",htmlFor:"email",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:g("forgotPassword.emailLabel")}),N(sn,{fullWidth:!0,id:"email",name:"email",type:"email",value:t,disabled:n,onChange:C=>i(C.target.value),error:!!h,helperText:h,autoComplete:"email",placeholder:g("forgotPassword.emailPlaceholder"),required:!0,autoFocus:!0,inputRef:y})]}),N(Ro,{disabled:n,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:n?N(an,{size:20}):g("forgotPassword.sendCodeButton")}),Se(xe,{sx:{display:"flex",justifyContent:"center",alignItems:"center",gap:2},children:[N(wr,{sx:{cursor:"pointer"},onClick:k,variant:"body2",color:"secondary",children:g("base.btn.back")}),N(De,{variant:"body2",sx:{color:"grey.400"},children:"\u2022"}),N(wr,{sx:{cursor:"pointer"},onClick:z,variant:"body2",color:"secondary",children:g("login.alreadyHaveCodeLink")})]})]}),N(xe,{children:a.length>0&&a.map((C,I)=>N(ln,{variant:"filled",sx:{mt:2},severity:"error",children:C},I))})]})},ko=cn;import{useState as $,useEffect as Eo,useMemo as Cr}from"react";import{Typography as or,TextField as Io,Button as dn,Box as we,CircularProgress as Ao,Alert as Lo,Link as un,IconButton as Fo,InputAdornment as Do}from"@mui/material";import Bo from"@mui/icons-material/Visibility";import _o from"@mui/icons-material/VisibilityOff";import{Fragment as gn,jsx as F,jsxs as Ve}from"react/jsx-runtime";var pn=({onScreenChange:e,onError:r,searchParams:o,onResetSuccess:t,passwordRules:i})=>{let{crudify:n}=he(),[l,a]=$(""),[u,h]=$(""),[d,b]=$(!1),[w,c]=$([]),[s,y]=$(null),[g,m]=$(null),[f,v]=$(""),[k,z]=$(""),[p,C]=$(!1),[I,A]=$(!0),[Y,le]=$(!1),[Q,ne]=$(null),[Oe,Ie]=$(!1),[H,V]=$(!1),[ee,R]=$(!1),{t:S}=oe(),W=Cr(()=>(i||mo).map(D=>({...D,message:S(D.message)})),[i,S]),ie=Cr(()=>po(l,W),[l,W]),re=Cr(()=>go(ie),[ie]),Ue=l===u,Re=E=>{let D=[`errors.auth.${E.code}`,`errors.data.${E.code}`,`errors.system.${E.code}`,`errors.${E.code}`,`resetPassword.${E.code.toLowerCase()}`];for(let M of D){let q=S(M);if(q!==M)return q}return E.message||S("base.errors.errorUnknown")},Ae=E=>o?o instanceof URLSearchParams?o.get(E):o[E]||null:null;Eo(()=>{if(o){if(o){let E=Ae("fromCodeVerification"),D=Ae("email"),M=Ae("code");if(E==="true"&&D&&M){v(D),z(M),C(!0),le(!0),A(!1);return}let q=Ae("link");if(q)try{let G=decodeURIComponent(q),[X,ye]=G.split("/");if(X&&ye&&X.length===6){z(X),v(ye),C(!1),ne({email:ye,code:X});return}}catch{}if(D&&M){v(D),z(M),C(!1),ne({email:D,code:M});return}}c([S("resetPassword.invalidCode")]),A(!1),setTimeout(()=>e?.("forgotPassword"),3e3)}},[o,n,S,e]),Eo(()=>{n&&Q&&!Oe&&(Ie(!0),(async(D,M)=>{try{let q=[{operation:"validatePasswordResetCode",data:{email:D,codePassword:M}}],G=await n.transaction(q);if(G.data&&Array.isArray(G.data)){let X=G.data[0];if(X&&X.response&&X.response.status==="OK"){le(!0);return}}if(G.success)le(!0);else{let ye=J(G).map(Re);c(ye),setTimeout(()=>e?.("forgotPassword"),3e3)}}catch(q){let X=J(q).map(Re);c(X),setTimeout(()=>e?.("forgotPassword"),3e3)}finally{A(!1),ne(null),Ie(!1)}})(Q.email,Q.code))},[n,Q,S,e]);let Xe=async()=>{if(d||!n)return;c([]),y(null),m(null);let E=!1;if(l?re||(y(S("resetPassword.passwordRequirementsNotMet")),E=!0):(y(S("resetPassword.newPasswordRequired")),E=!0),u?Ue||(m(S("resetPassword.passwordsDoNotMatch")),E=!0):(m(S("resetPassword.confirmPasswordRequired")),E=!0),!E){b(!0);try{let D=[{operation:"validateAndResetPassword",data:{email:f,codePassword:k,newPassword:l}}],M=await n.transaction(D);if(M.success)c([]),setTimeout(()=>{t?.()},1e3);else{let G=J(M).map(Re);c(G)}}catch(D){let q=J(D).map(Re);c(q),r&&r(q.join(", "))}b(!1)}},Or=()=>{p?e?.("checkCode",{email:f}):e?.("forgotPassword")};return I?F(we,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"300px"},children:F(Ao,{})}):Y?Ve(gn,{children:[Ve(we,{component:"form",noValidate:!0,sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[Ve(we,{sx:{mb:2},children:[F(or,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:S("resetPassword.title")}),F(or,{variant:"body2",sx:{color:"grey.600"},children:S("resetPassword.instructions")})]}),Ve(we,{sx:{mb:1},children:[F(or,{variant:"body2",component:"label",htmlFor:"newPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:S("resetPassword.newPasswordLabel")}),F(Io,{fullWidth:!0,id:"newPassword",name:"newPassword",type:H?"text":"password",value:l,disabled:d,onChange:E=>a(E.target.value),error:!!s,helperText:s,autoComplete:"new-password",placeholder:S("resetPassword.newPasswordPlaceholder"),required:!0,InputProps:{endAdornment:F(Do,{position:"end",children:F(Fo,{"aria-label":S(H?"base.btn.hidePassword":"base.btn.showPassword"),onClick:()=>V(!H),edge:"end",size:"small",disabled:d,children:H?F(_o,{}):F(Bo,{})})})}}),F(uo,{requirements:ie,show:l.length>0})]}),Ve(we,{sx:{mb:1},children:[F(or,{variant:"body2",component:"label",htmlFor:"confirmPassword",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:S("resetPassword.confirmPasswordLabel")}),F(Io,{fullWidth:!0,id:"confirmPassword",name:"confirmPassword",type:ee?"text":"password",value:u,disabled:d,onChange:E=>h(E.target.value),error:!!g,helperText:g,autoComplete:"new-password",placeholder:S("resetPassword.confirmPasswordPlaceholder"),required:!0,InputProps:{endAdornment:F(Do,{position:"end",children:F(Fo,{"aria-label":S(ee?"base.btn.hidePassword":"base.btn.showPassword"),onClick:()=>R(!ee),edge:"end",size:"small",disabled:d,children:ee?F(_o,{}):F(Bo,{})})})}})]}),F(dn,{disabled:d||!re||!Ue||!l||!u,type:"button",onClick:Xe,fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:d?F(Ao,{size:20}):S("resetPassword.resetPasswordButton")}),F(we,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:F(un,{sx:{cursor:"pointer"},onClick:Or,variant:"body2",color:"secondary",children:S("base.btn.back")})})]}),F(we,{children:w.length>0&&w.map((E,D)=>F(Lo,{variant:"filled",sx:{mt:2},severity:"error",children:E},D))})]}):F(we,{children:w.length>0&&w.map((E,D)=>F(Lo,{variant:"filled",sx:{mt:2},severity:"error",children:E},D))})},zo=pn;import{useState as $e,useEffect as Oo,useRef as mn}from"react";import{Typography as vr,TextField as fn,Button as yn,Box as je,CircularProgress as hn,Alert as bn,Link as xn}from"@mui/material";import{Fragment as Cn,jsx as de,jsxs as tr}from"react/jsx-runtime";var wn=({onScreenChange:e,onError:r,searchParams:o})=>{let{crudify:t}=he(),[i,n]=$e(""),[l,a]=$e(!1),[u,h]=$e([]),[d,b]=$e(null),[w,c]=$e(""),s=mn(null),{t:y}=oe(),g=p=>o?o instanceof URLSearchParams?o.get(p):o[p]||null:null,m=p=>{let C=[`errors.auth.${p.code}`,`errors.data.${p.code}`,`errors.system.${p.code}`,`errors.${p.code}`,`checkCode.${p.code.toLowerCase()}`];for(let I of C){let A=y(I);if(A!==I)return A}return p.message||y("base.errors.errorUnknown")};Oo(()=>{let p=g("email");p?c(p):e?.("forgotPassword")},[o,e]),Oo(()=>{s.current&&s.current.focus()},[]);let f=async()=>{if(!(l||!t)){if(h([]),b(null),!i){b(y("checkCode.codeRequired"));return}if(i.length!==6){b(y("checkCode.codeRequired"));return}a(!0);try{let p=[{operation:"validatePasswordResetCode",data:{email:w,codePassword:i}}],C=await t.transaction(p);if(C.success)e?.("resetPassword",{email:w,code:i,fromCodeVerification:"true"});else{let A=J(C).map(m);h(A),a(!1)}}catch(p){let I=J(p).map(m);h(I),a(!1),r&&r(I.join(", "))}}},v=()=>{e?.("forgotPassword")},k=p=>{let C=p.target.value.replace(/\D/g,"").slice(0,6);n(C)};return tr(Cn,{children:[tr(je,{component:"form",noValidate:!0,onSubmit:p=>{p.preventDefault(),f()},sx:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:[tr(je,{sx:{mb:2},children:[de(vr,{variant:"h5",component:"h1",sx:{mb:1,fontWeight:600},children:y("checkCode.title")}),de(vr,{variant:"body2",sx:{color:"grey.600"},children:y("checkCode.instructions")})]}),tr(je,{sx:{mb:1},children:[de(vr,{variant:"body2",component:"label",htmlFor:"code",sx:{display:"block",fontWeight:500,color:"grey.700",mb:.5},children:y("checkCode.codeLabel")}),de(fn,{fullWidth:!0,id:"code",name:"code",type:"text",value:i,disabled:l,onChange:k,error:!!d,helperText:d,placeholder:y("checkCode.codePlaceholder"),inputProps:{maxLength:6,style:{textAlign:"center",fontSize:"1.5rem",letterSpacing:"0.4rem"}},required:!0,autoFocus:!0,inputRef:s})]}),de(yn,{disabled:l||i.length!==6,type:"submit",fullWidth:!0,variant:"contained",color:"primary",sx:{mt:2,mb:2},children:l?de(hn,{size:20}):y("checkCode.verifyButton")}),de(je,{sx:{display:"flex",justifyContent:"center",alignItems:"center"},children:de(xn,{sx:{cursor:"pointer"},onClick:v,variant:"body2",color:"secondary",children:y("base.btn.back")})})]}),de(je,{children:u.length>0&&u.map((p,C)=>de(bn,{sx:{mt:2},severity:"error",children:p},C))})]})},Uo=wn;import{Box as vn,CircularProgress as Pn,Alert as Mo,Typography as Pr}from"@mui/material";import{Fragment as Tn,jsx as Be,jsxs as No}from"react/jsx-runtime";var Wo=({children:e,fallback:r})=>{let{isLoading:o,error:t,isInitialized:i}=he(),{t:n}=oe();return o?r||No(vn,{sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"200px",gap:2},children:[Be(Pn,{}),Be(Pr,{variant:"body2",color:"text.secondary",children:n("login.initializing")!=="login.initializing"?n("login.initializing"):"Initializing..."})]}):t?Be(Mo,{severity:"error",sx:{mt:2},children:No(Pr,{variant:"body2",children:[n("login.initializationError")!=="login.initializationError"?n("login.initializationError"):"Initialization error",":"," ",t]})}):i?Be(Tn,{children:e}):Be(Mo,{severity:"warning",sx:{mt:2},children:Be(Pr,{variant:"body2",children:n("login.notInitialized")!=="login.notInitialized"?n("login.notInitialized"):"System not initialized"})})};import{jsx as se,jsxs as In}from"react/jsx-runtime";var kn=({onScreenChange:e,onExternalNavigate:r,onLoginSuccess:o,onError:t,redirectUrl:i="/",passwordRules:n})=>{let{t:l}=oe(),{state:a,setScreen:u}=rr(),{config:h}=be(),{showNotification:d}=Jr(),b=(c,s)=>{let y=s;c==="login"?y={}:c==="forgotPassword"&&!s&&(y={}),u(c,y),e?.(c,y)},w=()=>{let c={onScreenChange:b,onExternalNavigate:r,onError:t,redirectUrl:i};switch(a.currentScreen){case"forgotPassword":return se(ko,{...c});case"checkCode":return se(Uo,{...c,searchParams:a.searchParams});case"resetPassword":return se(zo,{...c,searchParams:a.searchParams,passwordRules:n,onResetSuccess:()=>{let s=l("resetPassword.successMessage");d(s,"success"),b("login")}});default:return se(To,{...c,onLoginSuccess:o})}};return In(Wo,{children:[se(Rn,{sx:{display:"flex",justifyContent:"center",mb:3},children:se("img",{src:h.logo||"https://logos.crudia.com/nocios-default.png",alt:l("login.logoAlt"),style:{width:"100%",maxWidth:"150px",height:"auto"},onError:c=>{let s=c.target;s.src="https://logos.crudia.com/nocios-default.png"}})}),!h.logo&&h.appName&&se(Sn,{variant:"h6",component:"h1",sx:{textAlign:"center",mb:2},children:h.appName}),w()]})},En=({translations:e,translationsUrl:r,language:o="en",initialScreen:t="login",autoReadFromCookies:i=!0,...n})=>{let{config:l}=be();return se(bo,{translations:e,translationsUrl:r,language:o,children:se(Yr,{config:l,children:se(Co,{config:l,initialScreen:t,autoReadFromCookies:i,children:se(kn,{...n})})})})},ul=En;import{Box as Z,Card as Ho,CardContent as Vo,Typography as ae,Chip as nr,Avatar as An,Divider as Ln,CircularProgress as Fn,Alert as $o,List as Dn,ListItem as Tr,ListItemText as Rr,ListItemIcon as Bn,Collapse as _n,IconButton as Sr}from"@mui/material";import{Person as zn,Email as On,Badge as Un,Security as Mn,Schedule as Nn,AccountCircle as Wn,ExpandMore as Hn,ExpandLess as Vn,Info as $n}from"@mui/icons-material";import{useState as jn}from"react";import{Fragment as Gn,jsx as T,jsxs as B}from"react/jsx-runtime";var Kn=({showExtendedData:e=!0,showProfileCard:r=!0,autoRefresh:o=!0})=>{let{userProfile:t,loading:i,error:n,extendedData:l,refreshProfile:a}=Zr({autoFetch:o,retryOnError:!0,maxRetries:3}),[u,h]=jn(!1);if(i)return B(Z,{display:"flex",justifyContent:"center",alignItems:"center",p:3,children:[T(Fn,{}),T(ae,{variant:"body2",sx:{ml:2},children:"Cargando perfil de usuario..."})]});if(n)return B($o,{severity:"error",action:T(Sr,{color:"inherit",size:"small",onClick:a,children:T(ae,{variant:"caption",children:"Reintentar"})}),children:["Error al cargar el perfil: ",n]});if(!t)return T($o,{severity:"warning",children:"No se encontr\xF3 informaci\xF3n del usuario"});let d=l?.displayData||{},b=l?.totalFields||0,w=f=>{if(!f)return"No disponible";try{return new Date(f).toLocaleString("es-ES",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return f}},c=(f,v)=>v==null?"No disponible":typeof v=="boolean"?v?"S\xED":"No":Array.isArray(v)?v.length>0?v.join(", "):"Ninguno":typeof v=="object"?JSON.stringify(v,null,2):String(v),s=[{key:"id",label:"ID",icon:T(Un,{})},{key:"email",label:"Email",icon:T(On,{})},{key:"username",label:"Usuario",icon:T(zn,{})},{key:"fullName",label:"Nombre completo",icon:T(Wn,{})},{key:"role",label:"Rol",icon:T(Mn,{})}],y=[{key:"firstName",label:"Nombre"},{key:"lastName",label:"Apellido"},{key:"isActive",label:"Activo"},{key:"lastLogin",label:"\xDAltimo login"},{key:"createdAt",label:"Creado"},{key:"updatedAt",label:"Actualizado"}],g=[...s.map(f=>f.key),...y.map(f=>f.key),"permissions"],m=Object.keys(d).filter(f=>!g.includes(f)).map(f=>({key:f,label:f}));return B(Z,{children:[r&&T(Ho,{sx:{mb:2},children:B(Vo,{children:[B(Z,{display:"flex",alignItems:"center",mb:2,children:[T(An,{src:d.avatar,sx:{width:56,height:56,mr:2},children:d.fullName?.[0]||d.username?.[0]||d.email?.[0]}),B(Z,{children:[T(ae,{variant:"h6",children:d.fullName||d.username||d.email}),T(ae,{variant:"body2",color:"text.secondary",children:d.role||"Usuario"}),d.isActive!==void 0&&T(nr,{label:d.isActive?"Activo":"Inactivo",color:d.isActive?"success":"error",size:"small",sx:{mt:.5}})]})]}),T(Z,{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:2,children:s.map(({key:f,label:v,icon:k})=>d[f]?B(Z,{display:"flex",alignItems:"center",children:[T(Z,{sx:{mr:1,color:"text.secondary"},children:k}),B(Z,{children:[T(ae,{variant:"caption",color:"text.secondary",children:v}),T(ae,{variant:"body2",children:c(f,d[f])})]})]},f):null)}),d.permissions&&Array.isArray(d.permissions)&&d.permissions.length>0&&B(Z,{mt:2,children:[T(ae,{variant:"caption",color:"text.secondary",display:"block",children:"Permisos"}),B(Z,{display:"flex",flexWrap:"wrap",gap:.5,mt:.5,children:[d.permissions.slice(0,5).map((f,v)=>T(nr,{label:f,size:"small",variant:"outlined"},v)),d.permissions.length>5&&T(nr,{label:`+${d.permissions.length-5} m\xE1s`,size:"small"})]})]})]})}),e&&T(Ho,{children:B(Vo,{children:[B(Z,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2,children:[B(ae,{variant:"h6",display:"flex",alignItems:"center",children:[T($n,{sx:{mr:1}}),"Informaci\xF3n Detallada"]}),T(nr,{label:`${b} campos totales`,size:"small"})]}),B(Dn,{dense:!0,children:[y.map(({key:f,label:v})=>d[f]!==void 0&&B(Tr,{divider:!0,children:[T(Bn,{children:T(Nn,{fontSize:"small"})}),T(Rr,{primary:v,secondary:f.includes("At")||f.includes("Login")?w(d[f]):c(f,d[f])})]},f)),m.length>0&&B(Gn,{children:[T(Ln,{sx:{my:1}}),T(Tr,{children:T(Rr,{primary:B(Z,{display:"flex",justifyContent:"space-between",alignItems:"center",children:[B(ae,{variant:"subtitle2",children:["Campos Personalizados (",m.length,")"]}),T(Sr,{size:"small",onClick:()=>h(!u),children:u?T(Vn,{}):T(Hn,{})})]})})}),T(_n,{in:u,children:m.map(({key:f,label:v})=>T(Tr,{sx:{pl:4},children:T(Rr,{primary:v,secondary:c(f,d[f])})},f))})]})]}),B(Z,{mt:2,display:"flex",justifyContent:"space-between",alignItems:"center",children:[B(ae,{variant:"caption",color:"text.secondary",children:["\xDAltima actualizaci\xF3n: ",w(d.updatedAt)]}),T(Sr,{size:"small",onClick:a,disabled:i,children:T(ae,{variant:"caption",children:"Actualizar"})})]})]})})]})},qn=Kn;var jo=["create","read","update","delete"],Ko=["create","read","update","delete"];import{useRef as hi}from"react";import{useTranslation as bi}from"react-i18next";import{Box as ar,Typography as Qo,Button as xi,Stack as wi,Alert as et,Divider as Ci}from"@mui/material";import{Add as vi}from"@mui/icons-material";import{forwardRef as ni}from"react";import{useTranslation as ii}from"react-i18next";import{Box as ke,FormControl as si,InputLabel as ai,Select as li,MenuItem as ci,IconButton as di,Typography as _e,FormHelperText as ui,Stack as sr,Paper as Zo,Divider as pi,Button as Ar}from"@mui/material";import{Delete as gi,SelectAll as mi,ClearAll as fi}from"@mui/icons-material";import{useState as qo,useEffect as Go,useRef as Xo}from"react";import{useTranslation as Xn}from"react-i18next";import{Box as ir,Typography as Ke,Button as Jo,Stack as kr,FormControlLabel as Jn,FormHelperText as Yo,Switch as Yn,ToggleButton as Er,ToggleButtonGroup as Zn}from"@mui/material";import{CheckCircle as Qn,Cancel as ei,SelectAll as ri,ClearAll as oi}from"@mui/icons-material";import{jsx as O,jsxs as Ce}from"react/jsx-runtime";var ti=({value:e,onChange:r,availableFields:o,error:t,disabled:i=!1})=>{let{t:n}=Xn(),[l,a]=qo("custom"),[u,h]=qo(!1),d=Xo(null);Go(()=>{u&&d.current?.scrollIntoView({behavior:"smooth",block:"start"})},[u]);let b=Xo(!1);Go(()=>{let g=e||{allow:[],owner_allow:[],deny:[]},m=new Set(o),f=(g.allow||[]).filter(p=>m.has(p)),v=(g.owner_allow||[]).filter(p=>m.has(p)),k=(g.deny||[]).filter(p=>m.has(p));o.forEach(p=>{!f.includes(p)&&!v.includes(p)&&!k.includes(p)&&k.push(p)});let z={allow:f,owner_allow:v,deny:k};JSON.stringify(z)!==JSON.stringify(g)&&r(z),f.length===o.length?a("all"):k.length===o.length?a("none"):a("custom")},[o,e]);let w=()=>{b.current=!0,r({allow:[...o],owner_allow:[],deny:[]}),a("all"),setTimeout(()=>{b.current=!1},0)},c=()=>{b.current=!0,r({allow:[],owner_allow:[],deny:[...o]}),a("none"),setTimeout(()=>{b.current=!1},0)},s=g=>e?.allow?.includes(g)?"allow":e?.owner_allow?.includes(g)?"owner_allow":"deny",y=(g,m)=>{b.current=!0;let f=new Set(e?.allow||[]),v=new Set(e?.owner_allow||[]),k=new Set(e?.deny||[]);f.delete(g),v.delete(g),k.delete(g),m==="allow"&&f.add(g),m==="owner_allow"&&v.add(g),m==="deny"&&k.add(g),r({allow:Array.from(f),owner_allow:Array.from(v),deny:Array.from(k)}),a("custom"),setTimeout(()=>{b.current=!1},0)};return o.length===0?Ce(ir,{children:[O(Ke,{variant:"body2",color:"text.secondary",sx:{mb:1},children:n("publicPolicies.fields.conditions.label")}),O(Ke,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:n("publicPolicies.fields.conditions.noFieldsAvailable")}),t&&O(Yo,{error:!0,sx:{mt:1},children:t})]}):Ce(ir,{children:[O(Ke,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("publicPolicies.fields.conditions.label")}),Ce(kr,{direction:"row",spacing:1,alignItems:"center",sx:{mb:u?3:1},children:[O(Jo,{variant:l==="all"?"contained":"outlined",startIcon:O(ri,{}),onClick:w,disabled:i,size:"small",sx:{minWidth:120,...l==="all"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:n("publicPolicies.fields.conditions.allFields")}),O(Jo,{variant:l==="none"?"contained":"outlined",startIcon:O(oi,{}),onClick:c,disabled:i,size:"small",sx:{minWidth:120,...l==="none"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:n("publicPolicies.fields.conditions.noFields")}),O(ir,{sx:{display:"flex",alignItems:"center",px:1.5,py:.35,borderRadius:"999px",backgroundColor:"#f3f4f6",border:"1px solid #d1d9e0"},children:O(Jn,{control:O(Yn,{size:"small",checked:u,onChange:()=>h(g=>!g),disabled:i,color:"primary",sx:{transform:"scale(1.15)",transformOrigin:"center",m:0}}),label:n("publicPolicies.fields.conditions.customEdit"),labelPlacement:"end",sx:{ml:0,".MuiFormControlLabel-label":{fontSize:"0.75rem"}}})})]}),u&&Ce(ir,{ref:d,sx:{p:2,border:"1px solid #d1d9e0",borderRadius:1,backgroundColor:"#f6f8fa"},children:[O(Ke,{variant:"body2",color:"text.secondary",sx:{mb:2},children:n("publicPolicies.fields.conditions.help")}),O(kr,{spacing:1,children:o.map(g=>{let m=s(g);return Ce(kr,{direction:"row",spacing:1,alignItems:"center",children:[O(Ke,{variant:"body2",sx:{minWidth:100,fontFamily:"monospace"},children:g}),Ce(Zn,{value:m,exclusive:!0,size:"small",children:[Ce(Er,{value:"allow",onClick:()=>y(g,"allow"),disabled:i,sx:{px:2,color:m==="allow"?"#ffffff":"#6b7280",backgroundColor:m==="allow"?"#16a34a":"#f3f4f6",borderColor:m==="allow"?"#16a34a":"#d1d5db","&:hover":{backgroundColor:m==="allow"?"#15803d":"#e5e7eb",borderColor:m==="allow"?"#15803d":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#16a34a",color:"#ffffff","&:hover":{backgroundColor:"#15803d"}}},children:[O(Qn,{sx:{fontSize:16,mr:.5}}),n("publicPolicies.fields.conditions.states.allow")]}),O(Er,{value:"owner_allow",onClick:()=>y(g,"owner_allow"),disabled:i,sx:{px:2,color:m==="owner_allow"?"#ffffff":"#6b7280",backgroundColor:m==="owner_allow"?"#0ea5e9":"#f3f4f6",borderColor:m==="owner_allow"?"#0ea5e9":"#d1d5db","&:hover":{backgroundColor:m==="owner_allow"?"#0284c7":"#e5e7eb",borderColor:m==="owner_allow"?"#0284c7":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#0ea5e9",color:"#ffffff","&:hover":{backgroundColor:"#0284c7"}}},children:n("publicPolicies.fields.conditions.states.ownerAllow")}),Ce(Er,{value:"deny",onClick:()=>y(g,"deny"),disabled:i,sx:{px:2,color:m==="deny"?"#ffffff":"#6b7280",backgroundColor:m==="deny"?"#dc2626":"#f3f4f6",borderColor:m==="deny"?"#dc2626":"#d1d5db","&:hover":{backgroundColor:m==="deny"?"#b91c1c":"#e5e7eb",borderColor:m==="deny"?"#b91c1c":"#9ca3af"},"&.Mui-selected":{backgroundColor:"#dc2626",color:"#ffffff","&:hover":{backgroundColor:"#b91c1c"}}},children:[O(ei,{sx:{fontSize:16,mr:.5}}),n("publicPolicies.fields.conditions.states.deny")]})]})]},g)})})]}),t&&O(Yo,{error:!0,sx:{mt:1},children:t})]})},Ir=ti;import{jsx as U,jsxs as j}from"react/jsx-runtime";var yi=ni(({policy:e,onChange:r,onRemove:o,availableFields:t,isSubmitting:i=!1,usedActions:n,error:l},a)=>{let{t:u}=ii(),h=new Set(Array.from(n||[]));h.delete(e.action);let d=jo.map(b=>({value:b,label:u(`publicPolicies.fields.action.options.${b}`)}));return j(Zo,{ref:a,sx:{p:3,border:"1px solid #d1d9e0",borderRadius:2,position:"relative",backgroundColor:"#ffffff"},children:[j(ke,{sx:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",mb:3},children:[U(_e,{variant:"subtitle1",sx:{fontWeight:600,color:"#111418",fontSize:"1rem"},children:u("publicPolicies.policyTitle")}),U(di,{onClick:o,size:"small",disabled:i,"aria-label":u("publicPolicies.removePolicy"),sx:{color:"#656d76","&:hover":{color:"#cf222e",backgroundColor:"rgba(207, 34, 46, 0.1)"}},children:U(gi,{})})]}),j(sr,{spacing:1,children:[U(sr,{direction:{xs:"column",md:"row"},spacing:2,children:U(ke,{sx:{flex:1,minWidth:200},children:j(si,{fullWidth:!0,children:[U(ai,{children:u("publicPolicies.fields.action.label")}),U(li,{value:e.action,label:u("publicPolicies.fields.action.label"),disabled:i,onChange:b=>{let w=b.target.value,c={...e,action:w};w==="delete"?(c.permission="deny",delete c.fields):(c.fields={allow:[],owner_allow:[],deny:t},delete c.permission),r(c)},sx:{backgroundColor:"#ffffff","&:hover .MuiOutlinedInput-notchedOutline":{borderColor:"#8c959f"},"&.Mui-focused .MuiOutlinedInput-notchedOutline":{borderColor:"#0969da",borderWidth:2}},children:d.map(b=>{let w=h.has(b.value);return U(ci,{value:b.value,disabled:w,children:b.label},b.value)})}),l&&U(ui,{error:!0,children:l})]})})}),e.action==="delete"?j(ke,{children:[U(_e,{variant:"body2",color:"text.secondary",sx:{mb:2},children:u("publicPolicies.fields.conditions.label")}),j(sr,{direction:"row",spacing:1,sx:{mb:1},children:[U(Ar,{variant:e.permission==="*"?"contained":"outlined",startIcon:U(mi,{}),onClick:()=>r({...e,permission:"*"}),disabled:i,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="*"&&{backgroundColor:"#16a34a","&:hover":{backgroundColor:"#15803d"}}},children:u("publicPolicies.fields.conditions.allFields")}),U(Ar,{variant:e.permission==="owner"?"contained":"outlined",onClick:()=>r({...e,permission:"owner"}),disabled:i,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="owner"&&{backgroundColor:"#0ea5e9","&:hover":{backgroundColor:"#0284c7"}}},children:u("publicPolicies.fields.conditions.states.ownerAllow")}),U(Ar,{variant:e.permission==="deny"?"contained":"outlined",startIcon:U(fi,{}),onClick:()=>r({...e,permission:"deny"}),disabled:i,size:"small",sx:{minWidth:140,whiteSpace:"nowrap",...e.permission==="deny"&&{backgroundColor:"#cf222e","&:hover":{backgroundColor:"#bc1f2c"}}},children:u("publicPolicies.fields.conditions.noFields")})]})]}):U(Ir,{value:e.fields||{allow:[],owner_allow:[],deny:[]},onChange:b=>r({...e,fields:b}),availableFields:t,disabled:i}),U(Zo,{variant:"outlined",sx:{p:2,backgroundColor:"#f9fafb"},children:e.action==="delete"?j(_e,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(ke,{component:"span",sx:{color:e.permission==="*"?"#16a34a":e.permission==="owner"?"#0ea5e9":"#dc2626"},children:[u("publicPolicies.fields.conditions.states.allow"),":"]})," ",e.permission||"-"]}):j(sr,{spacing:.5,divider:U(pi,{sx:{borderColor:"#e5e7eb"}}),children:[j(_e,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(ke,{component:"span",sx:{color:"#16a34a"},children:[u("publicPolicies.fields.conditions.states.allow"),":"]})," ",(e?.fields?.allow||[]).join(", ")||"-"]}),j(_e,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(ke,{component:"span",sx:{color:"#0ea5e9"},children:[u("publicPolicies.fields.conditions.states.ownerAllow"),":"]})," ",(e?.fields?.owner_allow||[]).join(", ")||"-"]}),j(_e,{variant:"body2",sx:{fontFamily:"monospace",color:"text.secondary"},children:[j(ke,{component:"span",sx:{color:"#dc2626"},children:[u("publicPolicies.fields.conditions.states.deny"),":"]})," ",(e?.fields?.deny||[]).join(", ")||"-"]})]})})]})]})}),Lr=yi;import{Fragment as Ri,jsx as ue,jsxs as lr}from"react/jsx-runtime";var Pi=()=>typeof globalThis<"u"&&globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,Ti=({policies:e,onChange:r,availableFields:o,errors:t,isSubmitting:i=!1})=>{let{t:n}=bi(),l=hi({}),a=new Set((e||[]).map(s=>s.action).filter(Boolean)),u=Ko.filter(s=>!a.has(s)),h=u.length>0,d=()=>{let s=u[0]||"create",y={id:Pi(),action:s};s==="delete"?y.permission="deny":y.fields={allow:[],owner_allow:[],deny:o};let g=[...e||[],y];r(g),setTimeout(()=>{let m=g.length-1,f=l.current[m];f&&f.scrollIntoView({behavior:"smooth",block:"center"})},100)},b=s=>{let y=[...e];y.splice(s,1),r(y)},w=(()=>{if(!t)return null;if(typeof t=="string")return t;let s=t._error;return typeof s=="string"?s:null})(),c=new Set((e||[]).map(s=>s.action));return lr(Ri,{children:[ue(Ci,{sx:{borderColor:"#e0e4e7"}}),lr(ar,{children:[ue(ar,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:3,children:lr(ar,{children:[ue(Qo,{variant:"h6",sx:{fontWeight:600,color:"#111418",mb:1},children:n("publicPolicies.title")}),ue(Qo,{variant:"body2",color:"text.secondary",sx:{fontSize:"0.875rem"},children:n("publicPolicies.description")})]})}),w&&ue(et,{severity:"error",sx:{mb:3},children:w}),lr(wi,{spacing:3,children:[(e||[]).length===0?ue(et,{severity:"info",children:n("publicPolicies.noPolicies")}):e.map((s,y)=>ue(Lr,{ref:g=>{l.current[y]=g},policy:s,onChange:g=>{let m=[...e];m[y]=g,r(m)},onRemove:()=>b(y),availableFields:o,isSubmitting:i,usedActions:c,error:typeof t=="object"&&t!==null&&!("_error"in t)&&s.id in t?t[s.id]:void 0},s.id)),h&&ue(ar,{children:ue(xi,{type:"button",variant:"outlined",startIcon:ue(vi,{}),onClick:d,disabled:i,sx:{borderColor:"#d0d7de",color:"#656d76","&:hover":{borderColor:"#8c959f",backgroundColor:"transparent"}},children:n("publicPolicies.addPolicy")})})]})]})]})},Xl=Ti;import{useState as Fr}from"react";import{Button as cr,TextField as rt,Box as ze,Alert as qe,Typography as ve,CircularProgress as Dr}from"@mui/material";import{jsx as _,jsxs as me}from"react/jsx-runtime";function oc(){let[e,r]=Fr(""),[o,t]=Fr(""),[i,n]=Fr(!1),{isAuthenticated:l,isLoading:a,error:u,login:h,logout:d,refreshTokens:b,clearError:w,isExpiringSoon:c,expiresIn:s}=be(),y=async f=>{if(f.preventDefault(),!e||!o)return;(await h(e,o)).success&&(r(""),t(""),n(!1))},g=async()=>{await d()},m=async()=>{await b()};return l?me(ze,{sx:{maxWidth:600,mx:"auto",p:3},children:[_(ve,{variant:"h4",gutterBottom:!0,children:"Welcome! \u{1F389}"}),_(qe,{severity:"success",sx:{mb:3},children:"You are successfully logged in with Refresh Token Pattern enabled"}),me(ze,{sx:{mb:3,p:2,bgcolor:"background.paper",border:1,borderColor:"divider",borderRadius:1},children:[_(ve,{variant:"h6",gutterBottom:!0,children:"Token Status"}),me(ve,{variant:"body2",color:"text.secondary",children:["Access Token expires in: ",Math.round(s/1e3/60)," minutes"]}),c&&_(qe,{severity:"warning",sx:{mt:1},children:"Token expires soon - automatic refresh will happen"})]}),me(ze,{sx:{display:"flex",gap:2,flexWrap:"wrap"},children:[_(cr,{variant:"contained",onClick:m,disabled:a,startIcon:a?_(Dr,{size:16}):null,children:"Refresh Tokens"}),_(cr,{variant:"outlined",color:"error",onClick:g,disabled:a,children:"Logout"})]}),u&&_(qe,{severity:"error",sx:{mt:2},onClose:w,children:u})]}):me(ze,{sx:{maxWidth:400,mx:"auto",p:3},children:[_(ve,{variant:"h4",gutterBottom:!0,align:"center",children:"Login with Refresh Tokens"}),_(qe,{severity:"info",sx:{mb:3},children:"This demo shows the new Refresh Token Pattern with automatic session management"}),i?me("form",{onSubmit:y,children:[_(rt,{fullWidth:!0,label:"Email",type:"email",value:e,onChange:f=>r(f.target.value),margin:"normal",required:!0,autoComplete:"email"}),_(rt,{fullWidth:!0,label:"Password",type:"password",value:o,onChange:f=>t(f.target.value),margin:"normal",required:!0,autoComplete:"current-password"}),_(cr,{type:"submit",fullWidth:!0,variant:"contained",size:"large",disabled:a,startIcon:a?_(Dr,{size:16}):null,sx:{mt:3,mb:2},children:a?"Logging in...":"Login"})]}):_(cr,{fullWidth:!0,variant:"contained",size:"large",onClick:()=>n(!0),sx:{mt:2},children:"Show Login Form"}),u&&_(qe,{severity:"error",sx:{mt:2},onClose:w,children:u})]})}function tc(){let{isAuthenticated:e,isLoading:r,isExpiringSoon:o,expiresIn:t}=be();return r?me(ze,{sx:{display:"flex",alignItems:"center",gap:1},children:[_(Dr,{size:16}),_(ve,{variant:"caption",children:"Loading session..."})]}):e?me(ze,{children:[_(ve,{variant:"caption",color:"success.main",children:"\u2713 Authenticated"}),o&&me(ve,{variant:"caption",color:"warning.main",display:"block",children:["\u26A0 Token expires in ",Math.round(t/1e3/60)," min"]})]}):_(ve,{variant:"caption",color:"text.secondary",children:"Not logged in"})}import Si from"@mui/material/TextField";import ki from"@mui/material/CircularProgress";import ot from"@mui/material/InputAdornment";import Ei from"@mui/material/IconButton";import Ii from"@mui/icons-material/Refresh";import{jsx as Pe}from"react/jsx-runtime";var Ai=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),Li=({html:e})=>Pe("span",{dangerouslySetInnerHTML:{__html:Ai(e)}}),pc=({config:e,value:r,onChange:o,label:t,error:i=!1,helperText:n,readOnly:l=!1,disabled:a=!1})=>{let{value:u,loading:h,error:d,regenerate:b}=Qr(e,{autoFetch:!r,onSuccess:m=>{o?.(m)}}),w=r||u,c=i||!!d,s=d||n,y=c&&s&&(s.toLowerCase().includes("duplicate")||s.toLowerCase().includes("duplicado")||s.toLowerCase().includes("duplicada")||s.toLowerCase().includes("unique")||s.toLowerCase().includes("\xFAnico")||s.toLowerCase().includes("unico")||s.toLowerCase().includes("\xFAnica")||s.toLowerCase().includes("unica")||s.toLowerCase().includes("already exists")||s.toLowerCase().includes("ya existe")||s.toLowerCase().includes("e11000"));return Pe(Si,{label:t,fullWidth:!0,value:w,error:c,helperText:s?Pe(Li,{html:s}):" ",disabled:a,InputProps:{readOnly:!0,startAdornment:h?Pe(ot,{position:"start",children:Pe(ki,{size:20})}):void 0,endAdornment:y&&!h?Pe(ot,{position:"end",children:Pe(Ei,{edge:"end",onClick:async()=>{!a&&!h&&await b()},disabled:a,size:"small",color:"error","aria-label":"regenerar c\xF3digo",title:"Regenerar c\xF3digo",children:Pe(Ii,{})})}):void 0}})};import Br,{useCallback as fe,useRef as tt,useState as Ge}from"react";import Ee from"@mui/material/Box";import Te from"@mui/material/Typography";import _r from"@mui/material/IconButton";import Fi from"@mui/material/LinearProgress";import dr from"@mui/material/CircularProgress";import it from"@mui/material/Chip";import Di from"@mui/material/Paper";import Bi from"@mui/material/List";import _i from"@mui/material/ListItem";import zi from"@mui/material/ListItemText";import Oi from"@mui/material/ListItemSecondaryAction";import Ui from"@mui/material/FormHelperText";import Mi from"@mui/material/Dialog";import Ni from"@mui/material/DialogTitle";import Wi from"@mui/material/DialogContent";import Hi from"@mui/material/DialogActions";import nt from"@mui/material/Button";import Vi from"@mui/icons-material/CloudUpload";import $i from"@mui/icons-material/InsertDriveFile";import ji from"@mui/icons-material/Image";import Ki from"@mui/icons-material/PictureAsPdf";import qi from"@mui/icons-material/Delete";import Gi from"@mui/icons-material/Refresh";import Xi from"@mui/icons-material/Restore";import Ji from"@mui/icons-material/CheckCircle";import Yi from"@mui/icons-material/Error";import $c from"@mui/icons-material/BrokenImage";import{jsx as P,jsxs as pe}from"react/jsx-runtime";var Zi=e=>e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,""),Qi=e=>{if(e===0)return"0 B";let r=1024,o=["B","KB","MB","GB"],t=Math.floor(Math.log(e)/Math.log(r));return`${parseFloat((e/Math.pow(r,t)).toFixed(1))} ${o[t]}`},es=e=>e.startsWith("image/")?P(ji,{color:"primary"}):e==="application/pdf"?P(Ki,{color:"error"}):P($i,{color:"action"}),rs=(e,r)=>{switch(e){case"completed":return P(Ji,{color:"success",fontSize:"small"});case"error":return P(Yi,{color:"error",fontSize:"small"});case"uploading":case"pending":return P(dr,{size:16});case"removing":return P(dr,{size:16,color:"error"});case"pendingDeletion":return P(it,{label:r("base.file.pendingDeletion"),size:"small",color:"warning",variant:"outlined",sx:{fontSize:"0.65rem",height:20}});default:return null}},os=({file:e,baseUrl:r,disabled:o,onRemove:t,onRestore:i,onRetry:n})=>{let{t:l}=Me(),[a,u]=Ge(!1),h=e.status==="pendingDeletion",d=!o&&e.status!=="uploading"&&e.status!=="removing"&&!h,b=!o&&h,w=!o&&e.status==="error"&&e.file,c=e.contentType.startsWith("image/"),s=e.visibility==="public"||e.filePath?.startsWith("public/")||e.filePath?.startsWith(r),g=!e.filePath||!s?null:e.filePath.startsWith("http://")||e.filePath.startsWith("https://")||e.filePath.startsWith(r)?e.filePath:`${r}${e.filePath}`,m=e.status==="completed"&&g,f=()=>c&&m&&!a?P(Ee,{component:m?"a":"div",href:g||void 0,target:"_blank",rel:"noopener noreferrer",sx:{width:48,height:48,borderRadius:1,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"grey.100",border:"1px solid",borderColor:"divider",cursor:m?"pointer":"default",transition:"all 0.2s ease",flexShrink:0,"&:hover":m?{borderColor:"primary.main",transform:"scale(1.05)"}:{}},children:P("img",{src:g,alt:e.name,style:{width:"100%",height:"100%",objectFit:"cover"},onError:()=>u(!0)})}):P(Ee,{component:m?"a":"div",href:g||void 0,target:"_blank",rel:"noopener noreferrer",sx:{width:48,height:48,borderRadius:1,display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"grey.50",border:"1px solid",borderColor:"divider",cursor:m?"pointer":"default",transition:"all 0.2s ease",flexShrink:0,textDecoration:"none","&:hover":m?{borderColor:"primary.main",bgcolor:"action.hover"}:{}},children:es(e.contentType)});return pe(_i,{sx:{borderRadius:1,mb:.5,bgcolor:e.status==="error"?"error.lighter":"background.paper",border:"1px solid",borderColor:e.status==="error"?"error.light":"divider",gap:1.5},children:[f(),P(zi,{primary:pe(Ee,{sx:{display:"flex",alignItems:"center",gap:1},children:[P(Te,{variant:"body2",noWrap:!0,sx:{maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",textDecoration:h?"line-through":"none",opacity:h?.6:1},children:e.name}),rs(e.status,l)]}),secondary:pe(Ee,{sx:{opacity:h?.6:1},children:[e.size>0&&P(Te,{variant:"caption",color:"text.secondary",children:Qi(e.size)}),e.status==="uploading"&&P(Fi,{variant:"determinate",value:e.progress,sx:{mt:.5,height:4,borderRadius:2}}),e.status==="error"&&e.errorMessage&&P(Te,{variant:"caption",color:"error",display:"block",children:e.errorMessage}),m&&P(Te,{variant:"caption",color:"primary",display:"block",component:"a",href:g||void 0,target:"_blank",rel:"noopener noreferrer",sx:{cursor:"pointer",textDecoration:"underline","&:hover":{textDecoration:"none"}},children:l(c?"base.file.clickToPreview":"base.file.clickToDownload")})]})}),pe(Oi,{children:[w&&P(_r,{edge:"end",size:"small",onClick:()=>n(e.id),color:"primary",title:l("base.file.restore"),children:P(Gi,{fontSize:"small"})}),b&&P(_r,{edge:"end",size:"small",onClick:()=>i(e.id),color:"primary",title:l("base.file.restore"),children:P(Xi,{fontSize:"small"})}),d&&P(_r,{edge:"end",size:"small",onClick:()=>t(e.id),color:"error",title:l("base.file.delete"),children:P(qi,{fontSize:"small"})})]})]})};var qc=({label:e,accept:r,maxFileSize:o=10*1024*1024,multiple:t=!1,maxFiles:i,minFiles:n=0,required:l=!1,disabled:a=!1,error:u=!1,helperText:h,onChange:d,onValidation:b,initialFiles:w,placeholder:c,showFileList:s=!0,visibility:y="private",showPreview:g=!0,baseUrl:m,onDeletionHandlersReady:f,mode:v="create"})=>{let{t:k}=Me(),z=tt(null),[p,C]=Ge(!1),[I,A]=Ge(!1),[Y,le]=Ge(null),[Q,ne]=Ge(!1),Oe=t?i:1,Ie=l?Math.max(n,1):n,H={acceptedTypes:r,maxFileSize:o,maxFiles:Oe,minFiles:Ie,visibility:y,mode:v,onFilesChange:L=>{let ce=L.filter(Je=>Je.status==="completed"&&Je.filePath).map(Je=>{let gr=Je.filePath;return gr.startsWith("/")?gr:`/${gr}`});d?.(ce)}},{files:V,isUploading:ee,addFiles:R,removeFile:S,restoreFile:W,retryUpload:ie,isValid:re,validationError:Ue,validationErrorKey:Re,validationErrorParams:Ae,initializeFiles:Xe,isTouched:Or,markAsTouched:E,isSubmitted:D,markAsSubmitted:M,getPreviewUrl:q,commitDeletions:G,restorePendingDeletions:X,hasPendingDeletions:ye,deleteFileImmediately:Ur,activeFiles:Ps,activeFileCount:ct,waitForUploads:Mr,completedFilePaths:Nr}=eo(H),Wr=fe(()=>Nr,[Nr]),Hr=tt(!1);Br.useEffect(()=>{w&&w.length>0&&!Hr.current&&(Hr.current=!0,Xe(w,m))},[w,Xe,m]),Br.useEffect(()=>{b?.(re,Ue)},[re,Ue,b]),Br.useEffect(()=>{f?.({commitDeletions:G,restorePendingDeletions:X,hasPendingDeletions:ye,markAsSubmitted:M,isValid:re,isUploading:ee,waitForUploads:Mr,getCompletedFilePaths:Wr})},[f,G,X,ye,M,re,ee,Mr,Wr]);let dt=fe(L=>{E();let ce=L.target.files;ce&&ce.length>0&&R(ce),z.current&&(z.current.value="")},[R,E]),ut=fe(()=>{a||z.current?.click()},[a]),pt=fe(L=>{L.preventDefault(),L.stopPropagation(),a||C(!0)},[a]),gt=fe(L=>{L.preventDefault(),L.stopPropagation(),C(!1)},[]),mt=fe(L=>{if(L.preventDefault(),L.stopPropagation(),C(!1),a)return;E();let ce=L.dataTransfer.files;ce&&ce.length>0&&R(ce)},[a,R,E]),ft=fe(async L=>{(await S(L)).needsConfirmation&&(le(L),A(!0))},[S]),yt=fe(async()=>{if(Y){ne(!0);try{let L=await Ur(Y);L.success||x.error("Error deleting file",{error:L.error})}finally{ne(!1),A(!1),le(null)}}},[Y,Ur]),Vr=fe(()=>{A(!1),le(null)},[]),ht=r?.join(",")||"",bt=!a&&(t||ct===0),$r=D&&!re,pr=u||$r,jr=h||($r&&Re?k(Re,Ae):null);return pe(Ee,{sx:{width:"100%"},children:[e&&pe(Te,{variant:"body2",sx:{mb:1,fontWeight:500,color:pr?"error.main":"text.primary"},children:[e,l&&P("span",{style:{color:"red"},children:" *"})]}),P("input",{ref:z,type:"file",accept:ht,multiple:t,onChange:dt,disabled:a,style:{display:"none"}}),bt&&pe(Di,{variant:"outlined",onClick:ut,onDragOver:pt,onDragLeave:gt,onDrop:mt,sx:{p:3,textAlign:"center",cursor:a?"not-allowed":"pointer",borderStyle:"dashed",borderWidth:2,borderColor:p?"primary.main":pr?"error.main":"divider",bgcolor:p?"primary.lighter":a?"action.disabledBackground":"background.paper",transition:"all 0.2s ease","&:hover":a?{}:{borderColor:"primary.main",bgcolor:"action.hover"}},children:[P(Vi,{sx:{fontSize:48,color:p?"primary.main":a?"action.disabled":"action.active",mb:1}}),P(Te,{variant:"body2",color:a?"text.disabled":"text.secondary",children:c||k(p?"base.file.dropHere":"base.file.dragOrClick")}),r&&r.length>0&&!p&&P(Ee,{sx:{mt:1,display:"flex",gap:.5,justifyContent:"center",flexWrap:"wrap"},children:r.map(L=>P(it,{label:L.split("/")[1]?.toUpperCase()||L,size:"small",variant:"outlined",sx:{fontSize:"0.7rem"}},L))})]}),s&&V.length>0&&P(Bi,{dense:!0,sx:{mt:1,p:0},children:V.map(L=>P(os,{file:L,baseUrl:m,disabled:a,onRemove:ft,onRestore:W,onRetry:ie},L.id))}),ee&&pe(Ee,{sx:{display:"flex",alignItems:"center",gap:1,mt:1},children:[P(dr,{size:16}),P(Te,{variant:"caption",color:"text.secondary",children:k("base.file.uploading")})]}),jr&&P(Ui,{error:pr,sx:{mt:.5},dangerouslySetInnerHTML:{__html:Zi(jr)}}),pe(Mi,{open:I,onClose:Q?void 0:Vr,children:[P(Ni,{children:k("base.file.confirmDelete.title")}),P(Wi,{children:P(Te,{children:k("base.file.confirmDelete.message")})}),pe(Hi,{children:[P(nt,{onClick:Vr,disabled:Q,children:k("base.file.confirmDelete.cancel")}),P(nt,{onClick:yt,color:"error",variant:"contained",disabled:Q,startIcon:Q?P(dr,{size:16,color:"inherit"}):void 0,children:k(Q?"base.file.deleting":"base.file.confirmDelete.confirm")})]})]})]})};import{useCallback as ts,useRef as ns,useEffect as is}from"react";import st from"@mui/material/Box";import at from"@mui/material/Typography";import lt from"@mui/material/FormHelperText";import{MDXEditor as ss,headingsPlugin as as,listsPlugin as ls,quotePlugin as cs,thematicBreakPlugin as ds,markdownShortcutPlugin as us,linkPlugin as ps,linkDialogPlugin as gs,tablePlugin as ms,toolbarPlugin as fs,UndoRedo as ys,BoldItalicUnderlineToggles as hs,BlockTypeSelect as bs,CreateLink as xs,InsertTable as ws,ListsToggle as Cs,Separator as ur}from"@mdxeditor/editor";import"@mdxeditor/editor/style.css";import{Fragment as vs,jsx as K,jsxs as zr}from"react/jsx-runtime";var td=({label:e,value:r="",onChange:o,required:t=!1,disabled:i=!1,error:n=!1,helperText:l,placeholder:a="Write here...",minHeight:u=200,maxHeight:h=500})=>{let d=ns(null);is(()=>{d.current&&d.current.getMarkdown()!==r&&d.current.setMarkdown(r||"")},[r]);let b=ts(w=>{o?.(w)},[o]);return zr(st,{sx:{width:"100%"},children:[e&&zr(at,{component:"label",sx:{display:"block",mb:.5,fontSize:"0.875rem",fontWeight:500,color:n?"error.main":"text.primary"},children:[e,t&&K(at,{component:"span",color:"error.main",sx:{ml:.5},children:"*"})]}),K(st,{sx:{border:1,borderColor:n?"error.main":"divider",borderRadius:1,overflow:"hidden",opacity:i?.6:1,pointerEvents:i?"none":"auto","& .mdxeditor":{minHeight:u,maxHeight:h,overflow:"auto"},"& .mdxeditor-toolbar":{borderBottom:1,borderColor:"divider",backgroundColor:"background.default"},"& .mdxeditor-root-contenteditable":{padding:2,minHeight:u-50}},children:K(ss,{ref:d,markdown:r||"",onChange:b,placeholder:a,readOnly:i,plugins:[as(),ls(),cs(),ds(),us(),ps(),gs(),ms(),fs({toolbarContents:()=>zr(vs,{children:[K(ys,{}),K(ur,{}),K(hs,{}),K(ur,{}),K(bs,{}),K(ur,{}),K(Cs,{}),K(ur,{}),K(xs,{}),K(ws,{})]})})]})}),l&&K(lt,{error:n,sx:{mx:0,mt:.5},children:l}),!l&&K(lt,{sx:{mx:0,mt:.5},children:"\xA0"})]})};export{ge as a,Rs as b,Ss as c,mr as d,Ze as e,Us as f,Me as g,ao as h,lo as i,Hs as j,uo as k,po as l,go as m,mo as n,ul as o,qn as p,jo as q,Ko as r,Xl as s,oc as t,tc as u,pc as v,qc as w,td as x};