@nocios/crudify-ui 4.4.74 → 4.4.78
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{CrudiaMarkdownField-Bs940oF4.d.ts → CrudiaMarkdownField-C30enyF9.d.ts} +2 -2
- package/dist/{CrudiaMarkdownField-CKPdr2JL.d.mts → CrudiaMarkdownField-D-VooBtq.d.mts} +2 -2
- package/dist/{api-Djqihi4n.d.mts → api-RK-xY1Ah.d.mts} +22 -2
- package/dist/{api-Djqihi4n.d.ts → api-RK-xY1Ah.d.ts} +22 -2
- package/dist/chunk-34FAL7YW.js +1 -0
- package/dist/chunk-3NGJBTRH.mjs +1 -0
- package/dist/chunk-AKTAAP5I.js +1 -0
- package/dist/{chunk-YLCEL2HE.js → chunk-ARGPCO6I.js} +1 -1
- package/dist/{chunk-7X3OJMPH.mjs → chunk-EHDTUR6X.mjs} +1 -1
- package/dist/{chunk-2RQAIPFB.mjs → chunk-FRHTVRUM.mjs} +1 -1
- package/dist/chunk-FRLGHMXE.js +1 -0
- package/dist/chunk-G5OBPMIH.mjs +1 -0
- package/dist/{chunk-N6OQJOCM.js → chunk-QCGDLS4D.js} +1 -1
- package/dist/chunk-SUWV767V.mjs +1 -0
- package/dist/components.d.mts +1 -1
- package/dist/components.d.ts +1 -1
- package/dist/components.js +1 -1
- package/dist/components.mjs +1 -1
- package/dist/{errorTranslation-BuEEtVg4.d.mts → errorTranslation-B4wcHzD3.d.mts} +1 -1
- package/dist/{errorTranslation-BIyBYuGF.d.ts → errorTranslation-CCC5IWoN.d.ts} +1 -1
- package/dist/hooks.d.mts +4 -3
- package/dist/hooks.d.ts +4 -3
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/{index-CQnAzvOE.d.mts → index-DEnlzdtV.d.mts} +90 -16
- package/dist/{index-BVT7flO5.d.ts → index-pQmuVg3q.d.ts} +90 -16
- package/dist/index.d.mts +12 -72
- package/dist/index.d.ts +12 -72
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/utils.d.mts +3 -3
- package/dist/utils.d.ts +3 -3
- package/dist/utils.js +1 -1
- package/dist/utils.mjs +1 -1
- package/package.json +3 -3
- package/coverage/base.css +0 -224
- package/coverage/block-navigation.js +0 -87
- package/coverage/configResolver.ts.html +0 -499
- package/coverage/coverage-final.json +0 -2
- package/coverage/favicon.png +0 -0
- package/coverage/index.html +0 -116
- package/coverage/prettify.css +0 -1
- package/coverage/prettify.js +0 -2
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +0 -210
- package/dist/chunk-4Z2XAMJA.js +0 -1
- package/dist/chunk-EXXKBYWY.js +0 -1
- package/dist/chunk-ML7JNB3X.mjs +0 -1
- package/dist/chunk-NXXCVAVE.js +0 -1
- package/dist/chunk-PK2UX3UH.mjs +0 -1
- package/dist/chunk-RPYFDF5Q.mjs +0 -1
|
@@ -18,8 +18,8 @@ interface UserLoginData {
|
|
|
18
18
|
username?: string;
|
|
19
19
|
email?: string;
|
|
20
20
|
userId?: string;
|
|
21
|
-
profile?:
|
|
22
|
-
[key: string]:
|
|
21
|
+
profile?: Record<string, unknown>;
|
|
22
|
+
[key: string]: unknown;
|
|
23
23
|
}
|
|
24
24
|
interface CrudifyLoginProps {
|
|
25
25
|
onScreenChange?: (screen: BoxScreenType, params?: Record<string, string>) => void;
|
|
@@ -18,8 +18,8 @@ interface UserLoginData {
|
|
|
18
18
|
username?: string;
|
|
19
19
|
email?: string;
|
|
20
20
|
userId?: string;
|
|
21
|
-
profile?:
|
|
22
|
-
[key: string]:
|
|
21
|
+
profile?: Record<string, unknown>;
|
|
22
|
+
[key: string]: unknown;
|
|
23
23
|
}
|
|
24
24
|
interface CrudifyLoginProps {
|
|
25
25
|
onScreenChange?: (screen: BoxScreenType, params?: Record<string, string>) => void;
|
|
@@ -3,7 +3,7 @@ interface CrudifyApiResponse<T = unknown> {
|
|
|
3
3
|
data?: T;
|
|
4
4
|
errors?: string | Record<string, string[]> | string[];
|
|
5
5
|
errorCode?: string;
|
|
6
|
-
fieldsWarning?: Record<string, string[]
|
|
6
|
+
fieldsWarning?: Record<string, string[]> | null;
|
|
7
7
|
}
|
|
8
8
|
interface CrudifyTransactionResponse {
|
|
9
9
|
success: boolean;
|
|
@@ -78,5 +78,25 @@ interface ValidationError {
|
|
|
78
78
|
message: string;
|
|
79
79
|
code: string;
|
|
80
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* Options for Crudify request operations
|
|
83
|
+
*/
|
|
84
|
+
interface CrudifyRequestOptions {
|
|
85
|
+
signal?: AbortSignal;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Represents a single operation within a transaction.
|
|
89
|
+
*/
|
|
90
|
+
interface TransactionOperation {
|
|
91
|
+
operation: "create" | "update" | "delete" | string;
|
|
92
|
+
moduleKey: string;
|
|
93
|
+
data?: Record<string, unknown>;
|
|
94
|
+
_id?: string;
|
|
95
|
+
[key: string]: unknown;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Input for transaction operations. Can be a single operation or an array of operations.
|
|
99
|
+
*/
|
|
100
|
+
type TransactionInput = TransactionOperation | TransactionOperation[] | Record<string, unknown>;
|
|
81
101
|
|
|
82
|
-
export type { ApiError as A, CrudifyApiResponse as C, ForgotPasswordRequest as F, JwtPayload as J, LoginResponse as L, ResetPasswordRequest as R, TransactionResponseData as T, UserProfile as U, ValidateCodeRequest as V, CrudifyTransactionResponse as a, LoginRequest as b, ValidationError as c };
|
|
102
|
+
export type { ApiError as A, CrudifyApiResponse as C, ForgotPasswordRequest as F, JwtPayload as J, LoginResponse as L, ResetPasswordRequest as R, TransactionResponseData as T, UserProfile as U, ValidateCodeRequest as V, CrudifyTransactionResponse as a, LoginRequest as b, ValidationError as c, CrudifyRequestOptions as d, TransactionInput as e };
|
|
@@ -3,7 +3,7 @@ interface CrudifyApiResponse<T = unknown> {
|
|
|
3
3
|
data?: T;
|
|
4
4
|
errors?: string | Record<string, string[]> | string[];
|
|
5
5
|
errorCode?: string;
|
|
6
|
-
fieldsWarning?: Record<string, string[]
|
|
6
|
+
fieldsWarning?: Record<string, string[]> | null;
|
|
7
7
|
}
|
|
8
8
|
interface CrudifyTransactionResponse {
|
|
9
9
|
success: boolean;
|
|
@@ -78,5 +78,25 @@ interface ValidationError {
|
|
|
78
78
|
message: string;
|
|
79
79
|
code: string;
|
|
80
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* Options for Crudify request operations
|
|
83
|
+
*/
|
|
84
|
+
interface CrudifyRequestOptions {
|
|
85
|
+
signal?: AbortSignal;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Represents a single operation within a transaction.
|
|
89
|
+
*/
|
|
90
|
+
interface TransactionOperation {
|
|
91
|
+
operation: "create" | "update" | "delete" | string;
|
|
92
|
+
moduleKey: string;
|
|
93
|
+
data?: Record<string, unknown>;
|
|
94
|
+
_id?: string;
|
|
95
|
+
[key: string]: unknown;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Input for transaction operations. Can be a single operation or an array of operations.
|
|
99
|
+
*/
|
|
100
|
+
type TransactionInput = TransactionOperation | TransactionOperation[] | Record<string, unknown>;
|
|
81
101
|
|
|
82
|
-
export type { ApiError as A, CrudifyApiResponse as C, ForgotPasswordRequest as F, JwtPayload as J, LoginResponse as L, ResetPasswordRequest as R, TransactionResponseData as T, UserProfile as U, ValidateCodeRequest as V, CrudifyTransactionResponse as a, LoginRequest as b, ValidationError as c };
|
|
102
|
+
export type { ApiError as A, CrudifyApiResponse as C, ForgotPasswordRequest as F, JwtPayload as J, LoginResponse as L, ResetPasswordRequest as R, TransactionResponseData as T, UserProfile as U, ValidateCodeRequest as V, CrudifyTransactionResponse as a, LoginRequest as b, ValidationError as c, CrudifyRequestOptions as d, TransactionInput as e };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 b=[/password[^:]*[:=]\s*[^\s,}]+/gi,/token[^:]*[:=]\s*[^\s,}]+/gi,/key[^:]*[:=]\s*["']?[^\s,}"']+/gi,/secret[^:]*[:=]\s*[^\s,}]+/gi,/authorization[^:]*[:=]\s*[^\s,}]+/gi,/mongodb(\+srv)?:\/\/[^\s]+/gi,/postgres:\/\/[^\s]+/gi,/mysql:\/\/[^\s]+/gi];function w(n){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp("(^|;)\\s*"+n+"=([^;]+)"));return e?e[2]:null}function S(){if(typeof window<"u"&&window.__CRUDIFY_ENV__)return window.__CRUDIFY_ENV__;let n=w("environment");return n&&["dev","stg","api","prod"].includes(n)?n:"prod"}var N=null,_="CrudifyUI",v=class{constructor(){this.explicitEnv=null;this.explicitEnv=N,this.prefix=_}getEffectiveEnv(){return this.explicitEnv!==null?this.explicitEnv:S()}sanitize(e){let t=e;for(let o of b)t=t.replace(o,"[REDACTED]");return t}sanitizeContext(e){let t={};for(let[o,r]of Object.entries(e))if(r!=null)if(o==="userId"&&typeof r=="string")t[o]=r.length>8?`${r.substring(0,8)}***`:r;else if(o==="email"&&typeof r=="string"){let[a,u]=r.split("@");t[o]=a&&u?`${a.substring(0,3)}***@${u}`:"[REDACTED]"}else typeof r=="string"?t[o]=this.sanitize(r):typeof r=="object"&&r!==null?t[o]=this.sanitizeContext(r):t[o]=r;return t}shouldLog(e){if(typeof window<"u"&&window.__CRUDIFY_DEBUG_MODE__)return!0;let t=this.getEffectiveEnv();return!((t==="prod"||t==="production"||t==="api")&&e!=="error")}log(e,t,o){if(!this.shouldLog(e))return;let r=this.sanitize(t),a=o?this.sanitizeContext(o):void 0,u={timestamp:new Date().toISOString(),level:e,environment:this.getEffectiveEnv(),service:this.prefix,message:r,...a&&Object.keys(a).length>0&&{context:a}},l=JSON.stringify(u);switch(e){case"error":console.error(l);break;case"warn":console.warn(l);break;case"info":console.info(l);break;case"debug":console.log(l);break}}error(e,t){let o;t instanceof Error?o={errorName:t.name,errorMessage:t.message,stack:t.stack}:o=t,this.log("error",e,o)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}getEnvironment(){return this.getEffectiveEnv()}setEnvironment(e){this.explicitEnv=e,N=e,typeof window<"u"&&(window.__CRUDIFY_ENV__=e)}isExplicitlyConfigured(){return this.explicitEnv!==null}},i= exports.a =new v;var f=n=>{let e=document.cookie.match(new RegExp("(^|;)\\s*"+n+"=([^;]+)"));return e?e[2]:null};function O(n={}){let{publicApiKey:e,env:t,appName:o,logo:r,loginActions:a,featureKeys:u,enableDebug:l=!1}=n,s={configSource:"none"};l&&i.info("[ConfigResolver] Resolving configuration...",{propsApiKey:e?`${e.substring(0,10)}...`:void 0,propsEnv:t,hasPropsAppName:!!o,hasPropsLogo:!!r,propsLoginActions:a,propsFeatureKeys:u});let d=f("publicApiKey");if(l&&i.info("[ConfigResolver] Cookie check:",{hasCookieApiKey:!!d,cookieApiKey:d?`${d.substring(0,10)}...`:null,allCookies:typeof document<"u"?document.cookie:"N/A"}),d){let c=f("environment"),p=f("appName"),y=f("logo"),R=f("loginActions"),C=f("featureKeys"),A=f("theme");return s={publicApiKey:decodeURIComponent(d),env:c&&["dev","stg","api","prod"].includes(c)?c:"prod",appName:p?decodeURIComponent(p):void 0,logo:y?decodeURIComponent(y):void 0,loginActions:R?decodeURIComponent(R).split(",").map(E=>E.trim()).filter(Boolean):void 0,featureKeys:C?decodeURIComponent(C).split(",").map(E=>E.trim()).filter(Boolean):void 0,theme:A?(()=>{try{return JSON.parse(decodeURIComponent(A))}catch(E){l&&i.warn("[ConfigResolver] Failed to parse theme cookie",E instanceof Error?{errorMessage:E.message}:{message:String(E)});return}})():void 0,configSource:"cookies"},l&&(i.info("[ConfigResolver] \u2705 Using COOKIES configuration",{env:s.env,hasAppName:!!s.appName,hasLogo:!!s.logo,loginActionsCount:_optionalChain([s, 'access', _2 => _2.loginActions, 'optionalAccess', _3 => _3.length]),featureKeysCount:_optionalChain([s, 'access', _4 => _4.featureKeys, 'optionalAccess', _5 => _5.length])}),typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s}return e?(s={publicApiKey:e,env:t||"prod",appName:o,logo:r,loginActions:a,featureKeys:u,configSource:"props"},l&&(i.info("[ConfigResolver] \u2705 Using PROPS configuration (fallback - no cookies found)",{env:s.env,hasAppName:!!s.appName,hasLogo:!!s.logo,loginActionsCount:_optionalChain([s, 'access', _6 => _6.loginActions, 'optionalAccess', _7 => _7.length]),featureKeysCount:_optionalChain([s, 'access', _8 => _8.featureKeys, 'optionalAccess', _9 => _9.length])}),typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s):(l&&i.error("[ConfigResolver] \u274C No configuration found! Neither cookies nor props have publicApiKey",{hasCookies:!!d,hasProps:!!e}),s)}function M(n={}){return O(n)}var k=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],D={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},L={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function h(n,e){let{translateFn:t,currentLanguage:o,enableDebug:r}=e;r&&i.debug(`[ErrorTranslation] Translating error code: ${n} (lang: ${o||"unknown"})`);let a=n.toUpperCase(),u=D[a],l=k.map(c=>c.replace("{category}",u||"general").replace("{code}",a));r&&i.debug("[ErrorTranslation] Searching keys:",{translationKeys:l});for(let c of l){let p=t(c);if(r&&i.debug(`[ErrorTranslation] Checking key: "${c}" -> result: "${p}" (same as key: ${p===c})`),p&&p!==c)return r&&i.debug(`[ErrorTranslation] Found translation at key: ${c} = "${p}"`),p}let s=L[a];if(s)return r&&i.debug(`[ErrorTranslation] Using default message: "${s}"`),s;let d=a.replace(/_/g," ").toLowerCase().replace(/\b\w/g,c=>c.toUpperCase());return r&&i.debug(`[ErrorTranslation] No translation found, using friendly code: "${d}"`),d}function U(n,e){return n.map(t=>h(t,e))}function x(n,e){let{enableDebug:t}=e;t&&i.debug("[ErrorTranslation] Translating error:",{error:n});let o=h(n.code,e);return o!==n.code.toUpperCase()&&o!==n.code?(t&&i.debug(`[ErrorTranslation] Using hierarchical translation: "${o}"`),n.field?`${n.field}: ${o}`:o):n.message&&!n.message.includes("Error:")&&n.message.length>0&&n.message!==n.code?(t&&i.debug(`[ErrorTranslation] No hierarchical translation found, using API message: "${n.message}"`),n.message):(t&&i.debug(`[ErrorTranslation] Using final fallback: "${o}"`),n.field?`${n.field}: ${o}`:o)}function z(n,e={}){let t={translateFn:n,currentLanguage:e.currentLanguage,enableDebug:e.enableDebug||!1};return{translateErrorCode:o=>h(o,t),translateErrorCodes:o=>U(o,t),translateError:o=>x(o,t),translateApiError:o=>_optionalChain([o, 'optionalAccess', _10 => _10.data, 'optionalAccess', _11 => _11.response, 'optionalAccess', _12 => _12.status])?h(o.data.response.status,t):_optionalChain([o, 'optionalAccess', _13 => _13.status])?h(o.status,t):_optionalChain([o, 'optionalAccess', _14 => _14.code])?h(o.code,t):"Unknown error"}}var m=class n{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return n.instance||(n.instance=new n),n.instance}emit(e,t){let o=Date.now();if(this.isHandlingAuthError&&this.lastEventType===e&&o-this.lastErrorTime<this.DEBOUNCE_TIME){i.debug(`AuthEventBus: Ignoring duplicate ${e} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=o,this.lastEventType=e,i.debug(`AuthEventBus: Emitting ${e} event`,t?{details:t}:void 0);let r={type:e,details:t,timestamp:o};this.listeners.forEach(a=>{try{a(r)}catch(u){i.error("AuthEventBus: Error in listener",u instanceof Error?u:{message:String(u)})}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},J= exports.i =m.getInstance();var g=class g{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return g.instance||(g.instance=new g),g.instance}subscribe(e){return this.listeners.add(e),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(e)}}unsubscribe(e){this.listeners.delete(e),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let e=this;window.history.pushState=function(...t){let o=e.originalPushState.apply(this,t);return e.notifyListeners(),o},window.history.replaceState=function(...t){let o=e.originalReplaceState.apply(this,t);return e.notifyListeners(),o},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(e=>{try{e()}catch(t){i.error("NavigationTracker: Error in navigation listener",t instanceof Error?t:{message:String(t)})}})}static reset(){_optionalChain([g, 'access', _15 => _15.instance, 'optionalAccess', _16 => _16.isPatched])&&g.instance.removePatches(),g.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};g.instance=null;var I=g;var T=n=>{try{let e=n.split(".");if(e.length!==3)return i.warn("Invalid JWT format: token must have 3 parts"),null;let t=e[1],o=t+"=".repeat((4-t.length%4)%4);return JSON.parse(atob(o))}catch(e){return i.warn("Failed to decode JWT token",e instanceof Error?{errorMessage:e.message}:{message:String(e)}),null}},j= exports.l =()=>{try{let n=null;if(n=sessionStorage.getItem("authToken"),n||(n=sessionStorage.getItem("token")),n||(n=localStorage.getItem("authToken")||localStorage.getItem("token")),!n)return null;let e=T(n);return e&&(e.email||e["cognito:username"])||null}catch(n){return i.warn("Failed to get current user email",n instanceof Error?{errorMessage:n.message}:{message:String(n)}),null}},q= exports.m =n=>{try{let e=T(n);if(!e||!e.exp)return!0;let t=Math.floor(Date.now()/1e3);return e.exp<t}catch (e2){return!0}};exports.a = i; exports.b = f; exports.c = O; exports.d = M; exports.e = h; exports.f = U; exports.g = x; exports.h = z; exports.i = J; exports.j = I; exports.k = T; exports.l = j; exports.m = q;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h as $,j as U}from"./chunk-G5OBPMIH.mjs";import{a as V}from"./chunk-SUWV767V.mjs";import{useState as K,useEffect as z,useCallback as j,useRef as v}from"react";import Q from"@nocios/crudify-browser";var J=(S={})=>{let{autoFetch:c=!0,retryOnError:N=!1,maxRetries:m=3}=S,{isAuthenticated:T,isInitialized:I,sessionData:u,tokens:p}=U(),[R,d]=K(null),[y,A]=K(c&&T),[C,E]=K(null),l=v(null),o=v(!0),g=v(0),f=v(0),F=j(()=>{if(!u)return null;let h=u["cognito:username"];return u.email||(typeof h=="string"?h:null)},[u]),P=j(()=>{d(null),E(null),A(!1),f.current=0},[]),D=j(async()=>{let h=F();if(!h){o.current&&(E("No user email available from session data"),A(!1));return}if(!I){o.current&&(E("Session not initialized"),A(!1));return}l.current&&l.current.abort();let e=new AbortController;l.current=e;let i=++g.current;try{o.current&&(A(!0),E(null));let s=await Q.readItems("users",{filter:{email:h},pagination:{limit:1}});if(i===g.current&&o.current&&!e.signal.aborted){let r=null;if(s.success){let t=s.data;if(Array.isArray(t)&&t.length>0)r=t[0];else if(t&&typeof t=="object"&&!Array.isArray(t)&&t.response?.data)try{let n=t.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch{}else t&&typeof t=="object"&&!Array.isArray(t)&&t.items&&Array.isArray(t.items)&&t.items.length>0&&(r=t.items[0]);if(!r&&t&&typeof t=="object"&&!Array.isArray(t)&&t.data?.response?.data)try{let n=t.data.response.data,a=typeof n=="string"?JSON.parse(n):n;a&&a.items&&Array.isArray(a.items)&&a.items.length>0&&(r=a.items[0])}catch{}}r?(d(r),E(null),f.current=0):(E("User profile not found in database"),d(null))}}catch(s){if(i===g.current&&o.current){let r=s;if(r.name==="AbortError")return;N&&f.current<m&&(r.message?.includes("Network Error")||r.message?.includes("Failed to fetch"))?(f.current++,setTimeout(()=>{o.current&&D()},1e3*f.current)):(E("Failed to load user profile from database"),d(null))}}finally{i===g.current&&o.current&&A(!1),l.current===e&&(l.current=null)}},[I,F,N,m]);return z(()=>{c&&T&&I?D():T||P()},[c,T,I,D,P]),z(()=>(o.current=!0,()=>{o.current=!1,l.current&&(l.current.abort(),l.current=null)}),[]),{user:{session:u,data:R},loading:y,error:C,refreshProfile:D,clearProfile:P}};import{useCallback as W}from"react";var te=()=>{let{isAuthenticated:S,isLoading:c,isInitialized:N,tokens:m,error:T,sessionData:I,login:u,logout:p,refreshTokens:R,clearError:d,getTokenInfo:y,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E}=U(),l=W(g=>{g?V.warn("useAuth.setToken() is deprecated. Use login() method instead for better security."):p()},[p]),o=m?.expiresAt?new Date(m.expiresAt):null;return{isAuthenticated:S,loading:c,error:T,token:m?.accessToken||null,user:I,tokenExpiration:o,setToken:l,logout:p,refreshToken:R,login:u,isExpiringSoon:A,expiresIn:C,refreshExpiresIn:E,getTokenInfo:y,clearError:d}};import{useCallback as w}from"react";import k from"@nocios/crudify-browser";var ae=()=>{let{isInitialized:S,isLoading:c,error:N,isAuthenticated:m,login:T}=U(),I=w(()=>S&&!c&&!N,[S,c,N]),u=w(async()=>new Promise((o,g)=>{let f=()=>{I()?o():N?g(new Error(N)):setTimeout(f,100)};f()}),[I,N]),p=w(async()=>{if(!I())throw new Error("System not ready. Check isInitialized, isLoading, and error states.")},[I]),R=w(async(o,g,f)=>(await p(),await k.readItems(o,g||{},f)),[p]),d=w(async(o,g,f)=>(await p(),await k.readItem(o,g,f)),[p]),y=w(async(o,g,f)=>(await p(),await k.createItem(o,g,f)),[p]),A=w(async(o,g,f)=>(await p(),await k.updateItem(o,g,f)),[p]),C=w(async(o,g,f)=>(await p(),await k.deleteItem(o,g,f)),[p]),E=w(async(o,g)=>(await p(),await k.transaction(o,g)),[p]),l=w(async(o,g)=>{try{let f=await T(o,g);return f.success?{success:!0,data:f.tokens}:{success:!1,errors:f.error||"Login failed"}}catch(f){return{success:!1,errors:f instanceof Error?f.message:"Login failed"}}},[T]);return{readItems:R,readItem:d,createItem:y,updateItem:A,deleteItem:C,transaction:E,login:l,isInitialized:S,isInitializing:c,initializationError:N,isReady:I,waitForReady:u}};import{useCallback as _}from"react";import b from"@nocios/crudify-browser";var Y={INVALID_CREDENTIALS:"warning",UNAUTHORIZED:"warning",INVALID_API_KEY:"error",USER_NOT_FOUND:"warning",USER_NOT_ACTIVE:"warning",NO_PERMISSION:"warning",ITEM_NOT_FOUND:"info",NOT_FOUND:"info",IN_USE:"warning",FIELD_ERROR:"warning",BAD_REQUEST:"warning",INTERNAL_SERVER_ERROR:"error",DATABASE_CONNECTION_ERROR:"error",INVALID_CONFIGURATION:"error",UNKNOWN_OPERATION:"error",TOO_MANY_REQUESTS:"warning"},M={INVALID_CREDENTIALS:"errors.auth.INVALID_CREDENTIALS",UNAUTHORIZED:"errors.auth.UNAUTHORIZED",INVALID_API_KEY:"errors.auth.INVALID_API_KEY",USER_NOT_FOUND:"errors.auth.USER_NOT_FOUND",USER_NOT_ACTIVE:"errors.auth.USER_NOT_ACTIVE",NO_PERMISSION:"errors.auth.NO_PERMISSION",ITEM_NOT_FOUND:"errors.data.ITEM_NOT_FOUND",NOT_FOUND:"errors.data.NOT_FOUND",IN_USE:"errors.data.IN_USE",FIELD_ERROR:"errors.data.FIELD_ERROR",BAD_REQUEST:"errors.data.BAD_REQUEST",INTERNAL_SERVER_ERROR:"errors.system.INTERNAL_SERVER_ERROR",DATABASE_CONNECTION_ERROR:"errors.system.DATABASE_CONNECTION_ERROR",INVALID_CONFIGURATION:"errors.system.INVALID_CONFIGURATION",UNKNOWN_OPERATION:"errors.system.UNKNOWN_OPERATION",TOO_MANY_REQUESTS:"errors.system.TOO_MANY_REQUESTS"},de=(S={})=>{let{showNotification:c}=$(),{showSuccessNotifications:N=!1,showErrorNotifications:m=!0,customErrorMessages:T={},defaultErrorMessage:I="Ha ocurrido un error inesperado",autoHideDuration:u=6e3,appStructure:p=[],translateFn:R=e=>e}=S,d=_(e=>{if(!e.success&&e.errors&&(Object.keys(e.errors).some(r=>r!=="_error"&&r!=="_graphql"&&r!=="_transaction")||e.errors._transaction?.includes("ONE_OR_MORE_OPERATIONS_FAILED")||e.errors._error?.includes("TOO_MANY_REQUESTS")))return!1;let i=e.data;return!(!e.success&&i?.response?.status==="TOO_MANY_REQUESTS")},[]),y=_((e,i)=>{let s=R(e);return s===e?i||R("error.unknown"):s},[R]),A=_(e=>["create","update","delete"].includes(e),[]),C=_((e,i)=>N?A(e)&&i?!0:p.some(s=>s.key===e):!1,[N,p,A]),E=_((e,i,s)=>{let r=s?.key&&typeof s.key=="string"?s.key:e,t=`action.onSuccess.${r}`,n=y(t);if(n!==R("error.unknown")){if(A(r)&&i){let a=`action.${i}Singular`,O=y(a);if(O!==R("error.unknown"))return R(t,{item:O});{let L=`action.onSuccess.${r}WithoutItem`,x=y(L);return x!==R("error.unknown")?x:n}}return n}return R("success.transaction")},[y,R,A]),l=_(e=>{if(e.errorCode&&T[e.errorCode])return T[e.errorCode];if(e.errorCode&&M[e.errorCode])return y(M[e.errorCode]);if(e.errorCode){let i=[`errors.auth.${e.errorCode}`,`errors.data.${e.errorCode}`,`errors.system.${e.errorCode}`,`errors.${e.errorCode}`];for(let s of i){let r=y(s);if(r!==R("error.unknown"))return r}}if(typeof e.data=="string"&&e.data.startsWith("errors.")){let i=y(e.data);if(i!==R("error.unknown"))return i}if(e.errors&&Object.keys(e.errors).length>0){let i=Object.keys(e.errors);if(i.length===1&&i[0]==="_transaction"){let s=e.errors._transaction;if(s?.includes("ONE_OR_MORE_OPERATIONS_FAILED"))return"";if(Array.isArray(s)&&s.length>0){let r=s[0];if(typeof r=="string"&&r!=="ONE_OR_MORE_OPERATIONS_FAILED")try{let t=JSON.parse(r);if(Array.isArray(t)&&t.length>0){let n=t[0];if(n?.response?.errorCode){let a=n.response.errorCode;if(M[a])return y(M[a]);let O=[`errors.auth.${a}`,`errors.data.${a}`,`errors.system.${a}`,`errors.${a}`];for(let L of O){let x=y(L);if(x!==y("error.unknown"))return x}}if(n?.response?.data)return n.response.data}if(t?.response?.message){let n=t.response.message.toLowerCase();return n.includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):n.includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):t.response.message}}catch{return r.toLowerCase().includes("expired")?y("resetPassword.linkExpired","El enlace ha expirado"):r.toLowerCase().includes("invalid")?y("resetPassword.invalidCode","C\xF3digo inv\xE1lido"):r}}return y("error.transaction","Error en la operaci\xF3n")}if(i.length===1&&i[0]==="_error"){let s=e.errors._error;return Array.isArray(s)?s[0]:String(s)}return i.length===1&&i[0]==="_graphql"?y("errors.system.DATABASE_CONNECTION_ERROR"):`${y("errors.data.FIELD_ERROR")}: ${i.join(", ")}`}return I||R("error.unknown")},[T,I,R,y]),o=_(e=>e.errorCode&&Y[e.errorCode]?Y[e.errorCode]:"error",[]),g=_(async(e,i,s)=>{let r=await b.createItem(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=s?.actionConfig,n=t?.key||"create",a=t?.moduleKey||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[m,C,c,l,o,E,u,d]),f=_(async(e,i,s)=>{let r=await b.updateItem(e,i,s),t=s?.skipNotifications===!0;if(!t&&!r.success&&m&&d(r)){let n=l(r),a=o(r);c(n,a,{autoHideDuration:u})}else if(!t&&r.success){let n=s?.actionConfig,a=n?.key||"update",O=n?.moduleKey||e;if(C(a,O)){let L=E(a,O,n);c(L,"success",{autoHideDuration:u})}}return r},[m,C,c,l,o,E,u,d]),F=_(async(e,i,s)=>{let r=await b.deleteItem(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}else if(r.success){let t=s?.actionConfig,n=t?.key||"delete",a=t?.moduleKey||e;if(C(n,a)){let O=E(n,a,t);c(O,"success",{autoHideDuration:u})}}return r},[m,C,c,l,o,E,u,d]),P=_(async(e,i,s)=>{let r=await b.readItem(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[m,c,l,o,u,d]),D=_(async(e,i,s)=>{let r=await b.readItems(e,i,s);if(!r.success&&m&&d(r)){let t=l(r),n=o(r);c(t,n,{autoHideDuration:u})}return r},[m,c,l,o,u,d]),q=_(async(e,i)=>{let s=await b.transaction(e,i),r=i?.skipNotifications===!0;if(!r&&!s.success&&m&&d(s)){let t=l(s),n=o(s);c(t,n,{autoHideDuration:u})}else if(!r&&s.success){let t="transaction",n,a=null;if(i?.actionConfig?(a=i.actionConfig,t=a.key,n=a.moduleKey):Array.isArray(e)&&e.length>0&&e[0].operation&&(t=e[0].operation,a=p.find(O=>O.key===t),a&&(n=a.moduleKey)),C(t,n)){let O=E(t,n,a);c(O,"success",{autoHideDuration:u})}}return s},[m,C,c,l,o,E,u,d,p]),h=_((e,i)=>{if(!e.success&&m&&d(e)){let s=l(e),r=o(e);c(s,r,{autoHideDuration:u})}else e.success&&N&&i&&c(i,"success",{autoHideDuration:u});return e},[m,N,c,l,o,u,d,R]);return{createItem:g,updateItem:f,deleteItem:F,readItem:P,readItems:D,transaction:q,handleResponse:h,getErrorMessage:l,getErrorSeverity:o,shouldShowNotification:d}};export{J as a,te as b,ae as c,de as d};
|
|
@@ -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 _chunk34FAL7YWjs = require('./chunk-34FAL7YW.js');var _react = require('react'); var _react2 = _interopRequireDefault(_react);var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser);var ue=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){_chunk34FAL7YWjs.a.error("[CredentialsEventBus] Error in listener",t instanceof Error?t:{message:String(t)})}}),this.listeners=[]}waitForCredentials(){return this.isReady&&this.credentials?Promise.resolve(this.credentials):new Promise(i=>{this.listeners.push(i)})}reset(){this.credentials=null,this.isReady=!1,this.listeners=[]}areCredentialsReady(){return this.isReady&&this.credentials!==null}},j= exports.a =ue.getInstance();var _jsxruntime = require('react/jsx-runtime');var Ie=_react.createContext.call(void 0, void 0),Ae= exports.b =({config:r,children:i})=>{let[e,t]=_react.useState.call(void 0, !0),[n,s]=_react.useState.call(void 0, null),[c,m]=_react.useState.call(void 0, !1),[w,A]=_react.useState.call(void 0, ""),[v,u]=_react.useState.call(void 0, );_react.useEffect.call(void 0, ()=>{if(!r.publicApiKey){s("No publicApiKey provided"),t(!1),m(!1);return}let l=`${r.publicApiKey}-${r.env}`;if(l===w&&c){t(!1);return}(async()=>{t(!0),s(null),m(!1);try{_crudifybrowser2.default.config(r.env||"prod");let y=await _crudifybrowser2.default.init(r.publicApiKey,"none");if(u(y),typeof _crudifybrowser2.default.transaction=="function"&&typeof _crudifybrowser2.default.login=="function")m(!0),A(l),y.apiEndpointAdmin&&y.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:y.apiEndpointAdmin,apiKey:y.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(y){let E=y instanceof Error?y.message:"Failed to initialize Crudify";_chunk34FAL7YWjs.a.error("[CrudifyProvider] Initialization error",y instanceof Error?y:{message:String(y)}),s(E),m(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,w,c]);let a={crudify:c?_crudifybrowser2.default:null,isLoading:e,error:n,isInitialized:c,adminCredentials:v};return _jsxruntime.jsx.call(void 0, Ie.Provider,{value:a,children:i})},ke= exports.c =()=>{let r=_react.useContext.call(void 0, Ie);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var f=class f{static setStorageType(i){f.storageType=i}static generateEncryptionKey(){let i=[navigator.userAgent,navigator.language,navigator.platform,screen.width,screen.height,Date.now().toString(),Math.random().toString(36)].join("|");return _cryptojs2.default.SHA256(i).toString()}static getEncryptionKey(){if(f.encryptionKey)return f.encryptionKey;let i=window.localStorage;if(!i)return f.encryptionKey=f.generateEncryptionKey(),f.encryptionKey;try{let e=i.getItem(f.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=f.generateEncryptionKey(),i.setItem(f.ENCRYPTION_KEY_STORAGE,e)),f.encryptionKey=e,e}catch (e2){return _chunk34FAL7YWjs.a.warn("Crudify: Cannot persist encryption key, using temporary key"),f.encryptionKey=f.generateEncryptionKey(),f.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch (e3){return!1}}static getStorage(){return f.storageType==="none"?null:f.isStorageAvailable(f.storageType)?window[f.storageType]:(_chunk34FAL7YWjs.a.warn(`Crudify: ${f.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=f.getEncryptionKey();return _cryptojs2.default.AES.encrypt(i,e).toString()}catch(e){return _chunk34FAL7YWjs.a.error("Crudify: Encryption failed",e instanceof Error?e:{message:String(e)}),i}}static decrypt(i){try{let e=f.getEncryptionKey();return _cryptojs2.default.AES.decrypt(i,e).toString(_cryptojs2.default.enc.Utf8)||i}catch(e){return _chunk34FAL7YWjs.a.error("Crudify: Decryption failed",e instanceof Error?e:{message:String(e)}),i}}static saveTokens(i){let e=f.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},n=f.encrypt(JSON.stringify(t));e.setItem(f.TOKEN_KEY,n),_chunk34FAL7YWjs.a.debug("Crudify: Tokens saved successfully")}catch(t){_chunk34FAL7YWjs.a.error("Crudify: Failed to save tokens",t instanceof Error?t:{message:String(t)})}}static getTokens(){let i=f.getStorage();if(!i)return null;try{let e=i.getItem(f.TOKEN_KEY);if(!e)return null;let t=f.decrypt(e),n=JSON.parse(t);return!n.accessToken||!n.refreshToken||!n.expiresAt||!n.refreshExpiresAt?(_chunk34FAL7YWjs.a.warn("Crudify: Incomplete token data found, clearing storage"),f.clearTokens(),null):Date.now()>=n.refreshExpiresAt?(_chunk34FAL7YWjs.a.info("Crudify: Refresh token expired, clearing storage"),f.clearTokens(),null):{accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt,refreshExpiresAt:n.refreshExpiresAt}}catch(e){return _chunk34FAL7YWjs.a.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),f.clearTokens(),null}}static clearTokens(){let i=f.getStorage();if(i)try{i.removeItem(f.TOKEN_KEY),_chunk34FAL7YWjs.a.debug("Crudify: Tokens cleared from storage")}catch(e){_chunk34FAL7YWjs.a.error("Crudify: Failed to clear tokens",e instanceof Error?e:{message:String(e)})}}static rotateEncryptionKey(){try{f.clearTokens(),f.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(f.ENCRYPTION_KEY_STORAGE),_chunk34FAL7YWjs.a.info("Crudify: Encryption key rotated successfully")}catch(i){_chunk34FAL7YWjs.a.error("Crudify: Failed to rotate encryption key",i instanceof Error?i:{message:String(i)})}}static hasValidTokens(){return f.getTokens()!==null}static getExpirationInfo(){let i=f.getTokens();if(!i)return null;let e=Date.now();return{accessExpired:e>=i.expiresAt,refreshExpired:e>=i.refreshExpiresAt,accessExpiresIn:Math.max(0,i.expiresAt-e),refreshExpiresIn:Math.max(0,i.refreshExpiresAt-e)}}static updateAccessToken(i,e){let t=f.getTokens();if(!t){_chunk34FAL7YWjs.a.warn("Crudify: Cannot update access token, no existing tokens found");return}f.saveTokens({...t,accessToken:i,expiresAt:e})}static subscribeToChanges(i){let e=t=>{if(t.key===f.TOKEN_KEY){if(t.newValue===null){_chunk34FAL7YWjs.a.debug("Crudify: Tokens removed in another tab"),i(null);return}if(t.newValue){_chunk34FAL7YWjs.a.debug("Crudify: Tokens updated in another tab");let n=f.getTokens();i(n)}}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};f.TOKEN_KEY="crudify_tokens",f.ENCRYPTION_KEY_STORAGE="crudify_enc_key",f.encryptionKey=null,f.storageType="localStorage";var T=f;var Q=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(console.log("[CRUDIFY_DEBUG] SessionManager.initialize() called"),this.initialized){console.log("[CRUDIFY_DEBUG] SessionManager already initialized, skipping");return}if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},console.log("[CRUDIFY_DEBUG] SessionManager config set, env:",this.config.env),T.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&(console.log("[CRUDIFY_DEBUG] About to initialize crudify SDK"),await this.ensureCrudifyInitialized(),console.log("[CRUDIFY_DEBUG] crudify SDK initialized")),_crudifybrowser2.default.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),_chunk34FAL7YWjs.i.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=T.getTokens();e?T.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):T.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&(console.log("[CRUDIFY_DEBUG] About to restore session"),await this.restoreSession(),console.log("[CRUDIFY_DEBUG] Session restored (or no session to restore)")),this.initialized=!0,console.log("[CRUDIFY_DEBUG] SessionManager.initialize() completed successfully")}async login(i,e){try{let t=await _crudifybrowser2.default.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let n=T.getTokens(),s=t.data,c={accessToken:s.token,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt,apiEndpointAdmin:_optionalChain([n, 'optionalAccess', _2 => _2.apiEndpointAdmin])||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:_optionalChain([n, 'optionalAccess', _3 => _3.apiKeyEndpointAdmin])||this.config.apiKeyEndpointAdmin};return T.saveTokens(c),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.onLoginSuccess, 'optionalCall', _6 => _6(c)]),{success:!0,tokens:c,data:s}}catch(t){return _chunk34FAL7YWjs.a.error("[SessionManager] Login error",t instanceof Error?t:{message:String(t)}),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async logout(){try{this.log("Logging out..."),await _crudifybrowser2.default.logout(),T.clearTokens(),this.log("Logout successful"),_optionalChain([this, 'access', _7 => _7.config, 'access', _8 => _8.onLogout, 'optionalCall', _9 => _9()])}catch(i){this.log("Logout error:",i),T.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=T.getTokens();if(!i)return this.log("No valid tokens found in storage"),!1;if(Date.now()>=i.refreshExpiresAt)return this.log("Refresh token expired, clearing storage"),T.clearTokens(),!1;if(_crudifybrowser2.default.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),_crudifybrowser2.default.getTokenData().isValid===!1){if(this.log("Restored access token is invalid or expired"),Date.now()<i.refreshExpiresAt&&(this.log("Access token expired but refresh is valid, attempting refresh..."),await this.refreshTokens())){this.log("Session restored successfully via token refresh");let n=T.getTokens();return n&&_optionalChain([this, 'access', _10 => _10.config, 'access', _11 => _11.onSessionRestored, 'optionalCall', _12 => _12(n)]),!0}return T.clearTokens(),await _crudifybrowser2.default.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),_optionalChain([this, 'access', _13 => _13.config, 'access', _14 => _14.onSessionRestored, 'optionalCall', _15 => _15(i)]),!0}catch(i){return this.log("Session restore error:",i),T.clearTokens(),await _crudifybrowser2.default.logout(),!1}}isAuthenticated(){return _crudifybrowser2.default.isLogin()||T.hasValidTokens()}getTokenInfo(){let i=_crudifybrowser2.default.getTokenData(),e=T.getExpirationInfo(),t=T.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:T.hasValidTokens(),apiEndpointAdmin:_optionalChain([t, 'optionalAccess', _16 => _16.apiEndpointAdmin]),apiKeyEndpointAdmin:_optionalChain([t, 'optionalAccess', _17 => _17.apiKeyEndpointAdmin])}}async refreshTokens(){if(this.isRefreshingLocally&&this.refreshPromise)return this.log("Refresh already in progress, waiting for existing promise..."),this.refreshPromise;this.isRefreshingLocally=!0,this.refreshPromise=this._performRefresh();try{return await this.refreshPromise}finally{this.isRefreshingLocally=!1,this.refreshPromise=null}}async _performRefresh(){try{this.log("Starting token refresh...");let i=await _crudifybrowser2.default.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),T.clearTokens(),_optionalChain([this, 'access', _18 => _18.config, 'access', _19 => _19.showNotification, 'optionalCall', _20 => _20(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _21 => _21.config, 'access', _22 => _22.onSessionExpired, 'optionalCall', _23 => _23()]),!1;let e=i.data,t={accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt};return T.saveTokens(t),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),T.clearTokens(),_optionalChain([this, 'access', _24 => _24.config, 'access', _25 => _25.showNotification, 'optionalCall', _26 => _26(this.getSessionExpiredMessage(),"warning")]),_optionalChain([this, 'access', _27 => _27.config, 'access', _28 => _28.onSessionExpired, 'optionalCall', _29 => _29()]),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){_crudifybrowser2.default.setResponseInterceptor(async i=>{this.updateLastActivity();let e=this.detectAuthorizationError(i);if(e.isAuthError){if(this.log("\u{1F6A8} Authorization error detected:",{errorType:e.errorType,shouldLogout:e.shouldTriggerLogout}),e.isRefreshTokenInvalid||e.isTokenRefreshFailed)return this.log("Refresh token invalid, emitting TOKEN_REFRESH_FAILED event"),_chunk34FAL7YWjs.i.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(T.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),_chunk34FAL7YWjs.i.emit("TOKEN_EXPIRED",{message:"Access token expired, refresh needed",error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})):(this.log("No valid tokens or irrecoverable error, emitting SESSION_EXPIRED event"),_chunk34FAL7YWjs.i.emit("SESSION_EXPIRED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"})))}return i}),this.log("Response interceptor configured (non-blocking mode)")}async ensureCrudifyInitialized(){if(console.log("[CRUDIFY_DEBUG] ensureCrudifyInitialized() called"),this.crudifyInitialized){console.log("[CRUDIFY_DEBUG] crudify already initialized, skipping");return}try{this.log("Initializing crudify SDK...");let i=_crudifybrowser2.default.getTokenData();if(console.log("[CRUDIFY_DEBUG] Existing tokenData:",i?"exists":"null"),i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0,console.log("[CRUDIFY_DEBUG] Crudify was already initialized by another service");return}let e=this.config.env||"stg";console.log("[CRUDIFY_DEBUG] Configuring crudify with env:",e),_crudifybrowser2.default.config(e);let t=this.config.publicApiKey,n=this.config.enableLogging?"debug":"none";console.log("[CRUDIFY_DEBUG] Calling crudify.init() with apiKey:",_optionalChain([t, 'optionalAccess', _30 => _30.substring, 'call', _31 => _31(0,8)])+"...","logLevel:",n);let s=await _crudifybrowser2.default.init(t,n);if(console.log("[CRUDIFY_DEBUG] crudify.init() response:",JSON.stringify(s)),s&&s.success===!1&&s.errors)throw console.error("[CRUDIFY_DEBUG] crudify.init() FAILED:",s.errors),new Error(`Failed to initialize crudify: ${JSON.stringify(s.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully"),console.log("[CRUDIFY_DEBUG] crudify SDK initialized successfully")}catch(i){throw console.error("[CRUDIFY_DEBUG] ensureCrudifyInitialized FAILED:",i),_chunk34FAL7YWjs.a.error("[SessionManager] Failed to initialize crudify",i instanceof Error?i:{message:String(i)}),i}}detectAuthorizationError(i){let e={isAuthError:!1,isRefreshTokenInvalid:!1,isTokenRefreshFailed:!1,isTokenExpired:!1,isUnauthorized:!1,isIrrecoverable:!1,shouldTriggerLogout:!1,errorType:"",errorDetails:null,userFriendlyMessage:""};if(i.errors&&Array.isArray(i.errors)){let t=i.errors.find(n=>n.errorType==="Unauthorized"||_optionalChain([n, 'access', _32 => _32.message, 'optionalAccess', _33 => _33.includes, 'call', _34 => _34("Unauthorized")])||_optionalChain([n, 'access', _35 => _35.message, 'optionalAccess', _36 => _36.includes, 'call', _37 => _37("Not Authorized")])||_optionalChain([n, 'access', _38 => _38.message, 'optionalAccess', _39 => _39.includes, 'call', _40 => _40("NOT_AUTHORIZED")])||_optionalChain([n, 'access', _41 => _41.message, 'optionalAccess', _42 => _42.includes, 'call', _43 => _43("Token")])||_optionalChain([n, 'access', _44 => _44.message, 'optionalAccess', _45 => _45.includes, 'call', _46 => _46("TOKEN")])||_optionalChain([n, 'access', _47 => _47.message, 'optionalAccess', _48 => _48.includes, 'call', _49 => _49("Authentication")])||_optionalChain([n, 'access', _50 => _50.message, 'optionalAccess', _51 => _51.includes, 'call', _52 => _52("UNAUTHENTICATED")])||_optionalChain([n, 'access', _53 => _53.extensions, 'optionalAccess', _54 => _54.code])==="UNAUTHENTICATED"||_optionalChain([n, 'access', _55 => _55.extensions, 'optionalAccess', _56 => _56.code])==="FORBIDDEN");t&&(e.isAuthError=!0,e.errorType="GraphQL Array",e.errorDetails=t,e.shouldTriggerLogout=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.",(_optionalChain([t, 'access', _57 => _57.message, 'optionalAccess', _58 => _58.includes, 'call', _59 => _59("TOKEN")])||_optionalChain([t, 'access', _60 => _60.message, 'optionalAccess', _61 => _61.includes, 'call', _62 => _62("Token")]))&&(e.isTokenExpired=!0),_optionalChain([t, 'access', _63 => _63.extensions, 'optionalAccess', _64 => _64.code])==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let n=Object.values(i.errors).flat().find(s=>typeof s=="string"&&(s.includes("NOT_AUTHORIZED")||s.includes("TOKEN_REFRESH_FAILED")||s.includes("TOKEN_HAS_EXPIRED")||s.includes("PLEASE_LOGIN")||s.includes("Unauthorized")||s.includes("UNAUTHENTICATED")||s.includes("SESSION_EXPIRED")||s.includes("INVALID_TOKEN")));n&&typeof n=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,n.includes("TOKEN_REFRESH_FAILED")?(e.isTokenRefreshFailed=!0,e.isRefreshTokenInvalid=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("TOKEN_HAS_EXPIRED")||n.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):n.includes("INVALID_TOKEN")?(e.isTokenExpired=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Token inv\xE1lido. Por favor, inicia sesi\xF3n nuevamente."):e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&_optionalChain([i, 'access', _65 => _65.data, 'optionalAccess', _66 => _66.response, 'optionalAccess', _67 => _67.status])){let t=i.data.response.status.toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED")&&(e.isAuthError=!0,e.errorType="Status",e.errorDetails=i.data.response,e.isUnauthorized=!0,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}if(!e.isAuthError&&_optionalChain([i, 'access', _68 => _68.data, 'optionalAccess', _69 => _69.response, 'optionalAccess', _70 => _70.data]))try{let t=typeof i.data.response.data=="string"?JSON.parse(i.data.response.data):i.data.response.data;(t.error==="REFRESH_TOKEN_INVALID"||t.error==="TOKEN_EXPIRED"||t.error==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Parsed Data",e.errorDetails=t,e.shouldTriggerLogout=!0,e.isIrrecoverable=!0,t.error==="REFRESH_TOKEN_INVALID"?(e.isRefreshTokenInvalid=!0,e.isTokenRefreshFailed=!0,e.userFriendlyMessage="Tu sesi\xF3n ha caducado. Por favor, inicia sesi\xF3n nuevamente."):(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."))}catch (e4){}if(!e.isAuthError&&i.errorCode){let t=String(i.errorCode).toUpperCase();(t==="UNAUTHORIZED"||t==="UNAUTHENTICATED"||t==="TOKEN_EXPIRED"||t==="INVALID_TOKEN")&&(e.isAuthError=!0,e.errorType="Error Code",e.errorDetails={errorCode:t},e.shouldTriggerLogout=!0,t==="TOKEN_EXPIRED"?e.isTokenExpired=!0:e.isUnauthorized=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente.")}return e}updateLastActivity(){this.lastActivityTime=Date.now(),this.log("Last activity updated")}getTimeSinceLastActivity(){return this.lastActivityTime===0?0:Date.now()-this.lastActivityTime}checkInactivity(){let i=this.getTimeSinceLastActivity();if(this.lastActivityTime===0)return"none";let e=1800*1e3;return i>e?(this.log(`Inactivity timeout: ${Math.floor(i/6e4)} minutes since last activity`),"logout"):"none"}clearSession(){T.clearTokens(),_crudifybrowser2.default.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?_chunk34FAL7YWjs.e.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(i,...e){this.config.enableLogging&&console.log(`[SessionManager] ${i}`,...e)}formatError(i){return i?typeof i=="string"?i:typeof i=="object"?Object.values(i).flat().map(String).join(", "):"Authentication failed":"Unknown error"}};function be(r={}){let[i,e]=_react.useState.call(void 0, {isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=Q.getInstance(),n=_react.useCallback.call(void 0, async()=>{console.log("[CRUDIFY_DEBUG] useSession.initialize() called");try{e(o=>({...o,isLoading:!0,error:null}));let u={autoRestore:_nullishCoalesce(r.autoRestore, () => (!0)),enableLogging:_nullishCoalesce(r.enableLogging, () => (!1)),showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(o=>({...o,isAuthenticated:!1,tokens:null,error:"Session expired"})),_optionalChain([r, 'access', _71 => _71.onSessionExpired, 'optionalCall', _72 => _72()])},onSessionRestored:o=>{e(y=>({...y,isAuthenticated:!0,tokens:o,error:null})),_optionalChain([r, 'access', _73 => _73.onSessionRestored, 'optionalCall', _74 => _74(o)])},onLoginSuccess:o=>{e(y=>({...y,isAuthenticated:!0,tokens:o,error:null}))},onLogout:()=>{e(o=>({...o,isAuthenticated:!1,tokens:null,error:null}))}};console.log("[CRUDIFY_DEBUG] About to call sessionManager.initialize()"),await t.initialize(u),console.log("[CRUDIFY_DEBUG] sessionManager.initialize() completed"),t.setupResponseInterceptor(),console.log("[CRUDIFY_DEBUG] Response interceptor configured");let a=t.isAuthenticated(),l=t.getTokenInfo();console.log("[CRUDIFY_DEBUG] isAuth:",a,"hasAccessToken:",!!l.crudifyTokens.accessToken),e(o=>({...o,isAuthenticated:a,isInitialized:!0,isLoading:!1,tokens:l.crudifyTokens.accessToken?{accessToken:l.crudifyTokens.accessToken,refreshToken:l.crudifyTokens.refreshToken,expiresAt:l.crudifyTokens.expiresAt,refreshExpiresAt:l.crudifyTokens.refreshExpiresAt}:null})),console.log("[CRUDIFY_DEBUG] Initialize completed successfully")}catch(u){let a=u instanceof Error?u.message:"Initialization failed";console.error("[CRUDIFY_DEBUG] Initialize FAILED with error:",a,u),e(l=>({...l,isLoading:!1,isInitialized:!0,error:a}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),s=_react.useCallback.call(void 0, async(u,a)=>{e(l=>({...l,isLoading:!0,error:null}));try{let l=await t.login(u,a);return l.success&&l.tokens?e(o=>({...o,isAuthenticated:!0,tokens:l.tokens,isLoading:!1,error:null})):e(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),l}catch(l){let o=l instanceof Error?l.message:"Login failed",y=o.includes("INVALID_CREDENTIALS")||o.includes("Invalid email")||o.includes("Invalid password")||o.includes("credentials");return e(E=>({...E,isAuthenticated:!1,tokens:null,isLoading:!1,error:y?null:o})),{success:!1,error:o}}},[t]),c=_react.useCallback.call(void 0, async()=>{e(u=>({...u,isLoading:!0}));try{await t.logout(),e(u=>({...u,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(u){e(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:u instanceof Error?u.message:"Logout error"}))}},[t]),m=_react.useCallback.call(void 0, async()=>{try{let u=await t.refreshTokens();if(u){let a=t.getTokenInfo();e(l=>({...l,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(a=>({...a,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return u}catch(u){return e(a=>({...a,isAuthenticated:!1,tokens:null,error:u instanceof Error?u.message:"Token refresh failed"})),!1}},[t]),w=_react.useCallback.call(void 0, ()=>{e(u=>({...u,error:null}))},[]),A=_react.useCallback.call(void 0, ()=>t.getTokenInfo(),[t]);_react.useEffect.call(void 0, ()=>{n()},[n]),_react.useEffect.call(void 0, ()=>{if(!i.isAuthenticated||!i.tokens)return;let u=_chunk34FAL7YWjs.j.getInstance(),a=()=>{t.updateLastActivity()},l=u.subscribe(a);window.addEventListener("popstate",a);let o=()=>{let P=t.getTokenInfo().crudifyTokens.expiresIn||0;return P<300*1e3?30*1e3:P<1800*1e3?60*1e3:120*1e3},y,E=()=>{let b=o();y=setTimeout(async()=>{if(t.isRefreshing()){E();return}let P=t.getTokenInfo(),S=P.crudifyTokens.expiresIn||0,O=((P.crudifyTokens.expiresAt||0)-(Date.now()-S))*.5;if(S>0&&S<=O)if(e(U=>({...U,isLoading:!0})),await t.refreshTokens()){let U=t.getTokenInfo();e(ae=>({...ae,isLoading:!1,tokens:U.crudifyTokens.accessToken?{accessToken:U.crudifyTokens.accessToken,refreshToken:U.crudifyTokens.refreshToken,expiresAt:U.crudifyTokens.expiresAt,refreshExpiresAt:U.crudifyTokens.refreshExpiresAt}:null}))}else e(U=>({...U,isLoading:!1,isAuthenticated:!1,tokens:null}));let k=t.getTimeSinceLastActivity(),W=1800*1e3;k>W?await c():E()},b)};return E(),()=>{clearTimeout(y),window.removeEventListener("popstate",a),l()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,c]),_react.useEffect.call(void 0, ()=>{let u=_chunk34FAL7YWjs.i.subscribe(async a=>{if(a.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;e(l=>({...l,isLoading:!0}));try{if(await t.refreshTokens()){let o=t.getTokenInfo();e(y=>({...y,isLoading:!1,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null}))}else _chunk34FAL7YWjs.i.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(l){_chunk34FAL7YWjs.i.emit("SESSION_EXPIRED",{message:l instanceof Error?l.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(a.type==="SESSION_EXPIRED"||a.type==="TOKEN_REFRESH_FAILED")&&(e(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:_optionalChain([a, 'access', _75 => _75.details, 'optionalAccess', _76 => _76.message])||"Session expired"})),_optionalChain([r, 'access', _77 => _77.onSessionExpired, 'optionalCall', _78 => _78()]))});return()=>u()},[r.onSessionExpired,t]),_react.useEffect.call(void 0, ()=>{let u=T.subscribeToChanges(a=>{a?e(l=>({...l,tokens:a,isAuthenticated:!0})):(e(l=>({...l,isAuthenticated:!1,tokens:null})),_chunk34FAL7YWjs.i.emit("SESSION_EXPIRED",{message:"Sesi\xF3n cerrada en otra pesta\xF1a",source:"CrossTabSync"}))});return()=>u()},[]);let v=_react.useCallback.call(void 0, ()=>{t.updateLastActivity()},[t]);return{...i,login:s,logout:c,refreshTokens:m,clearError:w,getTokenInfo:A,updateActivity:v,isExpiringSoon:i.tokens?i.tokens.expiresAt-Date.now()<300*1e3:!1,expiresIn:i.tokens?Math.max(0,i.tokens.expiresAt-Date.now()):0,refreshExpiresIn:i.tokens?Math.max(0,i.tokens.refreshExpiresAt-Date.now()):0}}var _material = require('@mui/material');var _uuid = require('uuid');var _dompurify = require('dompurify'); var _dompurify2 = _interopRequireDefault(_dompurify);var Se=_react.createContext.call(void 0, null),ti=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}),de= exports.g =({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:n=!1,allowHtml:s=!1})=>{let[c,m]=_react.useState.call(void 0, []),w=_react.useCallback.call(void 0, (a,l="info",o)=>{if(!n)return"";if(!a||typeof a!="string")return _chunk34FAL7YWjs.a.warn("GlobalNotificationProvider: Invalid message provided"),"";a.length>1e3&&(_chunk34FAL7YWjs.a.warn("GlobalNotificationProvider: Message too long, truncating"),a=a.substring(0,1e3)+"...");let y=_uuid.v4.call(void 0, ),E={id:y,message:a,severity:l,autoHideDuration:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _79 => _79.autoHideDuration]), () => (e)),persistent:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _80 => _80.persistent]), () => (!1)),allowHtml:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _81 => _81.allowHtml]), () => (s))};return m(b=>[...b.length>=i?b.slice(-(i-1)):b,E]),y},[i,e,n,s]),A=_react.useCallback.call(void 0, a=>{m(l=>l.filter(o=>o.id!==a))},[]),v=_react.useCallback.call(void 0, ()=>{m([])},[]),u={showNotification:w,hideNotification:A,clearAllNotifications:v};return _jsxruntime.jsxs.call(void 0, Se.Provider,{value:u,children:[r,n&&_jsxruntime.jsx.call(void 0, _material.Portal,{children:_jsxruntime.jsx.call(void 0, _material.Box,{sx:{position:"fixed",zIndex:9999,[t.vertical]:(t.vertical==="top",24),[t.horizontal]:t.horizontal==="right"||t.horizontal==="left"?24:"50%",...t.horizontal==="center"&&{transform:"translateX(-50%)"},display:"flex",flexDirection:t.vertical==="top"?"column":"column-reverse",gap:1,maxWidth:"400px",width:"auto"},children:c.map(a=>_jsxruntime.jsx.call(void 0, ri,{notification:a,onClose:()=>A(a.id)},a.id))})})]})},ri=({notification:r,onClose:i})=>{let[e,t]=_react.useState.call(void 0, !0),n=_react.useCallback.call(void 0, (s,c)=>{c!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);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:e,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:ti(r.message)}}):_jsxruntime.jsx.call(void 0, "span",{children:r.message})})})},we= exports.h =()=>{let r=_react.useContext.call(void 0, Se);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};var De=_react.createContext.call(void 0, void 0);function Re({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:n={}}){let s;try{let{showNotification:o}=we();s=o}catch (e5){}let c={};try{let o=ke();o.isInitialized&&o.adminCredentials&&(c=o.adminCredentials)}catch (e6){}let m=_react.useMemo.call(void 0, ()=>{let o=_chunk34FAL7YWjs.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _82 => _82.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _83 => _83.env]),enableDebug:_optionalChain([i, 'optionalAccess', _84 => _84.enableLogging])});return{publicApiKey:o.publicApiKey,env:o.env||"prod"}},[e,_optionalChain([i, 'optionalAccess', _85 => _85.enableLogging])]),w=_react2.default.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:c.apiEndpointAdmin,apiKeyEndpointAdmin:c.apiKeyEndpointAdmin,publicApiKey:m.publicApiKey,env:m.env,onSessionExpired:()=>{_optionalChain([i, 'access', _86 => _86.onSessionExpired, 'optionalCall', _87 => _87()])}}),[i,s,c.apiEndpointAdmin,c.apiKeyEndpointAdmin,m]),A=be(w),v=_react.useMemo.call(void 0, ()=>{let o=_chunk34FAL7YWjs.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _88 => _88.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _89 => _89.env]),appName:_optionalChain([e, 'optionalAccess', _90 => _90.appName]),logo:_optionalChain([e, 'optionalAccess', _91 => _91.logo]),loginActions:_optionalChain([e, 'optionalAccess', _92 => _92.loginActions]),enableDebug:_optionalChain([i, 'optionalAccess', _93 => _93.enableLogging])});return{publicApiKey:o.publicApiKey,env:o.env,appName:o.appName,loginActions:o.loginActions,logo:o.logo}},[e,_optionalChain([i, 'optionalAccess', _94 => _94.enableLogging])]),u=_react.useMemo.call(void 0, ()=>{if(!_optionalChain([A, 'access', _95 => _95.tokens, 'optionalAccess', _96 => _96.accessToken])||!A.isAuthenticated)return null;try{let o=_chunk34FAL7YWjs.k.call(void 0, A.tokens.accessToken);if(o&&o.sub&&o.email&&o.subscriber){let y={_id:o.sub,email:o.email,subscriberKey:o.subscriber};return Object.keys(o).forEach(E=>{["sub","email","subscriber"].includes(E)||(y[E]=o[E])}),y}}catch(o){_chunk34FAL7YWjs.a.error("Error decoding JWT token for sessionData",o instanceof Error?o:{message:String(o)})}return null},[_optionalChain([A, 'access', _97 => _97.tokens, 'optionalAccess', _98 => _98.accessToken]),A.isAuthenticated]),a={...A,sessionData:u,config:v},l={enabled:t,maxNotifications:n.maxNotifications||5,defaultAutoHideDuration:n.defaultAutoHideDuration||6e3,position:n.position||{vertical:"top",horizontal:"right"}};return _jsxruntime.jsx.call(void 0, De.Provider,{value:a,children:r})}function ct(r){let i={enabled:r.showNotifications,maxNotifications:_optionalChain([r, 'access', _99 => _99.notificationOptions, 'optionalAccess', _100 => _100.maxNotifications])||5,defaultAutoHideDuration:_optionalChain([r, 'access', _101 => _101.notificationOptions, 'optionalAccess', _102 => _102.defaultAutoHideDuration])||6e3,position:_optionalChain([r, 'access', _103 => _103.notificationOptions, 'optionalAccess', _104 => _104.position])||{vertical:"top",horizontal:"right"},allowHtml:_optionalChain([r, 'access', _105 => _105.notificationOptions, 'optionalAccess', _106 => _106.allowHtml])||!1};return _optionalChain([r, 'access', _107 => _107.config, 'optionalAccess', _108 => _108.publicApiKey])?_jsxruntime.jsx.call(void 0, Ae,{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, de,{...i,children:_jsxruntime.jsx.call(void 0, Re,{...r})})}):_jsxruntime.jsx.call(void 0, de,{...i,children:_jsxruntime.jsx.call(void 0, Re,{...r})})}function li(){let r=_react.useContext.call(void 0, De);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function ut(){let r=li();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 ht=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[n,s]=_react.useState.call(void 0, null),[c,m]=_react.useState.call(void 0, !1),[w,A]=_react.useState.call(void 0, null),[v,u]=_react.useState.call(void 0, {}),a=_react.useRef.call(void 0, null),l=_react.useRef.call(void 0, !0),o=_react.useRef.call(void 0, 0),y=_react.useRef.call(void 0, 0),E=_react.useCallback.call(void 0, ()=>{s(null),A(null),m(!1),u({})},[]),b=_react.useCallback.call(void 0, async()=>{let P=_chunk34FAL7YWjs.l.call(void 0, );if(!P){l.current&&(A("No user email available"),m(!1));return}a.current&&a.current.abort();let S=new AbortController;a.current=S;let N=++o.current;try{l.current&&(m(!0),A(null));let F=await _crudifybrowser2.default.readItems("users",{filter:{email:P},pagination:{limit:1}});if(N===o.current&&l.current&&!S.signal.aborted){let O=F.data;if(F.success&&O&&O.length>0){let k=O[0];s(k);let W={fullProfile:k,totalFields:Object.keys(k).length,displayData:{id:k.id,email:k.email,username:k.username,firstName:k.firstName,lastName:k.lastName,fullName:k.fullName||`${k.firstName||""} ${k.lastName||""}`.trim(),role:k.role,permissions:k.permissions||[],isActive:k.isActive,lastLogin:k.lastLogin,createdAt:k.createdAt,updatedAt:k.updatedAt,...Object.keys(k).filter(V=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(V)).reduce((V,U)=>({...V,[U]:k[U]}),{})}};u(W),A(null),y.current=0}else A("User profile not found"),s(null),u({})}}catch(F){if(N===o.current&&l.current){let O=F;if(O.name==="AbortError")return;e&&y.current<t&&(_optionalChain([O, 'access', _109 => _109.message, 'optionalAccess', _110 => _110.includes, 'call', _111 => _111("Network Error")])||_optionalChain([O, 'access', _112 => _112.message, 'optionalAccess', _113 => _113.includes, 'call', _114 => _114("Failed to fetch")]))?(y.current++,setTimeout(()=>{l.current&&b()},1e3*y.current)):(A("Failed to load user profile"),s(null),u({}))}}finally{N===o.current&&l.current&&m(!1),a.current===S&&(a.current=null)}},[e,t]);return _react.useEffect.call(void 0, ()=>{i&&b()},[i,b]),_react.useEffect.call(void 0, ()=>(l.current=!0,()=>{l.current=!1,a.current&&(a.current.abort(),a.current=null)}),[]),{userProfile:n,loading:c,error:w,extendedData:v,refreshProfile:b,clearProfile:E}};var Tt=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:n}=i,{prefix:s,padding:c=0,separator:m=""}=r,[w,A]=_react.useState.call(void 0, ""),[v,u]=_react.useState.call(void 0, !1),[a,l]=_react.useState.call(void 0, null),o=_react.useRef.call(void 0, !1),y=_react.useCallback.call(void 0, S=>{let N=String(S).padStart(c,"0");return`${s}${m}${N}`},[s,c,m]),E=_react.useCallback.call(void 0, async()=>{u(!0),l(null);try{let S=await _crudifybrowser2.default.getNextSequence(s),N=S.data;if(S.success&&_optionalChain([N, 'optionalAccess', _115 => _115.value])){let F=y(N.value);A(F),_optionalChain([t, 'optionalCall', _116 => _116(F)])}else{let F=_optionalChain([S, 'access', _117 => _117.errors, 'optionalAccess', _118 => _118._error, 'optionalAccess', _119 => _119[0]])||"Failed to generate code";l(F),_optionalChain([n, 'optionalCall', _120 => _120(F)])}}catch(S){let N=S instanceof Error?S.message:"Unknown error";l(N),_optionalChain([n, 'optionalCall', _121 => _121(N)])}finally{u(!1)}},[s,y,t,n]),b=_react.useCallback.call(void 0, async()=>{await E()},[E]),P=_react.useCallback.call(void 0, ()=>{l(null)},[]);return _react.useEffect.call(void 0, ()=>{e&&!w&&!o.current&&(o.current=!0,E())},[e,w,E]),{value:w,loading:v,error:a,regenerate:b,clearError:P}};var ye=class r{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:n,enableLogging:s,requestedBy:c}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&_chunk34FAL7YWjs.a.warn(`[CrudifyInitialization] ${c} attempted to initialize with different key. Already initialized with key: ${_optionalChain([this, 'access', _122 => _122.state, 'access', _123 => _123.publicApiKey, 'optionalAccess', _124 => _124.slice, 'call', _125 => _125(0,10)])}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&_chunk34FAL7YWjs.a.debug(`[CrudifyInitialization] ${c} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&_chunk34FAL7YWjs.a.debug(`[CrudifyInitialization] ${c} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(c),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(c),this.getState().status==="INITIALIZED"){s&&_chunk34FAL7YWjs.a.debug(`[CrudifyInitialization] ${c} found initialization completed by HIGH priority`);return}s&&_chunk34FAL7YWjs.a.warn(`[CrudifyInitialization] ${c} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(_chunk34FAL7YWjs.a.warn(`[CrudifyInitialization] HIGH priority request from ${c} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&_chunk34FAL7YWjs.a.debug(`[CrudifyInitialization] ${c} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=c,this.initializationPromise=this.performInitialization(t,n,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=n,this.state.error=null,s&&_chunk34FAL7YWjs.a.info(`[CrudifyInitialization] Successfully initialized by ${c} (${e} priority)`)}catch(m){throw this.state.status="ERROR",this.state.error=m instanceof Error?m:new Error(String(m)),this.initializationPromise=null,_chunk34FAL7YWjs.a.error(`[CrudifyInitialization] Initialization failed for ${c}`,m instanceof Error?m:{message:String(m)}),m}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let n=0,s=setInterval(()=>{if(n+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){n=0;return}n>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),i&&_chunk34FAL7YWjs.a.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let n=_crudifybrowser2.default.getTokenData();if(n&&n.endpoint){t&&_chunk34FAL7YWjs.a.debug("[CrudifyInitialization] SDK already initialized externally");return}_crudifybrowser2.default.config(e);let s=t?"debug":"none",c=await _crudifybrowser2.default.init(i,s);if(c.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(c.errors||"Unknown error")}`);c.apiEndpointAdmin&&c.apiKeyEndpointAdmin&&j.notifyCredentialsReady({apiUrl:c.apiEndpointAdmin,apiKey:c.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}}},oe= exports.o =ye.getInstance();var Ue=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,yi=r=>{let i=r.lastIndexOf("."),e=i>0?r.substring(i):"",t=Date.now(),n=Math.random().toString(36).substring(2,8);return`${t}_${n}${e}`},Ct= exports.p =(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:n=0,visibility:s="private",onUploadComplete:c,onUploadError:m,onFileRemoved:w,onFilesChange:A}=r,[v,u]=_react.useState.call(void 0, []),[a,l]=_react.useState.call(void 0, !1),o=_react.useRef.call(void 0, new Map),y=_react.useCallback.call(void 0, ()=>{l(!0)},[]),E=_react.useCallback.call(void 0, (d,h)=>{u(g=>g.map(I=>I.id===d?{...I,...h}:I))},[]),b=_react.useCallback.call(void 0, d=>{_optionalChain([A, 'optionalCall', _126 => _126(d)])},[A]),P=_react.useCallback.call(void 0, d=>i&&i.length>0&&!i.includes(d.type)?{valid:!1,error:`File type not allowed: ${d.type}`}:d.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),S=_react.useCallback.call(void 0, async(d,h)=>{try{if(!oe.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let g=yi(h.name),x=await _crudifybrowser2.default.generateSignedUrl({fileName:g,contentType:h.type,visibility:s});if(!x.success||!x.data)throw new Error("Failed to get upload URL");let I=x.data,{uploadUrl:L,s3Key:R,publicUrl:M}=I;if(!L||!R)throw new Error("Incomplete signed URL response");let X=R.indexOf("/"),Me=X>0?R.substring(X+1):R;E(d.id,{status:"uploading",progress:0}),await new Promise((le,B)=>{let z=new XMLHttpRequest;z.upload.addEventListener("progress",_=>{if(_.lengthComputable){let Ge=Math.round(_.loaded/_.total*100);E(d.id,{progress:Ge})}}),z.addEventListener("load",()=>{z.status>=200&&z.status<300?le():B(new Error(`Upload failed with status ${z.status}`))}),z.addEventListener("error",()=>{B(new Error("Network error during upload"))}),z.addEventListener("abort",()=>{B(new Error("Upload cancelled"))}),z.open("PUT",L),z.setRequestHeader("Content-Type",h.type),z.send(h)});let He={status:"completed",progress:100,filePath:Me,visibility:s,publicUrl:s==="public"?M:void 0,file:void 0};u(le=>{let B=le.map(_=>_.id===d.id?{..._,...He}:_);b(B);let z=B.find(_=>_.id===d.id);return z&&_optionalChain([c, 'optionalCall', _127 => _127(z)]),B})}catch(g){let x=g instanceof Error?g.message:"Unknown error";E(d.id,{status:"error",progress:0,errorMessage:x}),u(I=>{let L=I.find(R=>R.id===d.id);return L&&_optionalChain([m, 'optionalCall', _128 => _128(L,x)]),I})}},[E,c,m,s]),N=_react.useCallback.call(void 0, async d=>{let h=Array.from(d),g=[];u(x=>{if(t!==void 0){let R=x.filter(X=>X.status!=="error").length,M=t-R;if(M<=0)return _chunk34FAL7YWjs.a.warn(`File limit of ${t} already reached`),x;h.length>M&&(h=h.slice(0,M),_chunk34FAL7YWjs.a.warn(`Only ${M} files will be added to not exceed limit`))}let I=[];for(let R of h){let M=P(R),X={id:Ue(),name:R.name,size:R.size,contentType:R.type,status:M.valid?"pending":"error",progress:0,createdAt:Date.now(),file:M.valid?R:void 0,errorMessage:M.error};I.push(X)}g=I;let L=[...x,...I];return b(L),L}),setTimeout(()=>{let x=g.filter(I=>I.status==="pending"&&I.file);for(let I of x)if(I.file){let L=S(I,I.file);o.current.set(I.id,L),L.finally(()=>{o.current.delete(I.id)})}},0)},[t,P,S,b]),F=_react.useCallback.call(void 0, async d=>{let h=v.find(g=>g.id===d);if(!h)return!1;E(d,{status:"removing"});try{if(h.filePath){if(!oe.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");if(!(await _crudifybrowser2.default.disableFile({filePath:h.filePath})).success)throw new Error("Failed to remove file from server")}return u(g=>{let x=g.filter(I=>I.id!==d);return b(x),x}),_optionalChain([w, 'optionalCall', _129 => _129(h)]),!0}catch(g){return E(d,{status:h.filePath?"completed":"error",errorMessage:g instanceof Error?g.message:"Error removing file"}),!1}},[v,E,b,w]),O=_react.useCallback.call(void 0, ()=>{u([]),b([])},[b]),k=_react.useCallback.call(void 0, async d=>{let h=v.find(x=>x.id===d);if(!h||h.status!=="error"||!h.file){_chunk34FAL7YWjs.a.warn("Cannot retry: file not found or no original file");return}E(d,{status:"pending",progress:0,errorMessage:void 0});let g=S(h,h.file);o.current.set(d,g),g.finally(()=>{o.current.delete(d)})},[v,E,S]),W=_react.useCallback.call(void 0, async()=>{let d=Array.from(o.current.values());d.length>0&&await Promise.allSettled(d)},[]),V=d=>{let h=_optionalChain([d, 'access', _130 => _130.split, 'call', _131 => _131("."), 'access', _132 => _132.pop, 'call', _133 => _133(), 'optionalAccess', _134 => _134.toLowerCase, 'call', _135 => _135()])||"";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"}[h]||"application/octet-stream"},U=_react.useCallback.call(void 0, d=>{let h=d.map(g=>{let I=g.filePath.startsWith("http://")||g.filePath.startsWith("https://")?new URL(g.filePath).pathname:g.filePath,L=I.includes("/public/")||I.startsWith("public/")?"public":"private",R=g.contentType||V(g.name);return{id:Ue(),name:g.name,size:g.size||0,contentType:R,status:"completed",progress:100,filePath:g.filePath,visibility:L,createdAt:Date.now()}});u(h),b(h)},[b]),ae=_react.useCallback.call(void 0, async d=>{let h=v.find(g=>g.id===d);if(!h||!h.filePath)return null;if(h.visibility==="public"&&h.publicUrl)return h.publicUrl;try{if(!oe.isInitialized())return null;let g=await _crudifybrowser2.default.getFileUrl({filePath:h.filePath,expiresIn:3600}),x=g.data;return g.success&&_optionalChain([x, 'optionalAccess', _136 => _136.url])?x.url:null}catch (e7){return null}},[v]),Fe=_react.useMemo.call(void 0, ()=>v.some(d=>d.status==="uploading"||d.status==="pending"),[v]),Le=_react.useMemo.call(void 0, ()=>v.filter(d=>d.status==="uploading"||d.status==="pending").length,[v]),ze=_react.useMemo.call(void 0, ()=>v.filter(d=>d.status==="completed"&&d.filePath).map(d=>d.filePath),[v]),{isValid:Ke,validationError:Oe}=_react.useMemo.call(void 0, ()=>{let d=v.filter(g=>g.status==="completed").length;return d<n?{isValid:!1,validationError:n===1?"At least one file is required":`At least ${n} files are required`}:t!==void 0&&d>t?{isValid:!1,validationError:`Maximum ${t} files allowed`}:v.some(g=>g.status==="error")?{isValid:!1,validationError:"Some files have errors"}:{isValid:!0,validationError:null}},[v,n,t]);return{files:v,isUploading:Fe,pendingCount:Le,addFiles:N,removeFile:F,clearFiles:O,retryUpload:k,isValid:Ke,validationError:Oe,waitForUploads:W,completedFilePaths:ze,initializeFiles:U,isTouched:a,markAsTouched:y,getPreviewUrl:ae}};exports.a = j; exports.b = Ae; exports.c = ke; exports.d = T; exports.e = Q; exports.f = be; exports.g = de; exports.h = we; exports.i = ct; exports.j = li; exports.k = ut; exports.l = ht; exports.m = Tt; exports.n = ye; exports.o = oe; exports.p = Ct;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunk34FAL7YWjs = require('./chunk-34FAL7YW.js');var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var c=class{constructor(t="sessionStorage"){this.encryptionKey=this.generateEncryptionKey(),this.storage=t==="localStorage"?window.localStorage:window.sessionStorage}generateEncryptionKey(){let t=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset(),screen.colorDepth,screen.width,screen.height,"crudify-login"].join("|");return _cryptojs2.default.SHA256(t).toString()}setItem(t,e,n){try{let r=_cryptojs2.default.AES.encrypt(e,this.encryptionKey).toString();if(this.storage.setItem(t,r),n){let s=new Date().getTime()+n*60*1e3;this.storage.setItem(`${t}_expiry`,s.toString())}}catch(r){_chunk34FAL7YWjs.a.error("Failed to encrypt and store data",r instanceof Error?r:{message:String(r)})}}getItem(t){try{let e=`${t}_expiry`,n=this.storage.getItem(e);if(n){let g=parseInt(n,10);if(new Date().getTime()>g)return this.removeItem(t),null}let r=this.storage.getItem(t);if(!r)return null;let i=_cryptojs2.default.AES.decrypt(r,this.encryptionKey).toString(_cryptojs2.default.enc.Utf8);return i||(_chunk34FAL7YWjs.a.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return _chunk34FAL7YWjs.a.error("Failed to decrypt data",e instanceof Error?e:{message:String(e)}),this.removeItem(t),null}}removeItem(t){this.storage.removeItem(t),this.storage.removeItem(`${t}_expiry`)}setToken(t){try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=n.exp*1e3,s=new Date().getTime(),i=Math.floor((r-s)/(60*1e3));if(i>0){this.setItem("authToken",t,i);return}}}}catch (e2){_chunk34FAL7YWjs.a.warn("Failed to parse token expiry, using default expiry")}this.setItem("authToken",t,1440)}getToken(){let t=this.getItem("authToken");if(t)try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=Math.floor(Date.now()/1e3);if(n.exp<r)return this.removeItem("authToken"),null}}}catch (e3){return _chunk34FAL7YWjs.a.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}},y= exports.a =new c("sessionStorage"),h= exports.b =new c("localStorage");exports.a = y; exports.b = h;
|