@nocios/crudify-ui 4.4.86 → 4.4.92
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/coverage/base.css +224 -0
- package/coverage/block-navigation.js +87 -0
- package/coverage/coverage-final.json +68 -0
- package/coverage/favicon.png +0 -0
- package/coverage/index.html +431 -0
- package/coverage/prettify.css +1 -0
- package/coverage/prettify.js +2 -0
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +210 -0
- package/dist/{CrudiaMarkdownField-D-VooBtq.d.mts → CrudiaMarkdownField-CKuypna1.d.mts} +31 -1
- package/dist/{CrudiaMarkdownField-C30enyF9.d.ts → CrudiaMarkdownField-Cy8VBvkO.d.ts} +31 -1
- package/dist/chunk-34FAL7YW.js +1 -0
- package/dist/{chunk-2M2IM334.js → chunk-ARGPCO6I.js} +1 -1
- package/dist/chunk-DXIXGRHJ.mjs +1 -0
- package/dist/chunk-E4ILHUTV.js +1 -0
- package/dist/{chunk-PXFVXBFM.mjs → chunk-FRHTVRUM.mjs} +1 -1
- package/dist/chunk-HO44TY3Z.mjs +1 -0
- package/dist/chunk-KCWS6BRD.js +1 -0
- package/dist/{chunk-E342MLZO.js → chunk-OTCV6Y6D.js} +1 -1
- package/dist/{chunk-HI2IXLS6.mjs → chunk-QJI47CHZ.mjs} +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/hooks.d.mts +1 -1
- package/dist/hooks.d.ts +1 -1
- package/dist/hooks.js +1 -1
- package/dist/hooks.mjs +1 -1
- package/dist/{index-bgCgX03k.d.ts → index-By0tDIvO.d.ts} +45 -8
- package/dist/{index-DQAq3Wjl.d.mts → index-e0fEu7Sq.d.mts} +45 -8
- package/dist/index.d.mts +45 -3
- package/dist/index.d.ts +45 -3
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/dist/utils.js +1 -1
- package/dist/utils.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-7DIOFA73.mjs +0 -3
- package/dist/chunk-DJ3T7VVS.js +0 -1
- package/dist/chunk-HQKET2ZX.mjs +0 -1
- package/dist/chunk-L7LTBWM5.js +0 -3
- package/dist/chunk-UDDA2MQQ.js +0 -1
- package/dist/chunk-YSQ33BDT.mjs +0 -1
|
@@ -217,9 +217,9 @@ declare class SessionManager {
|
|
|
217
217
|
*/
|
|
218
218
|
private ensureCrudifyInitialized;
|
|
219
219
|
/**
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
220
|
+
* ✅ FASE 3.1: Detectar errores de autorización en todos los formatos posibles (mejorado)
|
|
221
|
+
* @param response - API response with dynamic structure that varies by error format
|
|
222
|
+
*/
|
|
223
223
|
private detectAuthorizationError;
|
|
224
224
|
/**
|
|
225
225
|
* ✅ FASE 2: Actualizar timestamp de última actividad del usuario
|
|
@@ -567,7 +567,7 @@ declare const useUserProfile: (options?: UseUserProfileOptions) => UseUserProfil
|
|
|
567
567
|
/**
|
|
568
568
|
* Individual file status
|
|
569
569
|
*/
|
|
570
|
-
type FileStatus = "pending" | "uploading" | "completed" | "error" | "removing";
|
|
570
|
+
type FileStatus = "pending" | "uploading" | "completed" | "error" | "removing" | "pendingDeletion";
|
|
571
571
|
/**
|
|
572
572
|
* Represents a file in the system
|
|
573
573
|
*/
|
|
@@ -604,6 +604,8 @@ interface FileItem {
|
|
|
604
604
|
createdAt: number;
|
|
605
605
|
/** Original file (only during upload) */
|
|
606
606
|
file?: File;
|
|
607
|
+
/** Whether this file existed before (was loaded from server) */
|
|
608
|
+
isExisting?: boolean;
|
|
607
609
|
}
|
|
608
610
|
/**
|
|
609
611
|
* Hook configuration
|
|
@@ -630,6 +632,8 @@ interface UseFileUploadOptions {
|
|
|
630
632
|
onFileRemoved?: (file: FileItem) => void;
|
|
631
633
|
/** Callback when the file list changes */
|
|
632
634
|
onFilesChange?: (files: FileItem[]) => void;
|
|
635
|
+
/** Form mode: 'create' or 'edit' - affects delete behavior */
|
|
636
|
+
mode?: "create" | "edit";
|
|
633
637
|
}
|
|
634
638
|
/**
|
|
635
639
|
* Hook return type
|
|
@@ -637,22 +641,40 @@ interface UseFileUploadOptions {
|
|
|
637
641
|
interface UseFileUploadReturn {
|
|
638
642
|
/** Current file list */
|
|
639
643
|
files: FileItem[];
|
|
644
|
+
/** Active files (excluding pendingDeletion) */
|
|
645
|
+
activeFiles: FileItem[];
|
|
646
|
+
/** Count of active files */
|
|
647
|
+
activeFileCount: number;
|
|
640
648
|
/** Whether uploads are in progress */
|
|
641
649
|
isUploading: boolean;
|
|
642
650
|
/** Number of pending uploads */
|
|
643
651
|
pendingCount: number;
|
|
644
652
|
/** Add files (triggers automatic upload) */
|
|
645
653
|
addFiles: (files: FileList | File[]) => Promise<void>;
|
|
646
|
-
/** Remove a file
|
|
647
|
-
removeFile: (fileId: string) => Promise<
|
|
654
|
+
/** Remove a file - returns whether confirmation is needed */
|
|
655
|
+
removeFile: (fileId: string) => Promise<{
|
|
656
|
+
needsConfirmation: boolean;
|
|
657
|
+
isExisting: boolean;
|
|
658
|
+
}>;
|
|
659
|
+
/** Delete a file immediately from server (for new files or create mode) */
|
|
660
|
+
deleteFileImmediately: (fileId: string) => Promise<{
|
|
661
|
+
success: boolean;
|
|
662
|
+
error?: string;
|
|
663
|
+
}>;
|
|
664
|
+
/** Restore a file that was marked for deletion */
|
|
665
|
+
restoreFile: (fileId: string) => boolean;
|
|
648
666
|
/** Clear all files */
|
|
649
667
|
clearFiles: () => void;
|
|
650
668
|
/** Retry upload for a failed file */
|
|
651
669
|
retryUpload: (fileId: string) => Promise<void>;
|
|
652
670
|
/** Validate if minimum requirements are met */
|
|
653
671
|
isValid: boolean;
|
|
654
|
-
/** Validation error message */
|
|
672
|
+
/** Validation error message (i18n key) */
|
|
655
673
|
validationError: string | null;
|
|
674
|
+
/** Validation error i18n key */
|
|
675
|
+
validationErrorKey: string | null;
|
|
676
|
+
/** Validation error params for i18n interpolation */
|
|
677
|
+
validationErrorParams: Record<string, string | number>;
|
|
656
678
|
/** Wait for all uploads to complete */
|
|
657
679
|
waitForUploads: () => Promise<void>;
|
|
658
680
|
/**
|
|
@@ -666,17 +688,32 @@ interface UseFileUploadReturn {
|
|
|
666
688
|
name: string;
|
|
667
689
|
size?: number;
|
|
668
690
|
contentType?: string;
|
|
669
|
-
}
|
|
691
|
+
}>, baseUrl?: string) => void;
|
|
670
692
|
/** Whether the user has interacted with the field */
|
|
671
693
|
isTouched: boolean;
|
|
672
694
|
/** Mark the field as touched (to show validation errors) */
|
|
673
695
|
markAsTouched: () => void;
|
|
696
|
+
/** Whether the form has been submitted */
|
|
697
|
+
isSubmitted: boolean;
|
|
698
|
+
/** Mark the form as submitted (to show all validation errors) */
|
|
699
|
+
markAsSubmitted: () => void;
|
|
674
700
|
/**
|
|
675
701
|
* Get URL for file preview
|
|
676
702
|
* - Public: returns publicUrl directly
|
|
677
703
|
* - Private: requests signed URL from backend
|
|
678
704
|
*/
|
|
679
705
|
getPreviewUrl: (fileId: string) => Promise<string | null>;
|
|
706
|
+
/** List of file IDs pending deletion */
|
|
707
|
+
pendingDeletions: string[];
|
|
708
|
+
/** Whether there are files pending deletion */
|
|
709
|
+
hasPendingDeletions: boolean;
|
|
710
|
+
/** Execute all pending deletions (call this on form submit) */
|
|
711
|
+
commitDeletions: () => Promise<{
|
|
712
|
+
success: boolean;
|
|
713
|
+
errors: string[];
|
|
714
|
+
}>;
|
|
715
|
+
/** Cancel all pending deletions and restore files */
|
|
716
|
+
restorePendingDeletions: () => void;
|
|
680
717
|
}
|
|
681
718
|
/**
|
|
682
719
|
* Hook for complete file handling with S3 upload
|
package/dist/index.d.mts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import crudify__default from '@nocios/crudify-browser';
|
|
2
2
|
export * from '@nocios/crudify-browser';
|
|
3
3
|
export { default as crudify } from '@nocios/crudify-browser';
|
|
4
|
-
import { d as CrudifyLoginConfig } from './CrudiaMarkdownField-
|
|
5
|
-
export { B as BoxScreenType, a as CrudiaAutoGenerate, i as CrudiaAutoGenerateProps, b as CrudiaFileField, j as CrudiaFileFieldProps, c as CrudiaMarkdownField, k as CrudiaMarkdownFieldProps, C as CrudifyLogin, e as CrudifyLoginProps, f as CrudifyLoginTranslations, L as LoginComponent, l as POLICY_ACTIONS, m as PREFERRED_POLICY_ORDER, P as Policies, h as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './CrudiaMarkdownField-
|
|
4
|
+
import { d as CrudifyLoginConfig } from './CrudiaMarkdownField-CKuypna1.mjs';
|
|
5
|
+
export { B as BoxScreenType, a as CrudiaAutoGenerate, i as CrudiaAutoGenerateProps, b as CrudiaFileField, n as CrudiaFileFieldDeletionHandlers, j as CrudiaFileFieldProps, c as CrudiaMarkdownField, k as CrudiaMarkdownFieldProps, C as CrudifyLogin, e as CrudifyLoginProps, f as CrudifyLoginTranslations, L as LoginComponent, l as POLICY_ACTIONS, m as PREFERRED_POLICY_ORDER, P as Policies, h as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './CrudiaMarkdownField-CKuypna1.mjs';
|
|
6
6
|
import React, { ReactNode } from 'react';
|
|
7
7
|
export { A as ApiError, C as CrudifyApiResponse, a as CrudifyTransactionResponse, F as ForgotPasswordRequest, J as JwtPayload, b as LoginRequest, L as LoginResponse, R as ResetPasswordRequest, T as TransactionResponseData, U as UserProfile, V as ValidateCodeRequest, c as ValidationError } from './api-RK-xY1Ah.mjs';
|
|
8
|
-
export { F as FileItem, v as FileStatus, L as LoginResult, N as NotificationOptions, a as SessionConfig, g as SessionDebugInfo, S as SessionManager, e as SessionProvider, h as SessionProviderProps, d as SessionState, c as StorageType, b as TokenData, T as TokenStorage, n as UseAuthReturn, p as UseDataReturn, s as UseFileUploadOptions, t as UseFileUploadReturn, U as UseSessionOptions, k as UseUserDataOptions, j as UseUserDataReturn, l as UserData, m as useAuth, w as useCrudifyWithNotifications, o as useData, r as useFileUpload, u as useSession, f as useSessionContext, i as useUserData, q as useUserProfile } from './index-
|
|
8
|
+
export { F as FileItem, v as FileStatus, L as LoginResult, N as NotificationOptions, a as SessionConfig, g as SessionDebugInfo, S as SessionManager, e as SessionProvider, h as SessionProviderProps, d as SessionState, c as StorageType, b as TokenData, T as TokenStorage, n as UseAuthReturn, p as UseDataReturn, s as UseFileUploadOptions, t as UseFileUploadReturn, U as UseSessionOptions, k as UseUserDataOptions, j as UseUserDataReturn, l as UserData, m as useAuth, w as useCrudifyWithNotifications, o as useData, r as useFileUpload, u as useSession, f as useSessionContext, i as useUserData, q as useUserProfile } from './index-e0fEu7Sq.mjs';
|
|
9
9
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
10
10
|
import { ThemeOptions } from '@mui/material';
|
|
11
11
|
export { A as AutoGenerateConfig, G as GlobalNotificationProvider, a as GlobalNotificationProviderProps, N as Notification, b as NotificationSeverity, d as UseAutoGenerateOptions, U as UseAutoGenerateReturn, c as useAutoGenerate, u as useGlobalNotification } from './GlobalNotificationProvider-Zq18OkpI.mjs';
|
|
@@ -828,6 +828,27 @@ declare const CRITICAL_TRANSLATIONS: {
|
|
|
828
828
|
readonly "resetPassword.title": "Nueva Contraseña";
|
|
829
829
|
readonly "resetPassword.validatingCode": "Validando código...";
|
|
830
830
|
readonly "modules.form.publicPolicies.fields.conditions.customEdit": "Edición personalizada";
|
|
831
|
+
readonly "file.clickToPreview": "Clic para ver imagen";
|
|
832
|
+
readonly "file.clickToDownload": "Clic para descargar";
|
|
833
|
+
readonly "file.privateFile": "Archivo privado";
|
|
834
|
+
readonly "file.noPreview": "Sin vista previa";
|
|
835
|
+
readonly "file.dropHere": "Suelta el archivo aquí";
|
|
836
|
+
readonly "file.dragOrClick": "Arrastra archivos aquí o haz clic para seleccionar";
|
|
837
|
+
readonly "file.uploading": "Subiendo archivos...";
|
|
838
|
+
readonly "file.restore": "Restaurar";
|
|
839
|
+
readonly "file.delete": "Eliminar";
|
|
840
|
+
readonly "file.pendingDeletion": "Pendiente de eliminación";
|
|
841
|
+
readonly "file.allowedTypes": "Tipos permitidos: {{types}}";
|
|
842
|
+
readonly "file.maxSize": "Máximo {{size}} por archivo";
|
|
843
|
+
readonly "file.maxFiles": "Máximo {{count}} archivos";
|
|
844
|
+
readonly "file.validation.minFilesRequired": "Se requiere al menos un archivo";
|
|
845
|
+
readonly "file.validation.minFilesRequiredPlural": "Se requieren al menos {{count}} archivos";
|
|
846
|
+
readonly "file.validation.maxFilesExceeded": "Máximo {{count}} archivos permitidos";
|
|
847
|
+
readonly "file.validation.filesWithErrors": "Algunos archivos tienen errores";
|
|
848
|
+
readonly "file.confirmDelete.title": "Eliminar archivo";
|
|
849
|
+
readonly "file.confirmDelete.message": "¿Estás seguro de que deseas eliminar este archivo? Esta acción no se puede deshacer.";
|
|
850
|
+
readonly "file.confirmDelete.confirm": "Eliminar";
|
|
851
|
+
readonly "file.confirmDelete.cancel": "Cancelar";
|
|
831
852
|
};
|
|
832
853
|
readonly en: {
|
|
833
854
|
readonly "checkCode.codeLabel": "Verification Code";
|
|
@@ -939,6 +960,27 @@ declare const CRITICAL_TRANSLATIONS: {
|
|
|
939
960
|
readonly "resetPassword.title": "New Password";
|
|
940
961
|
readonly "resetPassword.validatingCode": "Validating code...";
|
|
941
962
|
readonly "modules.form.publicPolicies.fields.conditions.customEdit": "Custom Edit";
|
|
963
|
+
readonly "file.clickToPreview": "Click to preview";
|
|
964
|
+
readonly "file.clickToDownload": "Click to download";
|
|
965
|
+
readonly "file.privateFile": "Private file";
|
|
966
|
+
readonly "file.noPreview": "No preview";
|
|
967
|
+
readonly "file.dropHere": "Drop file here";
|
|
968
|
+
readonly "file.dragOrClick": "Drag files here or click to select";
|
|
969
|
+
readonly "file.uploading": "Uploading files...";
|
|
970
|
+
readonly "file.restore": "Restore";
|
|
971
|
+
readonly "file.delete": "Delete";
|
|
972
|
+
readonly "file.pendingDeletion": "Pending deletion";
|
|
973
|
+
readonly "file.allowedTypes": "Allowed types: {{types}}";
|
|
974
|
+
readonly "file.maxSize": "Max {{size}} per file";
|
|
975
|
+
readonly "file.maxFiles": "Max {{count}} files";
|
|
976
|
+
readonly "file.validation.minFilesRequired": "At least one file is required";
|
|
977
|
+
readonly "file.validation.minFilesRequiredPlural": "At least {{count}} files are required";
|
|
978
|
+
readonly "file.validation.maxFilesExceeded": "Maximum {{count}} files allowed";
|
|
979
|
+
readonly "file.validation.filesWithErrors": "Some files have errors";
|
|
980
|
+
readonly "file.confirmDelete.title": "Delete file";
|
|
981
|
+
readonly "file.confirmDelete.message": "Are you sure you want to delete this file? This action cannot be undone.";
|
|
982
|
+
readonly "file.confirmDelete.confirm": "Delete";
|
|
983
|
+
readonly "file.confirmDelete.cancel": "Cancel";
|
|
942
984
|
};
|
|
943
985
|
};
|
|
944
986
|
type CriticalTranslationKey = keyof typeof CRITICAL_TRANSLATIONS.es;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import crudify__default from '@nocios/crudify-browser';
|
|
2
2
|
export * from '@nocios/crudify-browser';
|
|
3
3
|
export { default as crudify } from '@nocios/crudify-browser';
|
|
4
|
-
import { d as CrudifyLoginConfig } from './CrudiaMarkdownField-
|
|
5
|
-
export { B as BoxScreenType, a as CrudiaAutoGenerate, i as CrudiaAutoGenerateProps, b as CrudiaFileField, j as CrudiaFileFieldProps, c as CrudiaMarkdownField, k as CrudiaMarkdownFieldProps, C as CrudifyLogin, e as CrudifyLoginProps, f as CrudifyLoginTranslations, L as LoginComponent, l as POLICY_ACTIONS, m as PREFERRED_POLICY_ORDER, P as Policies, h as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './CrudiaMarkdownField-
|
|
4
|
+
import { d as CrudifyLoginConfig } from './CrudiaMarkdownField-Cy8VBvkO.js';
|
|
5
|
+
export { B as BoxScreenType, a as CrudiaAutoGenerate, i as CrudiaAutoGenerateProps, b as CrudiaFileField, n as CrudiaFileFieldDeletionHandlers, j as CrudiaFileFieldProps, c as CrudiaMarkdownField, k as CrudiaMarkdownFieldProps, C as CrudifyLogin, e as CrudifyLoginProps, f as CrudifyLoginTranslations, L as LoginComponent, l as POLICY_ACTIONS, m as PREFERRED_POLICY_ORDER, P as Policies, h as PolicyAction, S as SessionStatus, g as UserLoginData, U as UserProfileDisplay } from './CrudiaMarkdownField-Cy8VBvkO.js';
|
|
6
6
|
import React, { ReactNode } from 'react';
|
|
7
7
|
export { A as ApiError, C as CrudifyApiResponse, a as CrudifyTransactionResponse, F as ForgotPasswordRequest, J as JwtPayload, b as LoginRequest, L as LoginResponse, R as ResetPasswordRequest, T as TransactionResponseData, U as UserProfile, V as ValidateCodeRequest, c as ValidationError } from './api-RK-xY1Ah.js';
|
|
8
|
-
export { F as FileItem, v as FileStatus, L as LoginResult, N as NotificationOptions, a as SessionConfig, g as SessionDebugInfo, S as SessionManager, e as SessionProvider, h as SessionProviderProps, d as SessionState, c as StorageType, b as TokenData, T as TokenStorage, n as UseAuthReturn, p as UseDataReturn, s as UseFileUploadOptions, t as UseFileUploadReturn, U as UseSessionOptions, k as UseUserDataOptions, j as UseUserDataReturn, l as UserData, m as useAuth, w as useCrudifyWithNotifications, o as useData, r as useFileUpload, u as useSession, f as useSessionContext, i as useUserData, q as useUserProfile } from './index-
|
|
8
|
+
export { F as FileItem, v as FileStatus, L as LoginResult, N as NotificationOptions, a as SessionConfig, g as SessionDebugInfo, S as SessionManager, e as SessionProvider, h as SessionProviderProps, d as SessionState, c as StorageType, b as TokenData, T as TokenStorage, n as UseAuthReturn, p as UseDataReturn, s as UseFileUploadOptions, t as UseFileUploadReturn, U as UseSessionOptions, k as UseUserDataOptions, j as UseUserDataReturn, l as UserData, m as useAuth, w as useCrudifyWithNotifications, o as useData, r as useFileUpload, u as useSession, f as useSessionContext, i as useUserData, q as useUserProfile } from './index-By0tDIvO.js';
|
|
9
9
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
10
10
|
import { ThemeOptions } from '@mui/material';
|
|
11
11
|
export { A as AutoGenerateConfig, G as GlobalNotificationProvider, a as GlobalNotificationProviderProps, N as Notification, b as NotificationSeverity, d as UseAutoGenerateOptions, U as UseAutoGenerateReturn, c as useAutoGenerate, u as useGlobalNotification } from './GlobalNotificationProvider-Zq18OkpI.js';
|
|
@@ -828,6 +828,27 @@ declare const CRITICAL_TRANSLATIONS: {
|
|
|
828
828
|
readonly "resetPassword.title": "Nueva Contraseña";
|
|
829
829
|
readonly "resetPassword.validatingCode": "Validando código...";
|
|
830
830
|
readonly "modules.form.publicPolicies.fields.conditions.customEdit": "Edición personalizada";
|
|
831
|
+
readonly "file.clickToPreview": "Clic para ver imagen";
|
|
832
|
+
readonly "file.clickToDownload": "Clic para descargar";
|
|
833
|
+
readonly "file.privateFile": "Archivo privado";
|
|
834
|
+
readonly "file.noPreview": "Sin vista previa";
|
|
835
|
+
readonly "file.dropHere": "Suelta el archivo aquí";
|
|
836
|
+
readonly "file.dragOrClick": "Arrastra archivos aquí o haz clic para seleccionar";
|
|
837
|
+
readonly "file.uploading": "Subiendo archivos...";
|
|
838
|
+
readonly "file.restore": "Restaurar";
|
|
839
|
+
readonly "file.delete": "Eliminar";
|
|
840
|
+
readonly "file.pendingDeletion": "Pendiente de eliminación";
|
|
841
|
+
readonly "file.allowedTypes": "Tipos permitidos: {{types}}";
|
|
842
|
+
readonly "file.maxSize": "Máximo {{size}} por archivo";
|
|
843
|
+
readonly "file.maxFiles": "Máximo {{count}} archivos";
|
|
844
|
+
readonly "file.validation.minFilesRequired": "Se requiere al menos un archivo";
|
|
845
|
+
readonly "file.validation.minFilesRequiredPlural": "Se requieren al menos {{count}} archivos";
|
|
846
|
+
readonly "file.validation.maxFilesExceeded": "Máximo {{count}} archivos permitidos";
|
|
847
|
+
readonly "file.validation.filesWithErrors": "Algunos archivos tienen errores";
|
|
848
|
+
readonly "file.confirmDelete.title": "Eliminar archivo";
|
|
849
|
+
readonly "file.confirmDelete.message": "¿Estás seguro de que deseas eliminar este archivo? Esta acción no se puede deshacer.";
|
|
850
|
+
readonly "file.confirmDelete.confirm": "Eliminar";
|
|
851
|
+
readonly "file.confirmDelete.cancel": "Cancelar";
|
|
831
852
|
};
|
|
832
853
|
readonly en: {
|
|
833
854
|
readonly "checkCode.codeLabel": "Verification Code";
|
|
@@ -939,6 +960,27 @@ declare const CRITICAL_TRANSLATIONS: {
|
|
|
939
960
|
readonly "resetPassword.title": "New Password";
|
|
940
961
|
readonly "resetPassword.validatingCode": "Validating code...";
|
|
941
962
|
readonly "modules.form.publicPolicies.fields.conditions.customEdit": "Custom Edit";
|
|
963
|
+
readonly "file.clickToPreview": "Click to preview";
|
|
964
|
+
readonly "file.clickToDownload": "Click to download";
|
|
965
|
+
readonly "file.privateFile": "Private file";
|
|
966
|
+
readonly "file.noPreview": "No preview";
|
|
967
|
+
readonly "file.dropHere": "Drop file here";
|
|
968
|
+
readonly "file.dragOrClick": "Drag files here or click to select";
|
|
969
|
+
readonly "file.uploading": "Uploading files...";
|
|
970
|
+
readonly "file.restore": "Restore";
|
|
971
|
+
readonly "file.delete": "Delete";
|
|
972
|
+
readonly "file.pendingDeletion": "Pending deletion";
|
|
973
|
+
readonly "file.allowedTypes": "Allowed types: {{types}}";
|
|
974
|
+
readonly "file.maxSize": "Max {{size}} per file";
|
|
975
|
+
readonly "file.maxFiles": "Max {{count}} files";
|
|
976
|
+
readonly "file.validation.minFilesRequired": "At least one file is required";
|
|
977
|
+
readonly "file.validation.minFilesRequiredPlural": "At least {{count}} files are required";
|
|
978
|
+
readonly "file.validation.maxFilesExceeded": "Maximum {{count}} files allowed";
|
|
979
|
+
readonly "file.validation.filesWithErrors": "Some files have errors";
|
|
980
|
+
readonly "file.confirmDelete.title": "Delete file";
|
|
981
|
+
readonly "file.confirmDelete.message": "Are you sure you want to delete this file? This action cannot be undone.";
|
|
982
|
+
readonly "file.confirmDelete.confirm": "Delete";
|
|
983
|
+
readonly "file.confirmDelete.cancel": "Cancel";
|
|
942
984
|
};
|
|
943
985
|
};
|
|
944
986
|
type CriticalTranslationKey = keyof typeof CRITICAL_TRANSLATIONS.es;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createStarExport(obj) { Object.keys(obj) .filter((key) => key !== "default" && key !== "__esModule") .forEach((key) => { if (exports.hasOwnProperty(key)) { return; } Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]}); }); } 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
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createStarExport(obj) { Object.keys(obj) .filter((key) => key !== "default" && key !== "__esModule") .forEach((key) => { if (exports.hasOwnProperty(key)) { return; } Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]}); }); } 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 _chunkE4ILHUTVjs = require('./chunk-E4ILHUTV.js');var _chunkOTCV6Y6Djs = require('./chunk-OTCV6Y6D.js');var _chunkKCWS6BRDjs = require('./chunk-KCWS6BRD.js');var _chunkARGPCO6Ijs = require('./chunk-ARGPCO6I.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunk34FAL7YWjs = require('./chunk-34FAL7YW.js');var _crudifybrowser = require('@nocios/crudify-browser'); var _crudifybrowser2 = _interopRequireDefault(_crudifybrowser); _createStarExport(_crudifybrowser);var _react = require('react');var _material = require('@mui/material');var _jsxruntime = require('react/jsx-runtime');var Ke=(e={})=>{try{let r=_chunk34FAL7YWjs.b.call(void 0, "theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){_chunk34FAL7YWjs.a.warn("Error parsing theme from cookie",r instanceof Error?{errorMessage:r.message}:{message:String(r)})}return e};function Ve({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=_react.useMemo.call(void 0, ()=>{let s=Ke(r);return _material.createTheme.call(void 0, s)},[r]);return _jsxruntime.jsxs.call(void 0, _material.ThemeProvider,{theme:t,children:[!o&&_jsxruntime.jsx.call(void 0, _material.CssBaseline,{}),e]})}var _reactrouterdom = require('react-router-dom');var He={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},qe=()=>_jsxruntime.jsx.call(void 0, "style",{children:`
|
|
2
2
|
@keyframes spin {
|
|
3
3
|
0% { transform: rotate(0deg); }
|
|
4
4
|
100% { transform: rotate(360deg); }
|
|
5
5
|
}
|
|
6
|
-
`});function T({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, Ye,{}),_jsxruntime.jsxs.call(void 0, "div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[_jsxruntime.jsx.call(void 0, "div",{style:He}),_jsxruntime.jsx.call(void 0, "p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:t})]})]})}var We=/^[a-zA-Z0-9\-_./\?=&%#]+$/,Je=[/^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]/,/\\/],h= exports.validateInternalRedirect =(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return _chunkDJ3T7VVSjs.a.warn("Open redirect blocked (relative path)",{path:e}),r;if(!We.test(o))return _chunkDJ3T7VVSjs.a.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let p of Je)if(p.test(t))return _chunkDJ3T7VVSjs.a.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let s=o.split("?")[0].split("/").filter(Boolean);if(s.length===0)return o;for(let p of s)if(p===".."||p.includes(":")||p.length>100)return _chunkDJ3T7VVSjs.a.warn("Open redirect blocked (suspicious path part)",{part:p}),r;return o},E= exports.extractSafeRedirectFromUrl =(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let s=decodeURIComponent(t);return h(s,r)}catch(o){return _chunkDJ3T7VVSjs.a.warn("Error parsing redirect parameter",o instanceof Error?{errorMessage:o.message}:{message:String(o)}),r}};function L({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:s,isInitialized:p,tokens:l,error:y}=_chunkL7LTBWM5js.j.call(void 0, ),d=_reactrouterdom.useLocation.call(void 0, );if(!p||s)return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:r||_jsxruntime.jsx.call(void 0, T,{stage:"validating-session"})});let u=t&&_optionalChain([l, 'optionalAccess', _2 => _2.accessToken])&&l.accessToken.length>0;if(y||!t||!u){l&&(!l.accessToken||l.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let A=d.pathname+d.search,C=h(A),x=encodeURIComponent(C);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:`${o}?redirect=${x}`,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function F({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=_chunkL7LTBWM5js.j.call(void 0, ),t=_reactrouterdom.useLocation.call(void 0, );if(o){let s=new URLSearchParams(t.search),p=E(s,r);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:p,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}var N=_react.createContext.call(void 0, void 0),tr= exports.CrudifyInitializer =({config:e,children:r,fallback:o=null,onInitialized:t,onError:s})=>{let[p,l]=_react.useState.call(void 0, !1),[y,d]=_react.useState.call(void 0, !1),[u,A]=_react.useState.call(void 0, null),C=_react.useRef.call(void 0, !1),x=_react.useRef.call(void 0, !1);_react.useEffect.call(void 0, ()=>{C.current||(_chunkL7LTBWM5js.o.registerHighPriorityInitializer(),C.current=!0),x.current||(x.current=!0,(async()=>{console.log("[CRUDIFY_DEBUG] CrudifyInitializer.initializeAsync() starting"),console.log("[CRUDIFY_DEBUG] config prop:",e),console.log("[CRUDIFY_DEBUG] document.cookie:",document.cookie),d(!0),A(null);try{let c=_chunkDJ3T7VVSjs.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _3 => _3.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _4 => _4.env]),enableDebug:_optionalChain([e, 'optionalAccess', _5 => _5.enableLogging])});if(console.log("[CRUDIFY_DEBUG] resolvedConfig:",c),!c.publicApiKey)throw console.error("[CRUDIFY_DEBUG] No publicApiKey found in resolvedConfig!"),new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");let R=c.env||"prod";_chunkDJ3T7VVSjs.a.setEnvironment(R),await _chunkL7LTBWM5js.o.initialize({priority:"HIGH",publicApiKey:c.publicApiKey,env:c.env||"prod",enableLogging:_optionalChain([e, 'optionalAccess', _6 => _6.enableLogging]),requestedBy:"CrudifyInitializer"}),l(!0),d(!1),t&&t()}catch(c){let R=c instanceof Error?c:new Error(String(c));A(R),d(!1),s&&s(R)}})())},[_optionalChain([e, 'optionalAccess', _7 => _7.publicApiKey]),_optionalChain([e, 'optionalAccess', _8 => _8.env]),_optionalChain([e, 'optionalAccess', _9 => _9.enableLogging]),t,s]);let _={isInitialized:p,isInitializing:y,error:u};return y&&o?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:o}):(u&&_chunkDJ3T7VVSjs.a.error("[CrudifyInitializer] Initialization failed",u),_jsxruntime.jsx.call(void 0, N.Provider,{value:_,children:r}))},ir= exports.useCrudifyInitializer =()=>{let e=_react.useContext.call(void 0, N);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};var _crudifyadmin = require('@nocios/crudify-admin'); var _crudifyadmin2 = _interopRequireDefault(_crudifyadmin);var G=!1,g=null;async function sr(){let r=_chunkL7LTBWM5js.e.getInstance().getTokenInfo(),o=_optionalChain([r, 'optionalAccess', _10 => _10.apiEndpointAdmin]),t=_optionalChain([r, 'optionalAccess', _11 => _11.apiKeyEndpointAdmin]);return o&&t?{apiUrl:o,apiKey:t}:_chunkL7LTBWM5js.a.waitForCredentials()}async function ar(){if(!G)return g||(g=(async()=>{try{let e=_chunkL7LTBWM5js.e.getInstance(),{apiUrl:r,apiKey:o}=await sr();_crudifyadmin2.default.init({url:r,apiKey:o,getAdditionalHeaders:()=>{let t=e.getTokenInfo();return _optionalChain([t, 'optionalAccess', _12 => _12.crudifyTokens, 'optionalAccess', _13 => _13.accessToken])?{Authorization:`Bearer ${t.crudifyTokens.accessToken}`}:{}}}),G=!0}catch(e){throw g=null,_chunkDJ3T7VVSjs.a.error("[crudifyAdminWrapper] Initialization failed",e instanceof Error?e:{message:String(e)}),e}})(),g)}async function n(e){try{await ar();let r=await e(),o=r.errors&&(typeof r.errors=="string"&&r.errors.includes("401")||Array.isArray(r.errors)&&r.errors.some(t=>typeof t=="string"&&t.includes("401")));return!r.success&&o?await _chunkL7LTBWM5js.e.getInstance().refreshTokens()?await e():(_chunkDJ3T7VVSjs.a.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),r):r}catch(r){return _chunkDJ3T7VVSjs.a.error("[crudifyAdmin] Operation error",r instanceof Error?r:{message:String(r)}),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var pr={listModules:()=>n(()=>_crudifyadmin2.default.listModules()),getModule:e=>n(()=>_crudifyadmin2.default.getModule(e)),createModule:e=>n(()=>_crudifyadmin2.default.createModule(e)),editModule:(e,r)=>n(()=>_crudifyadmin2.default.editModule(e,r)),deleteModule:e=>n(()=>_crudifyadmin2.default.deleteModule(e)),activateModule:e=>n(()=>_crudifyadmin2.default.activateModule(e)),deactivateModule:e=>n(()=>_crudifyadmin2.default.deactivateModule(e)),getModuleVersions:e=>n(()=>_crudifyadmin2.default.getModuleVersions(e)),listActions:e=>n(()=>_crudifyadmin2.default.listActions(e)),getAction:e=>n(()=>_crudifyadmin2.default.getAction(e)),createAction:e=>n(()=>_crudifyadmin2.default.createAction(e)),editAction:(e,r)=>n(()=>_crudifyadmin2.default.editAction(e,r)),deleteAction:e=>n(()=>_crudifyadmin2.default.deleteAction(e)),activateAction:e=>n(()=>_crudifyadmin2.default.activateAction(e)),deactivateAction:e=>n(()=>_crudifyadmin2.default.deactivateAction(e)),getActionVersions:e=>n(()=>_crudifyadmin2.default.getActionVersions(e)),getActionsByProfile:e=>n(()=>_crudifyadmin2.default.getActionsByProfile(e)),updateActionsProfiles:e=>n(()=>_crudifyadmin2.default.updateActionsProfiles(e))};exports.AuthRoute = F; exports.CRITICAL_TRANSLATIONS = _chunkUDDA2MQQjs.a; exports.CrudiaAutoGenerate = _chunkUDDA2MQQjs.o; exports.CrudiaFileField = _chunkUDDA2MQQjs.p; exports.CrudiaMarkdownField = _chunkUDDA2MQQjs.q; exports.CrudifyInitializationManager = _chunkL7LTBWM5js.n; exports.CrudifyInitializer = tr; exports.CrudifyLogin = _chunkUDDA2MQQjs.h; exports.CrudifyProvider = _chunkL7LTBWM5js.b; exports.CrudifyThemeProvider = Ke; exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.GlobalNotificationProvider = _chunkL7LTBWM5js.g; exports.LoginComponent = _chunkUDDA2MQQjs.m; exports.POLICY_ACTIONS = _chunkUDDA2MQQjs.j; exports.PREFERRED_POLICY_ORDER = _chunkUDDA2MQQjs.k; exports.Policies = _chunkUDDA2MQQjs.l; exports.ProtectedRoute = L; exports.SessionDebugInfo = _chunkL7LTBWM5js.k; exports.SessionLoadingScreen = T; exports.SessionManager = _chunkL7LTBWM5js.e; exports.SessionProvider = _chunkL7LTBWM5js.i; exports.SessionStatus = _chunkUDDA2MQQjs.n; exports.TokenStorage = _chunkL7LTBWM5js.d; exports.TranslationService = _chunkUDDA2MQQjs.d; exports.TranslationsProvider = _chunkUDDA2MQQjs.f; exports.UserProfileDisplay = _chunkUDDA2MQQjs.i; exports.createErrorTranslator = _chunkDJ3T7VVSjs.h; exports.crudify = _crudifybrowser2.default; exports.crudifyAdmin = pr; exports.crudifyInitManager = _chunkL7LTBWM5js.o; exports.decodeJwtSafely = _chunkDJ3T7VVSjs.k; exports.extractSafeRedirectFromUrl = E; exports.getCookie = _chunkDJ3T7VVSjs.b; exports.getCriticalLanguages = _chunkUDDA2MQQjs.b; exports.getCriticalTranslations = _chunkUDDA2MQQjs.c; exports.getCurrentUserEmail = _chunkDJ3T7VVSjs.l; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunkDJ3T7VVSjs.m; exports.logger = _chunkDJ3T7VVSjs.a; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.secureLocalStorage = _chunk2M2IM334js.b; exports.secureSessionStorage = _chunk2M2IM334js.a; exports.translateError = _chunkDJ3T7VVSjs.g; exports.translateErrorCode = _chunkDJ3T7VVSjs.e; exports.translateErrorCodes = _chunkDJ3T7VVSjs.f; exports.translationService = _chunkUDDA2MQQjs.e; exports.useAuth = _chunkE342MLZOjs.b; exports.useAutoGenerate = _chunkL7LTBWM5js.m; exports.useCrudify = _chunkL7LTBWM5js.c; exports.useCrudifyInitializer = ir; exports.useCrudifyWithNotifications = _chunkE342MLZOjs.d; exports.useData = _chunkE342MLZOjs.c; exports.useFileUpload = _chunkL7LTBWM5js.p; exports.useGlobalNotification = _chunkL7LTBWM5js.h; exports.useSession = _chunkL7LTBWM5js.f; exports.useSessionContext = _chunkL7LTBWM5js.j; exports.useTranslations = _chunkUDDA2MQQjs.g; exports.useUserData = _chunkE342MLZOjs.a; exports.useUserProfile = _chunkL7LTBWM5js.l; exports.validateInternalRedirect = h;
|
|
6
|
+
`});function T({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, qe,{}),_jsxruntime.jsxs.call(void 0, "div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[_jsxruntime.jsx.call(void 0, "div",{style:He}),_jsxruntime.jsx.call(void 0, "p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:t})]})]})}var Je=/^[a-zA-Z0-9\-_./\?=&%#]+$/,$e=[/^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]/,/\\/],h= exports.validateInternalRedirect =(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return _chunk34FAL7YWjs.a.warn("Open redirect blocked (relative path)",{path:e}),r;if(!Je.test(o))return _chunk34FAL7YWjs.a.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let p of $e)if(p.test(t))return _chunk34FAL7YWjs.a.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let s=o.split("?")[0].split("/").filter(Boolean);if(s.length===0)return o;for(let p of s)if(p===".."||p.includes(":")||p.length>100)return _chunk34FAL7YWjs.a.warn("Open redirect blocked (suspicious path part)",{part:p}),r;return o},E= exports.extractSafeRedirectFromUrl =(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let s=decodeURIComponent(t);return h(s,r)}catch(o){return _chunk34FAL7YWjs.a.warn("Error parsing redirect parameter",o instanceof Error?{errorMessage:o.message}:{message:String(o)}),r}};function w({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:s,isInitialized:p,tokens:d,error:y}=_chunkKCWS6BRDjs.j.call(void 0, ),l=_reactrouterdom.useLocation.call(void 0, );if(!p||s)return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:r||_jsxruntime.jsx.call(void 0, T,{stage:"validating-session"})});let u=t&&_optionalChain([d, 'optionalAccess', _2 => _2.accessToken])&&d.accessToken.length>0;if(y||!t||!u){d&&(!d.accessToken||d.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let A=l.pathname+l.search,x=h(A),C=encodeURIComponent(x);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:`${o}?redirect=${C}`,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}function F({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=_chunkKCWS6BRDjs.j.call(void 0, ),t=_reactrouterdom.useLocation.call(void 0, );if(o){let s=new URLSearchParams(t.search),p=E(s,r);return _jsxruntime.jsx.call(void 0, _reactrouterdom.Navigate,{to:p,replace:!0})}return _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:e})}var D=_react.createContext.call(void 0, void 0),tr= exports.CrudifyInitializer =({config:e,children:r,fallback:o=null,onInitialized:t,onError:s})=>{let[p,d]=_react.useState.call(void 0, !1),[y,l]=_react.useState.call(void 0, !1),[u,A]=_react.useState.call(void 0, null),x=_react.useRef.call(void 0, !1),C=_react.useRef.call(void 0, !1);_react.useEffect.call(void 0, ()=>{x.current||(_chunkKCWS6BRDjs.o.registerHighPriorityInitializer(),x.current=!0),C.current||(C.current=!0,(async()=>{l(!0),A(null);try{let c=_chunk34FAL7YWjs.c.call(void 0, {publicApiKey:_optionalChain([e, 'optionalAccess', _3 => _3.publicApiKey]),env:_optionalChain([e, 'optionalAccess', _4 => _4.env]),enableDebug:_optionalChain([e, 'optionalAccess', _5 => _5.enableLogging])});if(!c.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");let P=c.env||"prod";_chunk34FAL7YWjs.a.setEnvironment(P),await _chunkKCWS6BRDjs.o.initialize({priority:"HIGH",publicApiKey:c.publicApiKey,env:c.env||"prod",enableLogging:_optionalChain([e, 'optionalAccess', _6 => _6.enableLogging]),requestedBy:"CrudifyInitializer"}),d(!0),l(!1),t&&t()}catch(c){let P=c instanceof Error?c:new Error(String(c));A(P),l(!1),s&&s(P)}})())},[_optionalChain([e, 'optionalAccess', _7 => _7.publicApiKey]),_optionalChain([e, 'optionalAccess', _8 => _8.env]),_optionalChain([e, 'optionalAccess', _9 => _9.enableLogging]),t,s]);let K={isInitialized:p,isInitializing:y,error:u};return y&&o?_jsxruntime.jsx.call(void 0, _jsxruntime.Fragment,{children:o}):(u&&_chunk34FAL7YWjs.a.error("[CrudifyInitializer] Initialization failed",u),_jsxruntime.jsx.call(void 0, D.Provider,{value:K,children:r}))},ir= exports.useCrudifyInitializer =()=>{let e=_react.useContext.call(void 0, D);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};var _crudifyadmin = require('@nocios/crudify-admin'); var _crudifyadmin2 = _interopRequireDefault(_crudifyadmin);var G=!1,g=null;async function sr(){let r=_chunkKCWS6BRDjs.e.getInstance().getTokenInfo(),o=_optionalChain([r, 'optionalAccess', _10 => _10.apiEndpointAdmin]),t=_optionalChain([r, 'optionalAccess', _11 => _11.apiKeyEndpointAdmin]);return o&&t?{apiUrl:o,apiKey:t}:_chunkKCWS6BRDjs.a.waitForCredentials()}async function ar(){if(!G)return g||(g=(async()=>{try{let e=_chunkKCWS6BRDjs.e.getInstance(),{apiUrl:r,apiKey:o}=await sr();_crudifyadmin2.default.init({url:r,apiKey:o,getAdditionalHeaders:()=>{let t=e.getTokenInfo();return _optionalChain([t, 'optionalAccess', _12 => _12.crudifyTokens, 'optionalAccess', _13 => _13.accessToken])?{Authorization:`Bearer ${t.crudifyTokens.accessToken}`}:{}}}),G=!0}catch(e){throw g=null,_chunk34FAL7YWjs.a.error("[crudifyAdminWrapper] Initialization failed",e instanceof Error?e:{message:String(e)}),e}})(),g)}async function n(e){try{await ar();let r=await e(),o=r.errors&&(typeof r.errors=="string"&&r.errors.includes("401")||Array.isArray(r.errors)&&r.errors.some(t=>typeof t=="string"&&t.includes("401")));return!r.success&&o?await _chunkKCWS6BRDjs.e.getInstance().refreshTokens()?await e():(_chunk34FAL7YWjs.a.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),r):r}catch(r){return _chunk34FAL7YWjs.a.error("[crudifyAdmin] Operation error",r instanceof Error?r:{message:String(r)}),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var pr={listModules:()=>n(()=>_crudifyadmin2.default.listModules()),getModule:e=>n(()=>_crudifyadmin2.default.getModule(e)),createModule:e=>n(()=>_crudifyadmin2.default.createModule(e)),editModule:(e,r)=>n(()=>_crudifyadmin2.default.editModule(e,r)),deleteModule:e=>n(()=>_crudifyadmin2.default.deleteModule(e)),activateModule:e=>n(()=>_crudifyadmin2.default.activateModule(e)),deactivateModule:e=>n(()=>_crudifyadmin2.default.deactivateModule(e)),getModuleVersions:e=>n(()=>_crudifyadmin2.default.getModuleVersions(e)),listActions:e=>n(()=>_crudifyadmin2.default.listActions(e)),getAction:e=>n(()=>_crudifyadmin2.default.getAction(e)),createAction:e=>n(()=>_crudifyadmin2.default.createAction(e)),editAction:(e,r)=>n(()=>_crudifyadmin2.default.editAction(e,r)),deleteAction:e=>n(()=>_crudifyadmin2.default.deleteAction(e)),activateAction:e=>n(()=>_crudifyadmin2.default.activateAction(e)),deactivateAction:e=>n(()=>_crudifyadmin2.default.deactivateAction(e)),getActionVersions:e=>n(()=>_crudifyadmin2.default.getActionVersions(e)),getActionsByProfile:e=>n(()=>_crudifyadmin2.default.getActionsByProfile(e)),updateActionsProfiles:e=>n(()=>_crudifyadmin2.default.updateActionsProfiles(e))};exports.AuthRoute = F; exports.CRITICAL_TRANSLATIONS = _chunkE4ILHUTVjs.a; exports.CrudiaAutoGenerate = _chunkE4ILHUTVjs.o; exports.CrudiaFileField = _chunkE4ILHUTVjs.p; exports.CrudiaMarkdownField = _chunkE4ILHUTVjs.q; exports.CrudifyInitializationManager = _chunkKCWS6BRDjs.n; exports.CrudifyInitializer = tr; exports.CrudifyLogin = _chunkE4ILHUTVjs.h; exports.CrudifyProvider = _chunkKCWS6BRDjs.b; exports.CrudifyThemeProvider = Ve; exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.GlobalNotificationProvider = _chunkKCWS6BRDjs.g; exports.LoginComponent = _chunkE4ILHUTVjs.m; exports.POLICY_ACTIONS = _chunkE4ILHUTVjs.j; exports.PREFERRED_POLICY_ORDER = _chunkE4ILHUTVjs.k; exports.Policies = _chunkE4ILHUTVjs.l; exports.ProtectedRoute = w; exports.SessionDebugInfo = _chunkKCWS6BRDjs.k; exports.SessionLoadingScreen = T; exports.SessionManager = _chunkKCWS6BRDjs.e; exports.SessionProvider = _chunkKCWS6BRDjs.i; exports.SessionStatus = _chunkE4ILHUTVjs.n; exports.TokenStorage = _chunkKCWS6BRDjs.d; exports.TranslationService = _chunkE4ILHUTVjs.d; exports.TranslationsProvider = _chunkE4ILHUTVjs.f; exports.UserProfileDisplay = _chunkE4ILHUTVjs.i; exports.createErrorTranslator = _chunk34FAL7YWjs.h; exports.crudify = _crudifybrowser2.default; exports.crudifyAdmin = pr; exports.crudifyInitManager = _chunkKCWS6BRDjs.o; exports.decodeJwtSafely = _chunk34FAL7YWjs.k; exports.extractSafeRedirectFromUrl = E; exports.getCookie = _chunk34FAL7YWjs.b; exports.getCriticalLanguages = _chunkE4ILHUTVjs.b; exports.getCriticalTranslations = _chunkE4ILHUTVjs.c; exports.getCurrentUserEmail = _chunk34FAL7YWjs.l; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunk34FAL7YWjs.m; exports.logger = _chunk34FAL7YWjs.a; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.secureLocalStorage = _chunkARGPCO6Ijs.b; exports.secureSessionStorage = _chunkARGPCO6Ijs.a; exports.translateError = _chunk34FAL7YWjs.g; exports.translateErrorCode = _chunk34FAL7YWjs.e; exports.translateErrorCodes = _chunk34FAL7YWjs.f; exports.translationService = _chunkE4ILHUTVjs.e; exports.useAuth = _chunkOTCV6Y6Djs.b; exports.useAutoGenerate = _chunkKCWS6BRDjs.m; exports.useCrudify = _chunkKCWS6BRDjs.c; exports.useCrudifyInitializer = ir; exports.useCrudifyWithNotifications = _chunkOTCV6Y6Djs.d; exports.useData = _chunkOTCV6Y6Djs.c; exports.useFileUpload = _chunkKCWS6BRDjs.p; exports.useGlobalNotification = _chunkKCWS6BRDjs.h; exports.useSession = _chunkKCWS6BRDjs.f; exports.useSessionContext = _chunkKCWS6BRDjs.j; exports.useTranslations = _chunkE4ILHUTVjs.g; exports.useUserData = _chunkOTCV6Y6Djs.a; exports.useUserProfile = _chunkKCWS6BRDjs.l; exports.validateInternalRedirect = h;
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as V,b as _,c as B,d as H,e as q,f as W,g as J,h as ye,i as xe,j as Ce,k as Pe,l as Re,m as Ie,n as he,o as ve,p as Me,q as ze}from"./chunk-HO44TY3Z.mjs";import{a as ke,b as Le,c as be,d as Fe}from"./chunk-QJI47CHZ.mjs";import{a as k,b as $,c as Y,d as Z,e as f,f as re,g as ne,h as se,i as ae,j as m,k as pe,l as Ae,m as Se,n as Te,o as R,p as Ee}from"./chunk-DXIXGRHJ.mjs";import{a as we,b as Ue}from"./chunk-FRHTVRUM.mjs";import{a as ce,b as de,c as le,d as ue,e as fe,f as me,g as ge}from"./chunk-BJ6PIVZR.mjs";import{a,b as v,c as z,e as Q,f as X,g as j,h as ee,k as oe,l as te,m as ie}from"./chunk-SUWV767V.mjs";import{default as Zr}from"@nocios/crudify-browser";export*from"@nocios/crudify-browser";import{useMemo as Oe}from"react";import{ThemeProvider as Ne,createTheme as De,CssBaseline as Ge}from"@mui/material";import{jsx as _e,jsxs as Be}from"react/jsx-runtime";var Ke=(e={})=>{try{let r=v("theme");if(r){let o=JSON.parse(decodeURIComponent(r));return{...e,...o}}}catch(r){a.warn("Error parsing theme from cookie",r instanceof Error?{errorMessage:r.message}:{message:String(r)})}return e};function Ve({children:e,defaultTheme:r={},disableCssBaseline:o=!1}){let t=Oe(()=>{let s=Ke(r);return De(s)},[r]);return Be(Ne,{theme:t,children:[!o&&_e(Ge,{}),e]})}import{Navigate as Ye,useLocation as Ze}from"react-router-dom";import{Fragment as We,jsx as I,jsxs as L}from"react/jsx-runtime";var He={border:"5px solid rgba(0, 0, 0, 0.1)",borderTopColor:"#3B82F6",borderRadius:"50%",width:"50px",height:"50px",animation:"spin 1s linear infinite"},qe=()=>I("style",{children:`
|
|
2
2
|
@keyframes spin {
|
|
3
3
|
0% { transform: rotate(0deg); }
|
|
4
4
|
100% { transform: rotate(360deg); }
|
|
5
5
|
}
|
|
6
|
-
`});function T({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return
|
|
6
|
+
`});function T({stage:e="loading",message:r}){let t=r||{initializing:"Initializing application...","validating-session":"Validating session...",loading:"Loading..."}[e];return L(We,{children:[I(qe,{}),L("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",backgroundColor:"#f0f2f5",fontFamily:'"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',color:"#333",textAlign:"center",boxSizing:"border-box",padding:"20px",background:"#fff"},children:[I("div",{style:He}),I("p",{style:{fontSize:"1.25em",fontWeight:"500",marginTop:"24px",color:"#1f2937"},children:t})]})]})}var Je=/^[a-zA-Z0-9\-_./\?=&%#]+$/,$e=[/^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]/,/\\/],h=(e,r="/")=>{if(!e||typeof e!="string")return r;let o=e.trim();if(!o)return r;if(!o.startsWith("/"))return a.warn("Open redirect blocked (relative path)",{path:e}),r;if(!Je.test(o))return a.warn("Open redirect blocked (invalid characters)",{path:e}),r;let t=o.toLowerCase();for(let p of $e)if(p.test(t))return a.warn("Open redirect blocked (dangerous pattern)",{path:e}),r;let s=o.split("?")[0].split("/").filter(Boolean);if(s.length===0)return o;for(let p of s)if(p===".."||p.includes(":")||p.length>100)return a.warn("Open redirect blocked (suspicious path part)",{part:p}),r;return o},E=(e,r="/")=>{try{let t=(typeof e=="string"?new URLSearchParams(e):e).get("redirect");if(!t)return r;let s=decodeURIComponent(t);return h(s,r)}catch(o){return a.warn("Error parsing redirect parameter",o instanceof Error?{errorMessage:o.message}:{message:String(o)}),r}};import{Fragment as b,jsx as S}from"react/jsx-runtime";function w({children:e,loadingComponent:r,loginPath:o="/login"}){let{isAuthenticated:t,isLoading:s,isInitialized:p,tokens:d,error:y}=m(),l=Ze();if(!p||s)return S(b,{children:r||S(T,{stage:"validating-session"})});let u=t&&d?.accessToken&&d.accessToken.length>0;if(y||!t||!u){d&&(!d.accessToken||d.accessToken.length===0)&&localStorage.removeItem("crudify_tokens");let A=l.pathname+l.search,x=h(A),C=encodeURIComponent(x);return S(Ye,{to:`${o}?redirect=${C}`,replace:!0})}return S(b,{children:e})}import{Navigate as Qe,useLocation as Xe}from"react-router-dom";import{Fragment as je,jsx as U}from"react/jsx-runtime";function F({children:e,redirectTo:r="/"}){let{isAuthenticated:o}=m(),t=Xe();if(o){let s=new URLSearchParams(t.search),p=E(s,r);return U(Qe,{to:p,replace:!0})}return U(je,{children:e})}import{createContext as er,useContext as rr,useEffect as or,useRef as O,useState as M}from"react";import{Fragment as nr,jsx as N}from"react/jsx-runtime";var D=er(void 0),tr=({config:e,children:r,fallback:o=null,onInitialized:t,onError:s})=>{let[p,d]=M(!1),[y,l]=M(!1),[u,A]=M(null),x=O(!1),C=O(!1);or(()=>{x.current||(R.registerHighPriorityInitializer(),x.current=!0),C.current||(C.current=!0,(async()=>{l(!0),A(null);try{let c=z({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:e?.enableLogging});if(!c.publicApiKey)throw new Error("Crudify configuration missing. Please provide publicApiKey via props or ensure cookies are set by Lambda.");let P=c.env||"prod";a.setEnvironment(P),await R.initialize({priority:"HIGH",publicApiKey:c.publicApiKey,env:c.env||"prod",enableLogging:e?.enableLogging,requestedBy:"CrudifyInitializer"}),d(!0),l(!1),t&&t()}catch(c){let P=c instanceof Error?c:new Error(String(c));A(P),l(!1),s&&s(P)}})())},[e?.publicApiKey,e?.env,e?.enableLogging,t,s]);let K={isInitialized:p,isInitializing:y,error:u};return y&&o?N(nr,{children:o}):(u&&a.error("[CrudifyInitializer] Initialization failed",u),N(D.Provider,{value:K,children:r}))},ir=()=>{let e=rr(D);if(!e)throw new Error("useCrudifyInitializer must be used within CrudifyInitializer");return e};import i from"@nocios/crudify-admin";var G=!1,g=null;async function sr(){let r=f.getInstance().getTokenInfo(),o=r?.apiEndpointAdmin,t=r?.apiKeyEndpointAdmin;return o&&t?{apiUrl:o,apiKey:t}:k.waitForCredentials()}async function ar(){if(!G)return g||(g=(async()=>{try{let e=f.getInstance(),{apiUrl:r,apiKey:o}=await sr();i.init({url:r,apiKey:o,getAdditionalHeaders:()=>{let t=e.getTokenInfo();return t?.crudifyTokens?.accessToken?{Authorization:`Bearer ${t.crudifyTokens.accessToken}`}:{}}}),G=!0}catch(e){throw g=null,a.error("[crudifyAdminWrapper] Initialization failed",e instanceof Error?e:{message:String(e)}),e}})(),g)}async function n(e){try{await ar();let r=await e(),o=r.errors&&(typeof r.errors=="string"&&r.errors.includes("401")||Array.isArray(r.errors)&&r.errors.some(t=>typeof t=="string"&&t.includes("401")));return!r.success&&o?await f.getInstance().refreshTokens()?await e():(a.error("[crudifyAdmin] Token refresh failed"),typeof window<"u"&&(window.location.href="/login"),r):r}catch(r){return a.error("[crudifyAdmin] Operation error",r instanceof Error?r:{message:String(r)}),{success:!1,errors:r instanceof Error?r.message:"Unknown error"}}}var pr={listModules:()=>n(()=>i.listModules()),getModule:e=>n(()=>i.getModule(e)),createModule:e=>n(()=>i.createModule(e)),editModule:(e,r)=>n(()=>i.editModule(e,r)),deleteModule:e=>n(()=>i.deleteModule(e)),activateModule:e=>n(()=>i.activateModule(e)),deactivateModule:e=>n(()=>i.deactivateModule(e)),getModuleVersions:e=>n(()=>i.getModuleVersions(e)),listActions:e=>n(()=>i.listActions(e)),getAction:e=>n(()=>i.getAction(e)),createAction:e=>n(()=>i.createAction(e)),editAction:(e,r)=>n(()=>i.editAction(e,r)),deleteAction:e=>n(()=>i.deleteAction(e)),activateAction:e=>n(()=>i.activateAction(e)),deactivateAction:e=>n(()=>i.deactivateAction(e)),getActionVersions:e=>n(()=>i.getActionVersions(e)),getActionsByProfile:e=>n(()=>i.getActionsByProfile(e)),updateActionsProfiles:e=>n(()=>i.updateActionsProfiles(e))};export{F as AuthRoute,V as CRITICAL_TRANSLATIONS,ve as CrudiaAutoGenerate,Me as CrudiaFileField,ze as CrudiaMarkdownField,Te as CrudifyInitializationManager,tr as CrudifyInitializer,ye as CrudifyLogin,$ as CrudifyProvider,Ve as CrudifyThemeProvider,ce as ERROR_CODES,de as ERROR_SEVERITY_MAP,ne as GlobalNotificationProvider,Ie as LoginComponent,Ce as POLICY_ACTIONS,Pe as PREFERRED_POLICY_ORDER,Re as Policies,w as ProtectedRoute,pe as SessionDebugInfo,T as SessionLoadingScreen,f as SessionManager,ae as SessionProvider,he as SessionStatus,Z as TokenStorage,H as TranslationService,W as TranslationsProvider,xe as UserProfileDisplay,ee as createErrorTranslator,Zr as crudify,pr as crudifyAdmin,R as crudifyInitManager,oe as decodeJwtSafely,E as extractSafeRedirectFromUrl,v as getCookie,_ as getCriticalLanguages,B as getCriticalTranslations,te as getCurrentUserEmail,fe as getErrorMessage,ge as handleCrudifyError,ie as isTokenExpired,a as logger,le as parseApiError,me as parseJavaScriptError,ue as parseTransactionError,Ue as secureLocalStorage,we as secureSessionStorage,j as translateError,Q as translateErrorCode,X as translateErrorCodes,q as translationService,Le as useAuth,Se as useAutoGenerate,Y as useCrudify,ir as useCrudifyInitializer,Fe as useCrudifyWithNotifications,be as useData,Ee as useFileUpload,se as useGlobalNotification,re as useSession,m as useSessionContext,J as useTranslations,ke as useUserData,Ae as useUserProfile,h as validateInternalRedirect};
|
package/dist/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkARGPCO6Ijs = require('./chunk-ARGPCO6I.js');var _chunkYIIUEOXCjs = require('./chunk-YIIUEOXC.js');var _chunk34FAL7YWjs = require('./chunk-34FAL7YW.js');exports.ERROR_CODES = _chunkYIIUEOXCjs.a; exports.ERROR_SEVERITY_MAP = _chunkYIIUEOXCjs.b; exports.NavigationTracker = _chunk34FAL7YWjs.j; exports.authEventBus = _chunk34FAL7YWjs.i; exports.createErrorTranslator = _chunk34FAL7YWjs.h; exports.decodeJwtSafely = _chunk34FAL7YWjs.k; exports.getCookie = _chunk34FAL7YWjs.b; exports.getCurrentUserEmail = _chunk34FAL7YWjs.l; exports.getErrorMessage = _chunkYIIUEOXCjs.e; exports.handleCrudifyError = _chunkYIIUEOXCjs.g; exports.isTokenExpired = _chunk34FAL7YWjs.m; exports.parseApiError = _chunkYIIUEOXCjs.c; exports.parseJavaScriptError = _chunkYIIUEOXCjs.f; exports.parseTransactionError = _chunkYIIUEOXCjs.d; exports.resolveConfig = _chunk34FAL7YWjs.c; exports.secureLocalStorage = _chunkARGPCO6Ijs.b; exports.secureSessionStorage = _chunkARGPCO6Ijs.a; exports.translateError = _chunk34FAL7YWjs.g; exports.translateErrorCode = _chunk34FAL7YWjs.e; exports.translateErrorCodes = _chunk34FAL7YWjs.f; exports.useResolvedConfig = _chunk34FAL7YWjs.d;
|
package/dist/utils.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as R,b as c}from"./chunk-
|
|
1
|
+
import{a as R,b as c}from"./chunk-FRHTVRUM.mjs";import{a as m,b as v,c as d,d as g,e as u,f as x,g as C}from"./chunk-BJ6PIVZR.mjs";import{b as r,c as e,d as o,e as t,f as a,g as n,h as s,i as E,j as i,k as p,l as f,m as l}from"./chunk-SUWV767V.mjs";export{m as ERROR_CODES,v as ERROR_SEVERITY_MAP,i as NavigationTracker,E as authEventBus,s as createErrorTranslator,p as decodeJwtSafely,r as getCookie,f as getCurrentUserEmail,u as getErrorMessage,C as handleCrudifyError,l as isTokenExpired,d as parseApiError,x as parseJavaScriptError,g as parseTransactionError,e as resolveConfig,c as secureLocalStorage,R as secureSessionStorage,n as translateError,t as translateErrorCode,a as translateErrorCodes,o as useResolvedConfig};
|
package/package.json
CHANGED
package/dist/chunk-7DIOFA73.mjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{a as g,c as ue,e as Ee,i as Y,j as Te,k as ve,l as Ie}from"./chunk-HQKET2ZX.mjs";import{createContext as Ye,useContext as Me,useEffect as Be,useState as q}from"react";import j from"@nocios/crudify-browser";var de=class n{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return n.instance||(n.instance=new n),n.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){g.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=de.getInstance();import{jsx as Ve}from"react/jsx-runtime";var Ae=Ye(void 0),ke=({config:n,children:i})=>{let[e,t]=q(!0),[r,s]=q(null),[f,m]=q(!1),[x,v]=q(""),[T,b]=q();Be(()=>{if(!n.publicApiKey){s("No publicApiKey provided"),t(!1),m(!1);return}let a=`${n.publicApiKey}-${n.env}`;if(a===x&&f){t(!1);return}(async()=>{t(!0),s(null),m(!1);try{j.config(n.env||"prod");let l=await j.init(n.publicApiKey,"none");if(b(l),typeof j.transaction=="function"&&typeof j.login=="function")m(!0),v(a),l.apiEndpointAdmin&&l.apiKeyEndpointAdmin&&J.notifyCredentialsReady({apiUrl:l.apiEndpointAdmin,apiKey:l.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(l){let p=l instanceof Error?l.message:"Failed to initialize Crudify";g.error("[CrudifyProvider] Initialization error",l instanceof Error?l:{message:String(l)}),s(p),m(!1)}finally{t(!1)}})()},[n.publicApiKey,n.env,x,f]);let c={crudify:f?j:null,isLoading:e,error:r,isInitialized:f,adminCredentials:T};return Ve(Ae.Provider,{value:c,children:i})},be=()=>{let n=Me(Ae);if(n===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return n};import Q from"crypto-js";var d=class d{static setStorageType(i){d.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 Q.SHA256(i).toString()}static getEncryptionKey(){if(d.encryptionKey)return d.encryptionKey;let i=window.localStorage;if(!i)return d.encryptionKey=d.generateEncryptionKey(),d.encryptionKey;try{let e=i.getItem(d.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=d.generateEncryptionKey(),i.setItem(d.ENCRYPTION_KEY_STORAGE,e)),d.encryptionKey=e,e}catch{return g.warn("Crudify: Cannot persist encryption key, using temporary key"),d.encryptionKey=d.generateEncryptionKey(),d.encryptionKey}}static isStorageAvailable(i){try{let e=window[i],t="__storage_test__";return e.setItem(t,"test"),e.removeItem(t),!0}catch{return!1}}static getStorage(){return d.storageType==="none"?null:d.isStorageAvailable(d.storageType)?window[d.storageType]:(g.warn(`Crudify: ${d.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=d.getEncryptionKey();return Q.AES.encrypt(i,e).toString()}catch(e){return g.error("Crudify: Encryption failed",e instanceof Error?e:{message:String(e)}),i}}static decrypt(i){try{let e=d.getEncryptionKey();return Q.AES.decrypt(i,e).toString(Q.enc.Utf8)||i}catch(e){return g.error("Crudify: Decryption failed",e instanceof Error?e:{message:String(e)}),i}}static saveTokens(i){let e=d.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},r=d.encrypt(JSON.stringify(t));e.setItem(d.TOKEN_KEY,r),g.debug("Crudify: Tokens saved successfully")}catch(t){g.error("Crudify: Failed to save tokens",t instanceof Error?t:{message:String(t)})}}static getTokens(){let i=d.getStorage();if(!i)return null;try{let e=i.getItem(d.TOKEN_KEY);if(!e)return null;let t=d.decrypt(e),r=JSON.parse(t);return!r.accessToken||!r.refreshToken||!r.expiresAt||!r.refreshExpiresAt?(g.warn("Crudify: Incomplete token data found, clearing storage"),d.clearTokens(),null):Date.now()>=r.refreshExpiresAt?(g.info("Crudify: Refresh token expired, clearing storage"),d.clearTokens(),null):{accessToken:r.accessToken,refreshToken:r.refreshToken,expiresAt:r.expiresAt,refreshExpiresAt:r.refreshExpiresAt}}catch(e){return g.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),d.clearTokens(),null}}static clearTokens(){let i=d.getStorage();if(i)try{i.removeItem(d.TOKEN_KEY),g.debug("Crudify: Tokens cleared from storage")}catch(e){g.error("Crudify: Failed to clear tokens",e instanceof Error?e:{message:String(e)})}}static rotateEncryptionKey(){try{d.clearTokens(),d.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(d.ENCRYPTION_KEY_STORAGE),g.info("Crudify: Encryption key rotated successfully")}catch(i){g.error("Crudify: Failed to rotate encryption key",i instanceof Error?i:{message:String(i)})}}static hasValidTokens(){return d.getTokens()!==null}static getExpirationInfo(){let i=d.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=d.getTokens();if(!t){g.warn("Crudify: Cannot update access token, no existing tokens found");return}d.saveTokens({...t,accessToken:i,expiresAt:e})}static createSyncEvent(i,e,t){return{type:i,tokens:e,hadPreviousTokens:t}}static subscribeToChanges(i){let e=t=>{if(t.key!==d.TOKEN_KEY)return;let r=t.oldValue!==null&&t.oldValue!=="";if(console.log("[CRUDIFY_DEBUG] TokenStorage.subscribeToChanges received event:",{key:t.key,hadOldValue:!!t.oldValue,hasNewValue:!!t.newValue,hadPreviousTokens:r}),t.newValue===null){g.debug("Crudify: Tokens removed in another tab"),i(null,d.SYNC_EVENTS.TOKENS_CLEARED,r);return}if(t.newValue){g.debug("Crudify: Tokens updated in another tab");let s=d.getTokens();i(s,d.SYNC_EVENTS.TOKENS_UPDATED,r)}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};d.TOKEN_KEY="crudify_tokens",d.ENCRYPTION_KEY_STORAGE="crudify_enc_key",d.encryptionKey=null,d.storageType="localStorage",d.SYNC_EVENTS={TOKENS_CLEARED:"TOKENS_CLEARED",TOKENS_UPDATED:"TOKENS_UPDATED"};var E=d;import N from"@nocios/crudify-browser";var ee=class n{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return n.instance||(n.instance=new n),n.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),E.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")),N.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),Y.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=E.getTokens();e?E.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):E.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 N.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let r=E.getTokens(),s=t.data,f={accessToken:s.token,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt,apiEndpointAdmin:r?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:r?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return E.saveTokens(f),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(f),{success:!0,tokens:f,data:s}}catch(t){return g.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 N.logout(),E.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),E.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=E.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"),E.clearTokens(),!1;if(N.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),N.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 r=E.getTokens();return r&&this.config.onSessionRestored?.(r),!0}return E.clearTokens(),await N.logout(),!1}return this.log("Session restored successfully"),this.lastActivityTime=Date.now(),this.config.onSessionRestored?.(i),!0}catch(i){return this.log("Session restore error:",i),E.clearTokens(),await N.logout(),!1}}isAuthenticated(){return N.isLogin()||E.hasValidTokens()}getTokenInfo(){let i=N.getTokenData(),e=E.getExpirationInfo(),t=E.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:E.hasValidTokens(),apiEndpointAdmin:t?.apiEndpointAdmin,apiKeyEndpointAdmin:t?.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 N.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),E.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1;let e=i.data,t={accessToken:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,refreshExpiresAt:e.refreshExpiresAt};return E.saveTokens(t),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),E.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){N.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"),Y.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(E.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),Y.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"),Y.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=N.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),N.config(e);let t=this.config.publicApiKey,r=this.config.enableLogging?"debug":"none";console.log("[CRUDIFY_DEBUG] Calling crudify.init() with apiKey:",t?.substring(0,8)+"...","logLevel:",r);let s=await N.init(t,r);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),g.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(r=>r.errorType==="Unauthorized"||r.message?.includes("Unauthorized")||r.message?.includes("Not Authorized")||r.message?.includes("NOT_AUTHORIZED")||r.message?.includes("Token")||r.message?.includes("TOKEN")||r.message?.includes("Authentication")||r.message?.includes("UNAUTHENTICATED")||r.extensions?.code==="UNAUTHENTICATED"||r.extensions?.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.",(t.message?.includes("TOKEN")||t.message?.includes("Token"))&&(e.isTokenExpired=!0),t.extensions?.code==="UNAUTHENTICATED"&&(e.isUnauthorized=!0))}if(!e.isAuthError&&i.errors&&typeof i.errors=="object"&&!Array.isArray(i.errors)){let r=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")));r&&typeof r=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,r.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."):r.includes("TOKEN_HAS_EXPIRED")||r.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):r.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&&i.data?.response?.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&&i.data?.response?.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{}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(){E.clearTokens(),N.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?Ee("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"}};import{useState as $e,useEffect as ie,useCallback as V}from"react";function Se(n={}){let[i,e]=$e({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=c=>{e(a=>{let o=typeof c=="function"?c(a):c;return o.error!==a.error&&console.log("[CRUDIFY_DEBUG] \u{1F534} STATE ERROR CHANGED:",{from:a.error,to:o.error,stack:new Error().stack?.split(`
|
|
2
|
-
`).slice(2,6).join(`
|
|
3
|
-
`)}),o.isAuthenticated!==a.isAuthenticated&&console.log("[CRUDIFY_DEBUG] \u{1F535} AUTH STATE CHANGED:",{from:a.isAuthenticated,to:o.isAuthenticated}),o})},r=ee.getInstance(),s=V(async()=>{console.log("[CRUDIFY_DEBUG] useSession.initialize() called");try{t(l=>({...l,isLoading:!0,error:null}));let c={autoRestore:n.autoRestore??!0,enableLogging:n.enableLogging??!1,showNotification:n.showNotification,translateFn:n.translateFn,apiEndpointAdmin:n.apiEndpointAdmin,apiKeyEndpointAdmin:n.apiKeyEndpointAdmin,publicApiKey:n.publicApiKey,env:n.env||"stg",onSessionExpired:()=>{console.log("[CRUDIFY_DEBUG] onSessionExpired callback triggered"),t(l=>({...l,isAuthenticated:!1,tokens:null,error:"Session expired"})),n.onSessionExpired?.()},onSessionRestored:l=>{console.log("[CRUDIFY_DEBUG] onSessionRestored callback triggered"),t(p=>({...p,isAuthenticated:!0,tokens:l,error:null})),n.onSessionRestored?.(l)},onLoginSuccess:l=>{console.log("[CRUDIFY_DEBUG] onLoginSuccess callback triggered"),t(p=>({...p,isAuthenticated:!0,tokens:l,error:null}))},onLogout:()=>{console.log("[CRUDIFY_DEBUG] onLogout callback triggered"),t(l=>({...l,isAuthenticated:!1,tokens:null,error:null}))}};console.log("[CRUDIFY_DEBUG] About to call sessionManager.initialize()"),await r.initialize(c),console.log("[CRUDIFY_DEBUG] sessionManager.initialize() completed"),r.setupResponseInterceptor(),console.log("[CRUDIFY_DEBUG] Response interceptor configured");let a=r.isAuthenticated(),o=r.getTokenInfo();console.log("[CRUDIFY_DEBUG] isAuth:",a,"hasAccessToken:",!!o.crudifyTokens.accessToken),t(l=>({...l,isAuthenticated:a,isInitialized:!0,isLoading:!1,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null})),console.log("[CRUDIFY_DEBUG] Initialize completed successfully")}catch(c){let a=c instanceof Error?c.message:"Initialization failed";console.error("[CRUDIFY_DEBUG] Initialize FAILED with error:",a,c),t(o=>({...o,isLoading:!1,isInitialized:!0,error:a}))}},[n.autoRestore,n.enableLogging,n.onSessionExpired,n.onSessionRestored]),f=V(async(c,a)=>{console.log("[CRUDIFY_DEBUG] login() called with email:",c),t(o=>({...o,isLoading:!0,error:null}));try{console.log("[CRUDIFY_DEBUG] Calling sessionManager.login()");let o=await r.login(c,a);return console.log("[CRUDIFY_DEBUG] sessionManager.login() result:",{success:o.success,hasTokens:!!o.tokens,error:o.error}),o.success&&o.tokens?(console.log("[CRUDIFY_DEBUG] Login SUCCESS, updating state with tokens"),t(l=>({...l,isAuthenticated:!0,tokens:o.tokens,isLoading:!1,error:null})),console.log("[CRUDIFY_DEBUG] State updated after successful login")):(console.log("[CRUDIFY_DEBUG] Login FAILED (no tokens), error:",o.error),t(l=>({...l,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))),o}catch(o){let l=o instanceof Error?o.message:"Login failed";console.error("[CRUDIFY_DEBUG] login() CAUGHT EXCEPTION:",l,o);let p=l.includes("INVALID_CREDENTIALS")||l.includes("Invalid email")||l.includes("Invalid password")||l.includes("credentials");return console.log("[CRUDIFY_DEBUG] isCredentialError:",p,"- will set global error:",!p),t(I=>({...I,isAuthenticated:!1,tokens:null,isLoading:!1,error:p?null:l})),{success:!1,error:l}}},[r]),m=V(async()=>{console.log("[CRUDIFY_DEBUG] logout() called"),t(c=>({...c,isLoading:!0}));try{await r.logout(),t(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){t(a=>({...a,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[r]),x=V(async()=>{console.log("[CRUDIFY_DEBUG] refreshTokens() called");try{let c=await r.refreshTokens();if(c){let a=r.getTokenInfo();t(o=>({...o,tokens:a.crudifyTokens.accessToken?{accessToken:a.crudifyTokens.accessToken,refreshToken:a.crudifyTokens.refreshToken,expiresAt:a.crudifyTokens.expiresAt,refreshExpiresAt:a.crudifyTokens.refreshExpiresAt}:null,error:null}))}else t(a=>({...a,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return t(a=>({...a,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[r]),v=V(()=>{console.log("[CRUDIFY_DEBUG] clearError() called"),t(c=>({...c,error:null}))},[]),T=V(()=>r.getTokenInfo(),[r]);ie(()=>{s()},[s]),ie(()=>{if(!i.isAuthenticated||!i.tokens)return;let c=Te.getInstance(),a=()=>{r.updateLastActivity()},o=c.subscribe(a);window.addEventListener("popstate",a);let l=()=>{let S=r.getTokenInfo().crudifyTokens.expiresIn||0;return S<300*1e3?30*1e3:S<1800*1e3?60*1e3:120*1e3},p,I=()=>{let z=l();p=setTimeout(async()=>{if(r.isRefreshing()){I();return}let S=r.getTokenInfo(),R=S.crudifyTokens.expiresIn||0,k=((S.crudifyTokens.expiresAt||0)-(Date.now()-R))*.5;if(R>0&&R<=k)if(console.log("[CRUDIFY_DEBUG] Token renewal triggered (TTL threshold)"),t(K=>({...K,isLoading:!0})),await r.refreshTokens()){let K=r.getTokenInfo();t(le=>({...le,isLoading:!1,tokens:K.crudifyTokens.accessToken?{accessToken:K.crudifyTokens.accessToken,refreshToken:K.crudifyTokens.refreshToken,expiresAt:K.crudifyTokens.expiresAt,refreshExpiresAt:K.crudifyTokens.refreshExpiresAt}:null}))}else t(K=>({...K,isLoading:!1,isAuthenticated:!1,tokens:null}));let W=r.getTimeSinceLastActivity(),M=1800*1e3;W>M?await m():I()},z)};return I(),()=>{clearTimeout(p),window.removeEventListener("popstate",a),o()}},[i.isAuthenticated,i.tokens,r,n.enableLogging,m]),ie(()=>{let c=Y.subscribe(async a=>{if(a.type==="TOKEN_EXPIRED"){if(console.log("[CRUDIFY_DEBUG] authEventBus received TOKEN_EXPIRED event"),r.isRefreshing()){console.log("[CRUDIFY_DEBUG] Refresh already in progress, ignoring TOKEN_EXPIRED");return}t(o=>({...o,isLoading:!0}));try{if(await r.refreshTokens()){let l=r.getTokenInfo();t(p=>({...p,isLoading:!1,tokens:l.crudifyTokens.accessToken?{accessToken:l.crudifyTokens.accessToken,refreshToken:l.crudifyTokens.refreshToken,expiresAt:l.crudifyTokens.expiresAt,refreshExpiresAt:l.crudifyTokens.refreshExpiresAt}:null}))}else Y.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(o){Y.emit("SESSION_EXPIRED",{message:o instanceof Error?o.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(a.type==="SESSION_EXPIRED"||a.type==="TOKEN_REFRESH_FAILED")&&(console.log("[CRUDIFY_DEBUG] authEventBus received",a.type,"event:",a.details),t(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:a.details?.message||"Session expired"})),n.onSessionExpired?.())});return()=>c()},[n.onSessionExpired,r]),ie(()=>{let c=E.subscribeToChanges((a,o,l)=>{console.log("[CRUDIFY_DEBUG] Cross-tab storage change detected:",{eventType:o,hasTokens:!!a,hadPreviousTokens:l,currentStateIsAuthenticated:i.isAuthenticated}),o===E.SYNC_EVENTS.TOKENS_CLEARED?l&&i.isAuthenticated?(console.log("[CRUDIFY_DEBUG] Cross-tab: Logout detected, user was authenticated"),t(p=>({...p,isAuthenticated:!1,tokens:null})),n.onSessionExpired?.()):l?(console.log("[CRUDIFY_DEBUG] Cross-tab: Tokens cleared, syncing state silently"),t(p=>({...p,isAuthenticated:!1,tokens:null}))):console.log("[CRUDIFY_DEBUG] Cross-tab: Tokens cleared but there were no previous tokens, ignoring"):o===E.SYNC_EVENTS.TOKENS_UPDATED&&a&&(console.log("[CRUDIFY_DEBUG] Cross-tab: Tokens updated, syncing to authenticated state"),t(p=>({...p,tokens:a,isAuthenticated:!0,error:null})))});return()=>c()},[i.isAuthenticated,n.onSessionExpired]);let b=V(()=>{r.updateLastActivity()},[r]);return{...i,login:f,logout:m,refreshTokens:x,clearError:v,getTokenInfo:T,updateActivity:b,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}}import{useState as De,createContext as Xe,useContext as We,useCallback as te,useEffect as Ze}from"react";import{Snackbar as qe,Alert as je,Box as Je,Portal as Qe}from"@mui/material";import{v4 as ei}from"uuid";import ii from"dompurify";import{jsx as $,jsxs as ni}from"react/jsx-runtime";var xe=Xe(null),ti=n=>ii.sanitize(n,{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}),fe=({children:n,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:r=!1,allowHtml:s=!1})=>{let[f,m]=De([]),x=te((c,a="info",o)=>{if(!r)return"";if(!c||typeof c!="string")return g.warn("GlobalNotificationProvider: Invalid message provided"),"";c.length>1e3&&(g.warn("GlobalNotificationProvider: Message too long, truncating"),c=c.substring(0,1e3)+"...");let l=ei(),p={id:l,message:c,severity:a,autoHideDuration:o?.autoHideDuration??e,persistent:o?.persistent??!1,allowHtml:o?.allowHtml??s};return m(I=>[...I.length>=i?I.slice(-(i-1)):I,p]),l},[i,e,r,s]),v=te(c=>{m(a=>a.filter(o=>o.id!==c))},[]),T=te(()=>{m([])},[]),b={showNotification:x,hideNotification:v,clearAllNotifications:T};return ni(xe.Provider,{value:b,children:[n,r&&$(Qe,{children:$(Je,{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:f.map(c=>$(ri,{notification:c,onClose:()=>v(c.id)},c.id))})})]})},ri=({notification:n,onClose:i})=>{let[e,t]=De(!0),r=te((s,f)=>{f!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return Ze(()=>{if(!n.persistent&&n.autoHideDuration){let s=setTimeout(()=>{r()},n.autoHideDuration);return()=>clearTimeout(s)}},[n.autoHideDuration,n.persistent,r]),$(qe,{open:e,onClose:r,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:$(je,{variant:"filled",severity:n.severity,onClose:r,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:n.allowHtml?$("span",{dangerouslySetInnerHTML:{__html:ti(n.message)}}):$("span",{children:n.message})})})},Re=()=>{let n=We(xe);if(!n)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return n};import oi,{createContext as si,useContext as ai,useMemo as ge}from"react";import{Fragment as ci,jsx as w,jsxs as G}from"react/jsx-runtime";var we=si(void 0);function Ce({children:n,options:i={},config:e,showNotifications:t=!1,notificationOptions:r={}}){let s;try{let{showNotification:o}=Re();s=o}catch{}let f={};try{let o=be();o.isInitialized&&o.adminCredentials&&(f=o.adminCredentials)}catch{}let m=ge(()=>{let o=ue({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:i?.enableLogging});return{publicApiKey:o.publicApiKey,env:o.env||"prod"}},[e,i?.enableLogging]),x=oi.useMemo(()=>({...i,showNotification:s,apiEndpointAdmin:f.apiEndpointAdmin,apiKeyEndpointAdmin:f.apiKeyEndpointAdmin,publicApiKey:m.publicApiKey,env:m.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,s,f.apiEndpointAdmin,f.apiKeyEndpointAdmin,m]),v=Se(x),T=ge(()=>{let o=ue({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:i?.enableLogging});return{publicApiKey:o.publicApiKey,env:o.env,appName:o.appName,loginActions:o.loginActions,logo:o.logo}},[e,i?.enableLogging]),b=ge(()=>{if(!v.tokens?.accessToken||!v.isAuthenticated)return null;try{let o=ve(v.tokens.accessToken);if(o&&o.sub&&o.email&&o.subscriber){let l={_id:o.sub,email:o.email,subscriberKey:o.subscriber};return Object.keys(o).forEach(p=>{["sub","email","subscriber"].includes(p)||(l[p]=o[p])}),l}}catch(o){g.error("Error decoding JWT token for sessionData",o instanceof Error?o:{message:String(o)})}return null},[v.tokens?.accessToken,v.isAuthenticated]),c={...v,sessionData:b,config:T};v.error&&console.log("[CRUDIFY_DEBUG] SessionProvider contextValue.error:",v.error);let a={enabled:t,maxNotifications:r.maxNotifications||5,defaultAutoHideDuration:r.defaultAutoHideDuration||6e3,position:r.position||{vertical:"top",horizontal:"right"}};return w(we.Provider,{value:c,children:n})}function ct(n){let i={enabled:n.showNotifications,maxNotifications:n.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:n.notificationOptions?.defaultAutoHideDuration||6e3,position:n.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:n.notificationOptions?.allowHtml||!1};return n.config?.publicApiKey?w(ke,{config:{publicApiKey:n.config.publicApiKey,env:n.config.env||"prod",appName:n.config.appName,loginActions:n.config.loginActions,logo:n.config.logo},children:w(fe,{...i,children:w(Ce,{...n})})}):w(fe,{...i,children:w(Ce,{...n})})}function li(){let n=ai(we);if(n===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return n}function ut(){let n=li();return n.isInitialized?G("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[w("h4",{children:"Session Debug Info"}),G("div",{children:[w("strong",{children:"Authenticated:"})," ",n.isAuthenticated?"Yes":"No"]}),G("div",{children:[w("strong",{children:"Loading:"})," ",n.isLoading?"Yes":"No"]}),G("div",{children:[w("strong",{children:"Error:"})," ",n.error||"None"]}),n.tokens&&G(ci,{children:[G("div",{children:[w("strong",{children:"Access Token:"})," ",n.tokens.accessToken.substring(0,20),"..."]}),G("div",{children:[w("strong",{children:"Refresh Token:"})," ",n.tokens.refreshToken.substring(0,20),"..."]}),G("div",{children:[w("strong",{children:"Access Expires In:"})," ",Math.round(n.expiresIn/1e3/60)," minutes"]}),G("div",{children:[w("strong",{children:"Refresh Expires In:"})," ",Math.round(n.refreshExpiresIn/1e3/60/60)," hours"]}),G("div",{children:[w("strong",{children:"Expiring Soon:"})," ",n.isExpiringSoon?"Yes":"No"]})]})]}):w("div",{children:"Session not initialized"})}import{useState as re,useEffect as Ne,useCallback as Ue,useRef as ne}from"react";import ui from"@nocios/crudify-browser";var ht=(n={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=n,[r,s]=re(null),[f,m]=re(!1),[x,v]=re(null),[T,b]=re({}),c=ne(null),a=ne(!0),o=ne(0),l=ne(0),p=Ue(()=>{s(null),v(null),m(!1),b({})},[]),I=Ue(async()=>{let z=Ie();if(!z){a.current&&(v("No user email available"),m(!1));return}c.current&&c.current.abort();let S=new AbortController;c.current=S;let R=++o.current;try{a.current&&(m(!0),v(null));let U=await ui.readItems("users",{filter:{email:z},pagination:{limit:1}});if(R===o.current&&a.current&&!S.signal.aborted){let O=U.data;if(U.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(M=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(M)).reduce((M,Z)=>({...M,[Z]:k[Z]}),{})}};b(W),v(null),l.current=0}else v("User profile not found"),s(null),b({})}}catch(U){if(R===o.current&&a.current){let O=U;if(O.name==="AbortError")return;e&&l.current<t&&(O.message?.includes("Network Error")||O.message?.includes("Failed to fetch"))?(l.current++,setTimeout(()=>{a.current&&I()},1e3*l.current)):(v("Failed to load user profile"),s(null),b({}))}}finally{R===o.current&&a.current&&m(!1),c.current===S&&(c.current=null)}},[e,t]);return Ne(()=>{i&&I()},[i,I]),Ne(()=>(a.current=!0,()=>{a.current=!1,c.current&&(c.current.abort(),c.current=null)}),[]),{userProfile:r,loading:f,error:x,extendedData:T,refreshProfile:I,clearProfile:p}};import{useState as pe,useEffect as di,useCallback as oe,useRef as fi}from"react";import gi from"@nocios/crudify-browser";var vt=(n,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:r}=i,{prefix:s,padding:f=0,separator:m=""}=n,[x,v]=pe(""),[T,b]=pe(!1),[c,a]=pe(null),o=fi(!1),l=oe(S=>{let R=String(S).padStart(f,"0");return`${s}${m}${R}`},[s,f,m]),p=oe(async()=>{b(!0),a(null);try{let S=await gi.getNextSequence(s),R=S.data;if(S.success&&R?.value){let U=l(R.value);v(U),t?.(U)}else{let U=S.errors?._error?.[0]||"Failed to generate code";a(U),r?.(U)}}catch(S){let R=S instanceof Error?S.message:"Unknown error";a(R),r?.(R)}finally{b(!1)}},[s,l,t,r]),I=oe(async()=>{await p()},[p]),z=oe(()=>{a(null)},[]);return di(()=>{e&&!x&&!o.current&&(o.current=!0,p())},[e,x,p]),{value:x,loading:T,error:c,regenerate:I,clearError:z}};import ye from"@nocios/crudify-browser";var he=class n{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 n.instance||(n.instance=new n),n.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:r,enableLogging:s,requestedBy:f}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&g.warn(`[CrudifyInitialization] ${f} attempted to initialize with different key. Already initialized with key: ${this.state.publicApiKey?.slice(0,10)}... by ${this.state.initializedBy}`);return}if(this.initializationPromise)return s&&g.debug(`[CrudifyInitialization] ${f} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(s&&g.debug(`[CrudifyInitialization] ${f} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(f),await this.waitForHighPriorityOrTimeout(s),this.waitingForHighPriority.delete(f),this.getState().status==="INITIALIZED"){s&&g.debug(`[CrudifyInitialization] ${f} found initialization completed by HIGH priority`);return}s&&g.warn(`[CrudifyInitialization] ${f} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(g.warn(`[CrudifyInitialization] HIGH priority request from ${f} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),s&&g.debug(`[CrudifyInitialization] ${f} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=f,this.initializationPromise=this.performInitialization(t,r,s);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=r,this.state.error=null,s&&g.info(`[CrudifyInitialization] Successfully initialized by ${f} (${e} priority)`)}catch(m){throw this.state.status="ERROR",this.state.error=m instanceof Error?m:new Error(String(m)),this.initializationPromise=null,g.error(`[CrudifyInitialization] Initialization failed for ${f}`,m instanceof Error?m:{message:String(m)}),m}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let r=0,s=setInterval(()=>{if(r+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(s),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){r=0;return}r>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(s),i&&g.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let r=ye.getTokenData();if(r&&r.endpoint){t&&g.debug("[CrudifyInitialization] SDK already initialized externally");return}ye.config(e);let s=t?"debug":"none",f=await ye.init(i,s);if(f.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(f.errors||"Unknown error")}`);f.apiEndpointAdmin&&f.apiKeyEndpointAdmin&&J.notifyCredentialsReady({apiUrl:f.apiEndpointAdmin,apiKey:f.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}}},se=he.getInstance();import{useState as Pe,useCallback as L,useRef as pi,useMemo as ae}from"react";import me from"@nocios/crudify-browser";var Fe=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,yi=n=>{let i=n.lastIndexOf("."),e=i>0?n.substring(i):"",t=Date.now(),r=Math.random().toString(36).substring(2,8);return`${t}_${r}${e}`},wt=(n={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:r=0,visibility:s="private",onUploadComplete:f,onUploadError:m,onFileRemoved:x,onFilesChange:v}=n,[T,b]=Pe([]),[c,a]=Pe(!1),o=pi(new Map),l=L(()=>{a(!0)},[]),p=L((u,h)=>{b(y=>y.map(A=>A.id===u?{...A,...h}:A))},[]),I=L(u=>{v?.(u)},[v]),z=L(u=>i&&i.length>0&&!i.includes(u.type)?{valid:!1,error:`File type not allowed: ${u.type}`}:u.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),S=L(async(u,h)=>{try{if(!se.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let y=yi(h.name),D=await me.generateSignedUrl({fileName:y,contentType:h.type,visibility:s});if(!D.success||!D.data)throw new Error("Failed to get upload URL");let A=D.data,{uploadUrl:P,s3Key:C,publicUrl:_}=A;if(!P||!C)throw new Error("Incomplete signed URL response");let X=C.indexOf("/"),_e=X>0?C.substring(X+1):C;p(u.id,{status:"uploading",progress:0}),await new Promise((ce,B)=>{let F=new XMLHttpRequest;F.upload.addEventListener("progress",H=>{if(H.lengthComputable){let He=Math.round(H.loaded/H.total*100);p(u.id,{progress:He})}}),F.addEventListener("load",()=>{F.status>=200&&F.status<300?ce():B(new Error(`Upload failed with status ${F.status}`))}),F.addEventListener("error",()=>{B(new Error("Network error during upload"))}),F.addEventListener("abort",()=>{B(new Error("Upload cancelled"))}),F.open("PUT",P),F.setRequestHeader("Content-Type",h.type),F.send(h)});let Ge={status:"completed",progress:100,filePath:_e,visibility:s,publicUrl:s==="public"?_:void 0,file:void 0};b(ce=>{let B=ce.map(H=>H.id===u.id?{...H,...Ge}:H);I(B);let F=B.find(H=>H.id===u.id);return F&&f?.(F),B})}catch(y){let D=y instanceof Error?y.message:"Unknown error";p(u.id,{status:"error",progress:0,errorMessage:D}),b(A=>{let P=A.find(C=>C.id===u.id);return P&&m?.(P,D),A})}},[p,f,m,s]),R=L(async u=>{let h=Array.from(u),y=[];b(D=>{if(t!==void 0){let C=D.filter(X=>X.status!=="error").length,_=t-C;if(_<=0)return g.warn(`File limit of ${t} already reached`),D;h.length>_&&(h=h.slice(0,_),g.warn(`Only ${_} files will be added to not exceed limit`))}let A=[];for(let C of h){let _=z(C),X={id:Fe(),name:C.name,size:C.size,contentType:C.type,status:_.valid?"pending":"error",progress:0,createdAt:Date.now(),file:_.valid?C:void 0,errorMessage:_.error};A.push(X)}y=A;let P=[...D,...A];return I(P),P}),setTimeout(()=>{let D=y.filter(A=>A.status==="pending"&&A.file);for(let A of D)if(A.file){let P=S(A,A.file);o.current.set(A.id,P),P.finally(()=>{o.current.delete(A.id)})}},0)},[t,z,S,I]),U=L(async u=>{let h=T.find(y=>y.id===u);if(!h)return!1;p(u,{status:"removing"});try{if(h.filePath){if(!se.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");if(!(await me.disableFile({filePath:h.filePath})).success)throw new Error("Failed to remove file from server")}return b(y=>{let D=y.filter(A=>A.id!==u);return I(D),D}),x?.(h),!0}catch(y){return p(u,{status:h.filePath?"completed":"error",errorMessage:y instanceof Error?y.message:"Error removing file"}),!1}},[T,p,I,x]),O=L(()=>{b([]),I([])},[I]),k=L(async u=>{let h=T.find(D=>D.id===u);if(!h||h.status!=="error"||!h.file){g.warn("Cannot retry: file not found or no original file");return}p(u,{status:"pending",progress:0,errorMessage:void 0});let y=S(h,h.file);o.current.set(u,y),y.finally(()=>{o.current.delete(u)})},[T,p,S]),W=L(async()=>{let u=Array.from(o.current.values());u.length>0&&await Promise.allSettled(u)},[]),M=u=>{let h=u.split(".").pop()?.toLowerCase()||"";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"},Z=L(u=>{let h=u.map(y=>{let A=y.filePath.startsWith("http://")||y.filePath.startsWith("https://")?new URL(y.filePath).pathname:y.filePath,P=A.includes("/public/")||A.startsWith("public/")?"public":"private",C=y.contentType||M(y.name);return{id:Fe(),name:y.name,size:y.size||0,contentType:C,status:"completed",progress:100,filePath:y.filePath,visibility:P,createdAt:Date.now()}});b(h),I(h)},[I]),K=L(async u=>{let h=T.find(y=>y.id===u);if(!h||!h.filePath)return null;if(h.visibility==="public"&&h.publicUrl)return h.publicUrl;try{if(!se.isInitialized())return null;let y=await me.getFileUrl({filePath:h.filePath,expiresIn:3600}),D=y.data;return y.success&&D?.url?D.url:null}catch{return null}},[T]),le=ae(()=>T.some(u=>u.status==="uploading"||u.status==="pending"),[T]),Le=ae(()=>T.filter(u=>u.status==="uploading"||u.status==="pending").length,[T]),ze=ae(()=>T.filter(u=>u.status==="completed"&&u.filePath).map(u=>u.filePath),[T]),{isValid:Ke,validationError:Oe}=ae(()=>{let u=T.filter(y=>y.status==="completed").length;return u<r?{isValid:!1,validationError:r===1?"At least one file is required":`At least ${r} files are required`}:t!==void 0&&u>t?{isValid:!1,validationError:`Maximum ${t} files allowed`}:T.some(y=>y.status==="error")?{isValid:!1,validationError:"Some files have errors"}:{isValid:!0,validationError:null}},[T,r,t]);return{files:T,isUploading:le,pendingCount:Le,addFiles:R,removeFile:U,clearFiles:O,retryUpload:k,isValid:Ke,validationError:Oe,waitForUploads:W,completedFilePaths:ze,initializeFiles:Z,isTouched:c,markAsTouched:l,getPreviewUrl:K}};export{J as a,ke as b,be as c,E as d,ee as e,Se as f,fe as g,Re as h,ct as i,li as j,ut as k,ht as l,vt as m,he as n,se as o,wt as p};
|
package/dist/chunk-DJ3T7VVS.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
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 T=[/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 T)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;console.log("[CRUDIFY_DEBUG] resolveConfig called with:",{propsApiKey:e?`${e.substring(0,10)}...`:"undefined",propsEnv:t,enableDebug:l,documentCookie:typeof document<"u"?document.cookie:"N/A"});let 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 g=f("publicApiKey");if(console.log("[CRUDIFY_DEBUG] getCookie('publicApiKey'):",g?`${g.substring(0,10)}...`:"null"),l&&i.info("[ConfigResolver] Cookie check:",{hasCookieApiKey:!!g,cookieApiKey:g?`${g.substring(0,10)}...`:null,allCookies:typeof document<"u"?document.cookie:"N/A"}),g){let c=f("environment"),p=f("appName"),y=f("logo"),R=f("loginActions"),C=f("featureKeys"),A=f("theme");return s={publicApiKey:decodeURIComponent(g),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:!!g,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 g=a.replace(/_/g," ").toLowerCase().replace(/\b\w/g,c=>c.toUpperCase());return r&&i.debug(`[ErrorTranslation] No translation found, using friendly code: "${g}"`),g}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 B(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 d=class d{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return d.instance||(d.instance=new d),d.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([d, 'access', _15 => _15.instance, 'optionalAccess', _16 => _16.isPatched])&&d.instance.removePatches(),d.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};d.instance=null;var I=d;var b=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=b(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=b(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 = B; exports.i = J; exports.j = I; exports.k = b; exports.l = j; exports.m = q;
|