@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
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
var addSorting = (function() {
|
|
3
|
+
'use strict';
|
|
4
|
+
var cols,
|
|
5
|
+
currentSort = {
|
|
6
|
+
index: 0,
|
|
7
|
+
desc: false
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
// returns the summary table element
|
|
11
|
+
function getTable() {
|
|
12
|
+
return document.querySelector('.coverage-summary');
|
|
13
|
+
}
|
|
14
|
+
// returns the thead element of the summary table
|
|
15
|
+
function getTableHeader() {
|
|
16
|
+
return getTable().querySelector('thead tr');
|
|
17
|
+
}
|
|
18
|
+
// returns the tbody element of the summary table
|
|
19
|
+
function getTableBody() {
|
|
20
|
+
return getTable().querySelector('tbody');
|
|
21
|
+
}
|
|
22
|
+
// returns the th element for nth column
|
|
23
|
+
function getNthColumn(n) {
|
|
24
|
+
return getTableHeader().querySelectorAll('th')[n];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function onFilterInput() {
|
|
28
|
+
const searchValue = document.getElementById('fileSearch').value;
|
|
29
|
+
const rows = document.getElementsByTagName('tbody')[0].children;
|
|
30
|
+
|
|
31
|
+
// Try to create a RegExp from the searchValue. If it fails (invalid regex),
|
|
32
|
+
// it will be treated as a plain text search
|
|
33
|
+
let searchRegex;
|
|
34
|
+
try {
|
|
35
|
+
searchRegex = new RegExp(searchValue, 'i'); // 'i' for case-insensitive
|
|
36
|
+
} catch (error) {
|
|
37
|
+
searchRegex = null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
for (let i = 0; i < rows.length; i++) {
|
|
41
|
+
const row = rows[i];
|
|
42
|
+
let isMatch = false;
|
|
43
|
+
|
|
44
|
+
if (searchRegex) {
|
|
45
|
+
// If a valid regex was created, use it for matching
|
|
46
|
+
isMatch = searchRegex.test(row.textContent);
|
|
47
|
+
} else {
|
|
48
|
+
// Otherwise, fall back to the original plain text search
|
|
49
|
+
isMatch = row.textContent
|
|
50
|
+
.toLowerCase()
|
|
51
|
+
.includes(searchValue.toLowerCase());
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
row.style.display = isMatch ? '' : 'none';
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// loads the search box
|
|
59
|
+
function addSearchBox() {
|
|
60
|
+
var template = document.getElementById('filterTemplate');
|
|
61
|
+
var templateClone = template.content.cloneNode(true);
|
|
62
|
+
templateClone.getElementById('fileSearch').oninput = onFilterInput;
|
|
63
|
+
template.parentElement.appendChild(templateClone);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// loads all columns
|
|
67
|
+
function loadColumns() {
|
|
68
|
+
var colNodes = getTableHeader().querySelectorAll('th'),
|
|
69
|
+
colNode,
|
|
70
|
+
cols = [],
|
|
71
|
+
col,
|
|
72
|
+
i;
|
|
73
|
+
|
|
74
|
+
for (i = 0; i < colNodes.length; i += 1) {
|
|
75
|
+
colNode = colNodes[i];
|
|
76
|
+
col = {
|
|
77
|
+
key: colNode.getAttribute('data-col'),
|
|
78
|
+
sortable: !colNode.getAttribute('data-nosort'),
|
|
79
|
+
type: colNode.getAttribute('data-type') || 'string'
|
|
80
|
+
};
|
|
81
|
+
cols.push(col);
|
|
82
|
+
if (col.sortable) {
|
|
83
|
+
col.defaultDescSort = col.type === 'number';
|
|
84
|
+
colNode.innerHTML =
|
|
85
|
+
colNode.innerHTML + '<span class="sorter"></span>';
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return cols;
|
|
89
|
+
}
|
|
90
|
+
// attaches a data attribute to every tr element with an object
|
|
91
|
+
// of data values keyed by column name
|
|
92
|
+
function loadRowData(tableRow) {
|
|
93
|
+
var tableCols = tableRow.querySelectorAll('td'),
|
|
94
|
+
colNode,
|
|
95
|
+
col,
|
|
96
|
+
data = {},
|
|
97
|
+
i,
|
|
98
|
+
val;
|
|
99
|
+
for (i = 0; i < tableCols.length; i += 1) {
|
|
100
|
+
colNode = tableCols[i];
|
|
101
|
+
col = cols[i];
|
|
102
|
+
val = colNode.getAttribute('data-value');
|
|
103
|
+
if (col.type === 'number') {
|
|
104
|
+
val = Number(val);
|
|
105
|
+
}
|
|
106
|
+
data[col.key] = val;
|
|
107
|
+
}
|
|
108
|
+
return data;
|
|
109
|
+
}
|
|
110
|
+
// loads all row data
|
|
111
|
+
function loadData() {
|
|
112
|
+
var rows = getTableBody().querySelectorAll('tr'),
|
|
113
|
+
i;
|
|
114
|
+
|
|
115
|
+
for (i = 0; i < rows.length; i += 1) {
|
|
116
|
+
rows[i].data = loadRowData(rows[i]);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
// sorts the table using the data for the ith column
|
|
120
|
+
function sortByIndex(index, desc) {
|
|
121
|
+
var key = cols[index].key,
|
|
122
|
+
sorter = function(a, b) {
|
|
123
|
+
a = a.data[key];
|
|
124
|
+
b = b.data[key];
|
|
125
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
126
|
+
},
|
|
127
|
+
finalSorter = sorter,
|
|
128
|
+
tableBody = document.querySelector('.coverage-summary tbody'),
|
|
129
|
+
rowNodes = tableBody.querySelectorAll('tr'),
|
|
130
|
+
rows = [],
|
|
131
|
+
i;
|
|
132
|
+
|
|
133
|
+
if (desc) {
|
|
134
|
+
finalSorter = function(a, b) {
|
|
135
|
+
return -1 * sorter(a, b);
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
for (i = 0; i < rowNodes.length; i += 1) {
|
|
140
|
+
rows.push(rowNodes[i]);
|
|
141
|
+
tableBody.removeChild(rowNodes[i]);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
rows.sort(finalSorter);
|
|
145
|
+
|
|
146
|
+
for (i = 0; i < rows.length; i += 1) {
|
|
147
|
+
tableBody.appendChild(rows[i]);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
// removes sort indicators for current column being sorted
|
|
151
|
+
function removeSortIndicators() {
|
|
152
|
+
var col = getNthColumn(currentSort.index),
|
|
153
|
+
cls = col.className;
|
|
154
|
+
|
|
155
|
+
cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, '');
|
|
156
|
+
col.className = cls;
|
|
157
|
+
}
|
|
158
|
+
// adds sort indicators for current column being sorted
|
|
159
|
+
function addSortIndicators() {
|
|
160
|
+
getNthColumn(currentSort.index).className += currentSort.desc
|
|
161
|
+
? ' sorted-desc'
|
|
162
|
+
: ' sorted';
|
|
163
|
+
}
|
|
164
|
+
// adds event listeners for all sorter widgets
|
|
165
|
+
function enableUI() {
|
|
166
|
+
var i,
|
|
167
|
+
el,
|
|
168
|
+
ithSorter = function ithSorter(i) {
|
|
169
|
+
var col = cols[i];
|
|
170
|
+
|
|
171
|
+
return function() {
|
|
172
|
+
var desc = col.defaultDescSort;
|
|
173
|
+
|
|
174
|
+
if (currentSort.index === i) {
|
|
175
|
+
desc = !currentSort.desc;
|
|
176
|
+
}
|
|
177
|
+
sortByIndex(i, desc);
|
|
178
|
+
removeSortIndicators();
|
|
179
|
+
currentSort.index = i;
|
|
180
|
+
currentSort.desc = desc;
|
|
181
|
+
addSortIndicators();
|
|
182
|
+
};
|
|
183
|
+
};
|
|
184
|
+
for (i = 0; i < cols.length; i += 1) {
|
|
185
|
+
if (cols[i].sortable) {
|
|
186
|
+
// add the click event handler on the th so users
|
|
187
|
+
// dont have to click on those tiny arrows
|
|
188
|
+
el = getNthColumn(i).querySelector('.sorter').parentElement;
|
|
189
|
+
if (el.addEventListener) {
|
|
190
|
+
el.addEventListener('click', ithSorter(i));
|
|
191
|
+
} else {
|
|
192
|
+
el.attachEvent('onclick', ithSorter(i));
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
// adds sorting functionality to the UI
|
|
198
|
+
return function() {
|
|
199
|
+
if (!getTable()) {
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
cols = loadColumns();
|
|
203
|
+
loadData();
|
|
204
|
+
addSearchBox();
|
|
205
|
+
addSortIndicators();
|
|
206
|
+
enableUI();
|
|
207
|
+
};
|
|
208
|
+
})();
|
|
209
|
+
|
|
210
|
+
window.addEventListener('load', addSorting);
|
|
@@ -141,6 +141,24 @@ declare const CrudiaAutoGenerate: React.FC<CrudiaAutoGenerateProps>;
|
|
|
141
141
|
* - Single/multiple support
|
|
142
142
|
*/
|
|
143
143
|
|
|
144
|
+
/**
|
|
145
|
+
* Deletion handlers exposed by the component
|
|
146
|
+
*/
|
|
147
|
+
interface CrudiaFileFieldDeletionHandlers {
|
|
148
|
+
/** Execute all pending deletions (call this on form success callback) */
|
|
149
|
+
commitDeletions: () => Promise<{
|
|
150
|
+
success: boolean;
|
|
151
|
+
errors: string[];
|
|
152
|
+
}>;
|
|
153
|
+
/** Cancel all pending deletions and restore files */
|
|
154
|
+
restorePendingDeletions: () => void;
|
|
155
|
+
/** Whether there are files pending deletion */
|
|
156
|
+
hasPendingDeletions: boolean;
|
|
157
|
+
/** Mark the field as submitted (triggers validation errors display) */
|
|
158
|
+
markAsSubmitted: () => void;
|
|
159
|
+
/** Whether the field is valid */
|
|
160
|
+
isValid: boolean;
|
|
161
|
+
}
|
|
144
162
|
/**
|
|
145
163
|
* Props del componente CrudiaFileField
|
|
146
164
|
*/
|
|
@@ -199,6 +217,18 @@ interface CrudiaFileFieldProps {
|
|
|
199
217
|
* También se usa para previsualizar/descargar archivos públicos en modo readonly
|
|
200
218
|
*/
|
|
201
219
|
baseUrl: string;
|
|
220
|
+
/**
|
|
221
|
+
* Callback called when deletion handlers are ready
|
|
222
|
+
* Use this to get access to commitDeletions and restorePendingDeletions functions
|
|
223
|
+
*/
|
|
224
|
+
onDeletionHandlersReady?: (handlers: CrudiaFileFieldDeletionHandlers) => void;
|
|
225
|
+
/**
|
|
226
|
+
* Form mode: 'create' or 'edit' - affects delete behavior
|
|
227
|
+
* - create: delete shows confirmation and deletes immediately from server
|
|
228
|
+
* - edit: existing files use pendingDeletion, new files delete immediately
|
|
229
|
+
* @default "create"
|
|
230
|
+
*/
|
|
231
|
+
mode?: "create" | "edit";
|
|
202
232
|
}
|
|
203
233
|
/**
|
|
204
234
|
* Main file field component
|
|
@@ -265,4 +295,4 @@ interface CrudiaMarkdownFieldProps {
|
|
|
265
295
|
}
|
|
266
296
|
declare const CrudiaMarkdownField: React.FC<CrudiaMarkdownFieldProps>;
|
|
267
297
|
|
|
268
|
-
export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, CrudiaAutoGenerate as a, CrudiaFileField as b, CrudiaMarkdownField as c, type CrudifyLoginConfig as d, type CrudifyLoginProps as e, type CrudifyLoginTranslations as f, type UserLoginData as g, type PolicyAction as h, type CrudiaAutoGenerateProps as i, type CrudiaFileFieldProps as j, type CrudiaMarkdownFieldProps as k, POLICY_ACTIONS as l, PREFERRED_POLICY_ORDER as m };
|
|
298
|
+
export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, CrudiaAutoGenerate as a, CrudiaFileField as b, CrudiaMarkdownField as c, type CrudifyLoginConfig as d, type CrudifyLoginProps as e, type CrudifyLoginTranslations as f, type UserLoginData as g, type PolicyAction as h, type CrudiaAutoGenerateProps as i, type CrudiaFileFieldProps as j, type CrudiaMarkdownFieldProps as k, POLICY_ACTIONS as l, PREFERRED_POLICY_ORDER as m, type CrudiaFileFieldDeletionHandlers as n };
|
|
@@ -141,6 +141,24 @@ declare const CrudiaAutoGenerate: React.FC<CrudiaAutoGenerateProps>;
|
|
|
141
141
|
* - Single/multiple support
|
|
142
142
|
*/
|
|
143
143
|
|
|
144
|
+
/**
|
|
145
|
+
* Deletion handlers exposed by the component
|
|
146
|
+
*/
|
|
147
|
+
interface CrudiaFileFieldDeletionHandlers {
|
|
148
|
+
/** Execute all pending deletions (call this on form success callback) */
|
|
149
|
+
commitDeletions: () => Promise<{
|
|
150
|
+
success: boolean;
|
|
151
|
+
errors: string[];
|
|
152
|
+
}>;
|
|
153
|
+
/** Cancel all pending deletions and restore files */
|
|
154
|
+
restorePendingDeletions: () => void;
|
|
155
|
+
/** Whether there are files pending deletion */
|
|
156
|
+
hasPendingDeletions: boolean;
|
|
157
|
+
/** Mark the field as submitted (triggers validation errors display) */
|
|
158
|
+
markAsSubmitted: () => void;
|
|
159
|
+
/** Whether the field is valid */
|
|
160
|
+
isValid: boolean;
|
|
161
|
+
}
|
|
144
162
|
/**
|
|
145
163
|
* Props del componente CrudiaFileField
|
|
146
164
|
*/
|
|
@@ -199,6 +217,18 @@ interface CrudiaFileFieldProps {
|
|
|
199
217
|
* También se usa para previsualizar/descargar archivos públicos en modo readonly
|
|
200
218
|
*/
|
|
201
219
|
baseUrl: string;
|
|
220
|
+
/**
|
|
221
|
+
* Callback called when deletion handlers are ready
|
|
222
|
+
* Use this to get access to commitDeletions and restorePendingDeletions functions
|
|
223
|
+
*/
|
|
224
|
+
onDeletionHandlersReady?: (handlers: CrudiaFileFieldDeletionHandlers) => void;
|
|
225
|
+
/**
|
|
226
|
+
* Form mode: 'create' or 'edit' - affects delete behavior
|
|
227
|
+
* - create: delete shows confirmation and deletes immediately from server
|
|
228
|
+
* - edit: existing files use pendingDeletion, new files delete immediately
|
|
229
|
+
* @default "create"
|
|
230
|
+
*/
|
|
231
|
+
mode?: "create" | "edit";
|
|
202
232
|
}
|
|
203
233
|
/**
|
|
204
234
|
* Main file field component
|
|
@@ -265,4 +295,4 @@ interface CrudiaMarkdownFieldProps {
|
|
|
265
295
|
}
|
|
266
296
|
declare const CrudiaMarkdownField: React.FC<CrudiaMarkdownFieldProps>;
|
|
267
297
|
|
|
268
|
-
export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, CrudiaAutoGenerate as a, CrudiaFileField as b, CrudiaMarkdownField as c, type CrudifyLoginConfig as d, type CrudifyLoginProps as e, type CrudifyLoginTranslations as f, type UserLoginData as g, type PolicyAction as h, type CrudiaAutoGenerateProps as i, type CrudiaFileFieldProps as j, type CrudiaMarkdownFieldProps as k, POLICY_ACTIONS as l, PREFERRED_POLICY_ORDER as m };
|
|
298
|
+
export { type BoxScreenType as B, CrudifyLogin as C, LoginComponent as L, Policies as P, SessionStatus as S, UserProfileDisplay as U, CrudiaAutoGenerate as a, CrudiaFileField as b, CrudiaMarkdownField as c, type CrudifyLoginConfig as d, type CrudifyLoginProps as e, type CrudifyLoginTranslations as f, type UserLoginData as g, type PolicyAction as h, type CrudiaAutoGenerateProps as i, type CrudiaFileFieldProps as j, type CrudiaMarkdownFieldProps as k, POLICY_ACTIONS as l, PREFERRED_POLICY_ORDER as m, type CrudiaFileFieldDeletionHandlers as n };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var b=[/password[^:]*[:=]\s*[^\s,}]+/gi,/token[^:]*[:=]\s*[^\s,}]+/gi,/key[^:]*[:=]\s*["']?[^\s,}"']+/gi,/secret[^:]*[:=]\s*[^\s,}]+/gi,/authorization[^:]*[:=]\s*[^\s,}]+/gi,/mongodb(\+srv)?:\/\/[^\s]+/gi,/postgres:\/\/[^\s]+/gi,/mysql:\/\/[^\s]+/gi];function w(n){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp("(^|;)\\s*"+n+"=([^;]+)"));return e?e[2]:null}function S(){if(typeof window<"u"&&window.__CRUDIFY_ENV__)return window.__CRUDIFY_ENV__;let n=w("environment");return n&&["dev","stg","api","prod"].includes(n)?n:"prod"}var N=null,_="CrudifyUI",v=class{constructor(){this.explicitEnv=null;this.explicitEnv=N,this.prefix=_}getEffectiveEnv(){return this.explicitEnv!==null?this.explicitEnv:S()}sanitize(e){let t=e;for(let o of b)t=t.replace(o,"[REDACTED]");return t}sanitizeContext(e){let t={};for(let[o,r]of Object.entries(e))if(r!=null)if(o==="userId"&&typeof r=="string")t[o]=r.length>8?`${r.substring(0,8)}***`:r;else if(o==="email"&&typeof r=="string"){let[a,u]=r.split("@");t[o]=a&&u?`${a.substring(0,3)}***@${u}`:"[REDACTED]"}else typeof r=="string"?t[o]=this.sanitize(r):typeof r=="object"&&r!==null?t[o]=this.sanitizeContext(r):t[o]=r;return t}shouldLog(e){if(typeof window<"u"&&window.__CRUDIFY_DEBUG_MODE__)return!0;let t=this.getEffectiveEnv();return!((t==="prod"||t==="production"||t==="api")&&e!=="error")}log(e,t,o){if(!this.shouldLog(e))return;let r=this.sanitize(t),a=o?this.sanitizeContext(o):void 0,u={timestamp:new Date().toISOString(),level:e,environment:this.getEffectiveEnv(),service:this.prefix,message:r,...a&&Object.keys(a).length>0&&{context:a}},l=JSON.stringify(u);switch(e){case"error":console.error(l);break;case"warn":console.warn(l);break;case"info":console.info(l);break;case"debug":console.log(l);break}}error(e,t){let o;t instanceof Error?o={errorName:t.name,errorMessage:t.message,stack:t.stack}:o=t,this.log("error",e,o)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}getEnvironment(){return this.getEffectiveEnv()}setEnvironment(e){this.explicitEnv=e,N=e,typeof window<"u"&&(window.__CRUDIFY_ENV__=e)}isExplicitlyConfigured(){return this.explicitEnv!==null}},i= exports.a =new v;var f=n=>{let e=document.cookie.match(new RegExp("(^|;)\\s*"+n+"=([^;]+)"));return e?e[2]:null};function O(n={}){let{publicApiKey:e,env:t,appName:o,logo:r,loginActions:a,featureKeys:u,enableDebug:l=!1}=n,s={configSource:"none"};l&&i.info("[ConfigResolver] Resolving configuration...",{propsApiKey:e?`${e.substring(0,10)}...`:void 0,propsEnv:t,hasPropsAppName:!!o,hasPropsLogo:!!r,propsLoginActions:a,propsFeatureKeys:u});let d=f("publicApiKey");if(l&&i.info("[ConfigResolver] Cookie check:",{hasCookieApiKey:!!d,cookieApiKey:d?`${d.substring(0,10)}...`:null,allCookies:typeof document<"u"?document.cookie:"N/A"}),d){let c=f("environment"),p=f("appName"),y=f("logo"),R=f("loginActions"),C=f("featureKeys"),A=f("theme");return s={publicApiKey:decodeURIComponent(d),env:c&&["dev","stg","api","prod"].includes(c)?c:"prod",appName:p?decodeURIComponent(p):void 0,logo:y?decodeURIComponent(y):void 0,loginActions:R?decodeURIComponent(R).split(",").map(E=>E.trim()).filter(Boolean):void 0,featureKeys:C?decodeURIComponent(C).split(",").map(E=>E.trim()).filter(Boolean):void 0,theme:A?(()=>{try{return JSON.parse(decodeURIComponent(A))}catch(E){l&&i.warn("[ConfigResolver] Failed to parse theme cookie",E instanceof Error?{errorMessage:E.message}:{message:String(E)});return}})():void 0,configSource:"cookies"},l&&(i.info("[ConfigResolver] \u2705 Using COOKIES configuration",{env:s.env,hasAppName:!!s.appName,hasLogo:!!s.logo,loginActionsCount:_optionalChain([s, 'access', _2 => _2.loginActions, 'optionalAccess', _3 => _3.length]),featureKeysCount:_optionalChain([s, 'access', _4 => _4.featureKeys, 'optionalAccess', _5 => _5.length])}),typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s}return e?(s={publicApiKey:e,env:t||"prod",appName:o,logo:r,loginActions:a,featureKeys:u,configSource:"props"},l&&(i.info("[ConfigResolver] \u2705 Using PROPS configuration (fallback - no cookies found)",{env:s.env,hasAppName:!!s.appName,hasLogo:!!s.logo,loginActionsCount:_optionalChain([s, 'access', _6 => _6.loginActions, 'optionalAccess', _7 => _7.length]),featureKeysCount:_optionalChain([s, 'access', _8 => _8.featureKeys, 'optionalAccess', _9 => _9.length])}),typeof window<"u"&&(window.__CRUDIFY_RESOLVED_CONFIG=s)),s):(l&&i.error("[ConfigResolver] \u274C No configuration found! Neither cookies nor props have publicApiKey",{hasCookies:!!d,hasProps:!!e}),s)}function M(n={}){return O(n)}var k=["errors.{category}.{code}","errors.{code}","login.{code}","error.{code}","messages.{code}","{code}"],D={INVALID_CREDENTIALS:"auth",UNAUTHORIZED:"auth",INVALID_API_KEY:"auth",USER_NOT_FOUND:"auth",USER_NOT_ACTIVE:"auth",NO_PERMISSION:"auth",SESSION_EXPIRED:"auth",ITEM_NOT_FOUND:"data",NOT_FOUND:"data",IN_USE:"data",DUPLICATE_ENTRY:"data",FIELD_ERROR:"validation",BAD_REQUEST:"validation",INVALID_EMAIL:"validation",INVALID_CODE:"validation",REQUIRED_FIELD:"validation",INTERNAL_SERVER_ERROR:"system",DATABASE_CONNECTION_ERROR:"system",INVALID_CONFIGURATION:"system",UNKNOWN_OPERATION:"system",TIMEOUT_ERROR:"system",NETWORK_ERROR:"system",TOO_MANY_REQUESTS:"rate_limit"},L={INVALID_CREDENTIALS:"Invalid username or password",UNAUTHORIZED:"You are not authorized to perform this action",SESSION_EXPIRED:"Your session has expired. Please log in again.",USER_NOT_FOUND:"User not found",ITEM_NOT_FOUND:"Item not found",FIELD_ERROR:"Invalid field value",INTERNAL_SERVER_ERROR:"An internal error occurred",NETWORK_ERROR:"Network connection error",TIMEOUT_ERROR:"Request timeout",UNKNOWN_OPERATION:"Unknown operation",INVALID_EMAIL:"Invalid email format",INVALID_CODE:"Invalid code",TOO_MANY_REQUESTS:"Too many requests, please try again later"};function h(n,e){let{translateFn:t,currentLanguage:o,enableDebug:r}=e;r&&i.debug(`[ErrorTranslation] Translating error code: ${n} (lang: ${o||"unknown"})`);let a=n.toUpperCase(),u=D[a],l=k.map(c=>c.replace("{category}",u||"general").replace("{code}",a));r&&i.debug("[ErrorTranslation] Searching keys:",{translationKeys:l});for(let c of l){let p=t(c);if(r&&i.debug(`[ErrorTranslation] Checking key: "${c}" -> result: "${p}" (same as key: ${p===c})`),p&&p!==c)return r&&i.debug(`[ErrorTranslation] Found translation at key: ${c} = "${p}"`),p}let s=L[a];if(s)return r&&i.debug(`[ErrorTranslation] Using default message: "${s}"`),s;let d=a.replace(/_/g," ").toLowerCase().replace(/\b\w/g,c=>c.toUpperCase());return r&&i.debug(`[ErrorTranslation] No translation found, using friendly code: "${d}"`),d}function U(n,e){return n.map(t=>h(t,e))}function x(n,e){let{enableDebug:t}=e;t&&i.debug("[ErrorTranslation] Translating error:",{error:n});let o=h(n.code,e);return o!==n.code.toUpperCase()&&o!==n.code?(t&&i.debug(`[ErrorTranslation] Using hierarchical translation: "${o}"`),n.field?`${n.field}: ${o}`:o):n.message&&!n.message.includes("Error:")&&n.message.length>0&&n.message!==n.code?(t&&i.debug(`[ErrorTranslation] No hierarchical translation found, using API message: "${n.message}"`),n.message):(t&&i.debug(`[ErrorTranslation] Using final fallback: "${o}"`),n.field?`${n.field}: ${o}`:o)}function z(n,e={}){let t={translateFn:n,currentLanguage:e.currentLanguage,enableDebug:e.enableDebug||!1};return{translateErrorCode:o=>h(o,t),translateErrorCodes:o=>U(o,t),translateError:o=>x(o,t),translateApiError:o=>_optionalChain([o, 'optionalAccess', _10 => _10.data, 'optionalAccess', _11 => _11.response, 'optionalAccess', _12 => _12.status])?h(o.data.response.status,t):_optionalChain([o, 'optionalAccess', _13 => _13.status])?h(o.status,t):_optionalChain([o, 'optionalAccess', _14 => _14.code])?h(o.code,t):"Unknown error"}}var m=class n{constructor(){this.listeners=new Set;this.isHandlingAuthError=!1;this.lastErrorTime=0;this.lastEventType=null;this.DEBOUNCE_TIME=1e3}static getInstance(){return n.instance||(n.instance=new n),n.instance}emit(e,t){let o=Date.now();if(this.isHandlingAuthError&&this.lastEventType===e&&o-this.lastErrorTime<this.DEBOUNCE_TIME){i.debug(`AuthEventBus: Ignoring duplicate ${e} event (debounced)`);return}this.isHandlingAuthError=!0,this.lastErrorTime=o,this.lastEventType=e,i.debug(`AuthEventBus: Emitting ${e} event`,t?{details:t}:void 0);let r={type:e,details:t,timestamp:o};this.listeners.forEach(a=>{try{a(r)}catch(u){i.error("AuthEventBus: Error in listener",u instanceof Error?u:{message:String(u)})}}),setTimeout(()=>{this.isHandlingAuthError=!1,this.lastEventType=null},2e3)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clear(){this.listeners.clear(),this.isHandlingAuthError=!1,this.lastEventType=null}isHandling(){return this.isHandlingAuthError}},J= exports.i =m.getInstance();var g=class g{constructor(){this.isPatched=!1;this.refCount=0;this.listeners=new Set;this.originalPushState=window.history.pushState,this.originalReplaceState=window.history.replaceState}static getInstance(){return g.instance||(g.instance=new g),g.instance}subscribe(e){return this.listeners.add(e),this.refCount++,this.isPatched||this.applyPatches(),()=>{this.unsubscribe(e)}}unsubscribe(e){this.listeners.delete(e),this.refCount--,this.refCount===0&&this.isPatched&&this.removePatches()}applyPatches(){let e=this;window.history.pushState=function(...t){let o=e.originalPushState.apply(this,t);return e.notifyListeners(),o},window.history.replaceState=function(...t){let o=e.originalReplaceState.apply(this,t);return e.notifyListeners(),o},this.isPatched=!0}removePatches(){window.history.pushState=this.originalPushState,window.history.replaceState=this.originalReplaceState,this.isPatched=!1}notifyListeners(){this.listeners.forEach(e=>{try{e()}catch(t){i.error("NavigationTracker: Error in navigation listener",t instanceof Error?t:{message:String(t)})}})}static reset(){_optionalChain([g, 'access', _15 => _15.instance, 'optionalAccess', _16 => _16.isPatched])&&g.instance.removePatches(),g.instance=null}getSubscriberCount(){return this.refCount}isActive(){return this.isPatched}};g.instance=null;var I=g;var T=n=>{try{let e=n.split(".");if(e.length!==3)return i.warn("Invalid JWT format: token must have 3 parts"),null;let t=e[1],o=t+"=".repeat((4-t.length%4)%4);return JSON.parse(atob(o))}catch(e){return i.warn("Failed to decode JWT token",e instanceof Error?{errorMessage:e.message}:{message:String(e)}),null}},j= exports.l =()=>{try{let n=null;if(n=sessionStorage.getItem("authToken"),n||(n=sessionStorage.getItem("token")),n||(n=localStorage.getItem("authToken")||localStorage.getItem("token")),!n)return null;let e=T(n);return e&&(e.email||e["cognito:username"])||null}catch(n){return i.warn("Failed to get current user email",n instanceof Error?{errorMessage:n.message}:{message:String(n)}),null}},q= exports.m =n=>{try{let e=T(n);if(!e||!e.exp)return!0;let t=Math.floor(Date.now()/1e3);return e.exp<t}catch (e2){return!0}};exports.a = i; exports.b = f; exports.c = O; exports.d = M; exports.e = h; exports.f = U; exports.g = x; exports.h = z; exports.i = J; exports.j = I; exports.k = T; exports.l = j; exports.m = q;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }var _chunk34FAL7YWjs = require('./chunk-34FAL7YW.js');var _cryptojs = require('crypto-js'); var _cryptojs2 = _interopRequireDefault(_cryptojs);var c=class{constructor(t="sessionStorage"){this.encryptionKey=this.generateEncryptionKey(),this.storage=t==="localStorage"?window.localStorage:window.sessionStorage}generateEncryptionKey(){let t=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset(),screen.colorDepth,screen.width,screen.height,"crudify-login"].join("|");return _cryptojs2.default.SHA256(t).toString()}setItem(t,e,n){try{let r=_cryptojs2.default.AES.encrypt(e,this.encryptionKey).toString();if(this.storage.setItem(t,r),n){let s=new Date().getTime()+n*60*1e3;this.storage.setItem(`${t}_expiry`,s.toString())}}catch(r){_chunk34FAL7YWjs.a.error("Failed to encrypt and store data",r instanceof Error?r:{message:String(r)})}}getItem(t){try{let e=`${t}_expiry`,n=this.storage.getItem(e);if(n){let g=parseInt(n,10);if(new Date().getTime()>g)return this.removeItem(t),null}let r=this.storage.getItem(t);if(!r)return null;let i=_cryptojs2.default.AES.decrypt(r,this.encryptionKey).toString(_cryptojs2.default.enc.Utf8);return i||(_chunk34FAL7YWjs.a.warn("Failed to decrypt stored data - may be corrupted"),this.removeItem(t),null)}catch(e){return _chunk34FAL7YWjs.a.error("Failed to decrypt data",e instanceof Error?e:{message:String(e)}),this.removeItem(t),null}}removeItem(t){this.storage.removeItem(t),this.storage.removeItem(`${t}_expiry`)}setToken(t){try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=n.exp*1e3,s=new Date().getTime(),i=Math.floor((r-s)/(60*1e3));if(i>0){this.setItem("authToken",t,i);return}}}}catch (e2){_chunk34FAL7YWjs.a.warn("Failed to parse token expiry, using default expiry")}this.setItem("authToken",t,1440)}getToken(){let t=this.getItem("authToken");if(t)try{let e=t.split(".");if(e.length===3){let n=JSON.parse(atob(e[1]));if(n.exp){let r=Math.floor(Date.now()/1e3);if(n.exp<r)return this.removeItem("authToken"),null}}}catch (e3){return _chunk34FAL7YWjs.a.warn("Failed to validate token expiry"),this.removeItem("authToken"),null}return t}},y= exports.a =new c("sessionStorage"),h= exports.b =new c("localStorage");exports.a = y; exports.b = h;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as p,c as fe,e as Te,i as V,j as be,k as Ae,l as ke}from"./chunk-SUWV767V.mjs";import{createContext as ni,useContext as si,useEffect as oi,useState as j}from"react";import J from"@nocios/crudify-browser";var ge=class r{constructor(){this.listeners=[];this.credentials=null;this.isReady=!1}static getInstance(){return r.instance||(r.instance=new r),r.instance}notifyCredentialsReady(i){this.credentials=i,this.isReady=!0,this.listeners.forEach(e=>{try{e(i)}catch(t){p.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}},ee=ge.getInstance();import{jsx as ai}from"react/jsx-runtime";var Ie=ni(void 0),Se=({config:r,children:i})=>{let[e,t]=j(!0),[s,l]=j(null),[f,T]=j(!1),[P,A]=j(""),[L,c]=j();oi(()=>{if(!r.publicApiKey){l("No publicApiKey provided"),t(!1),T(!1);return}let d=`${r.publicApiKey}-${r.env}`;if(d===P&&f){t(!1);return}(async()=>{t(!0),l(null),T(!1);try{J.config(r.env||"prod");let E=await J.init(r.publicApiKey,"none");if(c(E),typeof J.transaction=="function"&&typeof J.login=="function")T(!0),A(d),E.apiEndpointAdmin&&E.apiKeyEndpointAdmin&&ee.notifyCredentialsReady({apiUrl:E.apiEndpointAdmin,apiKey:E.apiKeyEndpointAdmin});else throw new Error("Crudify methods not properly initialized")}catch(E){let I=E instanceof Error?E.message:"Failed to initialize Crudify";p.error("[CrudifyProvider] Initialization error",E instanceof Error?E:{message:String(E)}),l(I),T(!1)}finally{t(!1)}})()},[r.publicApiKey,r.env,P,f]);let o={crudify:f?J:null,isLoading:e,error:s,isInitialized:f,adminCredentials:L};return ai(Ie.Provider,{value:o,children:i})},xe=()=>{let r=si(Ie);if(r===void 0)throw new Error("useCrudify must be used within a CrudifyProvider");return r};import ie from"crypto-js";var m=class m{static setStorageType(i){m.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 ie.SHA256(i).toString()}static getEncryptionKey(){if(m.encryptionKey)return m.encryptionKey;let i=window.localStorage;if(!i)return m.encryptionKey=m.generateEncryptionKey(),m.encryptionKey;try{let e=i.getItem(m.ENCRYPTION_KEY_STORAGE);return(!e||e.length<32)&&(e=m.generateEncryptionKey(),i.setItem(m.ENCRYPTION_KEY_STORAGE,e)),m.encryptionKey=e,e}catch{return p.warn("Crudify: Cannot persist encryption key, using temporary key"),m.encryptionKey=m.generateEncryptionKey(),m.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 m.storageType==="none"?null:m.isStorageAvailable(m.storageType)?window[m.storageType]:(p.warn(`Crudify: ${m.storageType} not available, tokens won't persist`),null)}static encrypt(i){try{let e=m.getEncryptionKey();return ie.AES.encrypt(i,e).toString()}catch(e){return p.error("Crudify: Encryption failed",e instanceof Error?e:{message:String(e)}),i}}static decrypt(i){try{let e=m.getEncryptionKey();return ie.AES.decrypt(i,e).toString(ie.enc.Utf8)||i}catch(e){return p.error("Crudify: Decryption failed",e instanceof Error?e:{message:String(e)}),i}}static saveTokens(i){let e=m.getStorage();if(e)try{let t={accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt,savedAt:Date.now()},s=m.encrypt(JSON.stringify(t));e.setItem(m.TOKEN_KEY,s),p.debug("Crudify: Tokens saved successfully")}catch(t){p.error("Crudify: Failed to save tokens",t instanceof Error?t:{message:String(t)})}}static getTokens(){let i=m.getStorage();if(!i)return null;try{let e=i.getItem(m.TOKEN_KEY);if(!e)return null;let t=m.decrypt(e),s=JSON.parse(t);return!s.accessToken||!s.refreshToken||!s.expiresAt||!s.refreshExpiresAt?(p.warn("Crudify: Incomplete token data found, clearing storage"),m.clearTokens(),null):Date.now()>=s.refreshExpiresAt?(p.info("Crudify: Refresh token expired, clearing storage"),m.clearTokens(),null):{accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:s.expiresAt,refreshExpiresAt:s.refreshExpiresAt}}catch(e){return p.error("Crudify: Failed to retrieve tokens",e instanceof Error?e:{message:String(e)}),m.clearTokens(),null}}static clearTokens(){let i=m.getStorage();if(i)try{i.removeItem(m.TOKEN_KEY),p.debug("Crudify: Tokens cleared from storage")}catch(e){p.error("Crudify: Failed to clear tokens",e instanceof Error?e:{message:String(e)})}}static rotateEncryptionKey(){try{m.clearTokens(),m.encryptionKey=null;let i=window.localStorage;i&&i.removeItem(m.ENCRYPTION_KEY_STORAGE),p.info("Crudify: Encryption key rotated successfully")}catch(i){p.error("Crudify: Failed to rotate encryption key",i instanceof Error?i:{message:String(i)})}}static hasValidTokens(){return m.getTokens()!==null}static getExpirationInfo(){let i=m.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=m.getTokens();if(!t){p.warn("Crudify: Cannot update access token, no existing tokens found");return}m.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!==m.TOKEN_KEY)return;let s=t.oldValue!==null&&t.oldValue!=="";if(t.newValue===null){p.debug("Crudify: Tokens removed in another tab"),i(null,m.SYNC_EVENTS.TOKENS_CLEARED,s);return}if(t.newValue){p.debug("Crudify: Tokens updated in another tab");let l=m.getTokens();i(l,m.SYNC_EVENTS.TOKENS_UPDATED,s)}};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}};m.TOKEN_KEY="crudify_tokens",m.ENCRYPTION_KEY_STORAGE="crudify_enc_key",m.encryptionKey=null,m.storageType="localStorage",m.SYNC_EVENTS={TOKENS_CLEARED:"TOKENS_CLEARED",TOKENS_UPDATED:"TOKENS_UPDATED"};var b=m;import F from"@nocios/crudify-browser";var te=class r{constructor(){this.config={};this.initialized=!1;this.crudifyInitialized=!1;this.lastActivityTime=0;this.isRefreshingLocally=!1;this.refreshPromise=null}static getInstance(){return r.instance||(r.instance=new r),r.instance}async initialize(i={}){if(!this.initialized){if(this.config={storageType:"localStorage",autoRestore:!0,enableLogging:!1,env:"stg",...i},b.setStorageType(this.config.storageType||"localStorage"),this.config.publicApiKey&&!this.crudifyInitialized&&await this.ensureCrudifyInitialized(),F.setTokenInvalidationCallback(()=>{this.log("Tokens invalidated by crudify-core"),V.emit("SESSION_EXPIRED",{message:"Your session has expired. Please log in again.",source:"crudify-core.clearTokensAndRefreshState"})}),this.config.apiEndpointAdmin&&this.config.apiKeyEndpointAdmin){let e=b.getTokens();e?b.saveTokens({...e,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin}):b.saveTokens({accessToken:"",refreshToken:"",expiresAt:0,refreshExpiresAt:0,apiEndpointAdmin:this.config.apiEndpointAdmin,apiKeyEndpointAdmin:this.config.apiKeyEndpointAdmin})}this.config.autoRestore&&await this.restoreSession(),this.initialized=!0}}async login(i,e){try{let t=await F.login(i,e);if(!t.success)return{success:!1,error:this.formatError(t.errors),rawResponse:t};let s=b.getTokens(),l=t.data,f={accessToken:l.token,refreshToken:l.refreshToken,expiresAt:l.expiresAt,refreshExpiresAt:l.refreshExpiresAt,apiEndpointAdmin:s?.apiEndpointAdmin||this.config.apiEndpointAdmin,apiKeyEndpointAdmin:s?.apiKeyEndpointAdmin||this.config.apiKeyEndpointAdmin};return b.saveTokens(f),this.lastActivityTime=Date.now(),this.config.onLoginSuccess?.(f),{success:!0,tokens:f,data:l}}catch(t){return p.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 F.logout(),b.clearTokens(),this.log("Logout successful"),this.config.onLogout?.()}catch(i){this.log("Logout error:",i),b.clearTokens()}}async restoreSession(){try{this.log("Attempting to restore session...");let i=b.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"),b.clearTokens(),!1;if(F.setTokens({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:i.expiresAt,refreshExpiresAt:i.refreshExpiresAt}),F.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 s=b.getTokens();return s&&this.config.onSessionRestored?.(s),!0}return b.clearTokens(),await F.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),b.clearTokens(),await F.logout(),!1}}isAuthenticated(){return F.isLogin()||b.hasValidTokens()}getTokenInfo(){let i=F.getTokenData(),e=b.getExpirationInfo(),t=b.getTokens();return{isLoggedIn:this.isAuthenticated(),crudifyTokens:i,storageInfo:e,hasValidTokens:b.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 F.refreshAccessToken();if(!i.success)return this.log("Token refresh failed:",i.errors),b.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 b.saveTokens(t),this.log("Tokens refreshed and saved successfully"),this.lastActivityTime=Date.now(),!0}catch(i){return this.log("Token refresh error:",i),b.clearTokens(),this.config.showNotification?.(this.getSessionExpiredMessage(),"warning"),this.config.onSessionExpired?.(),!1}}isRefreshing(){return this.isRefreshingLocally}setupResponseInterceptor(){F.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"),V.emit("TOKEN_REFRESH_FAILED",{message:e.userFriendlyMessage,error:e.errorDetails,source:"SessionManager.setupResponseInterceptor"}),i;e.shouldTriggerLogout&&(b.hasValidTokens()&&!e.isIrrecoverable?(this.log("Access token expired, emitting TOKEN_EXPIRED event"),V.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"),V.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(!this.crudifyInitialized)try{this.log("Initializing crudify SDK...");let i=F.getTokenData();if(i&&i.endpoint){this.log("Crudify already initialized by another service"),this.crudifyInitialized=!0;return}let e=this.config.env||"stg";F.config(e);let t=this.config.publicApiKey,s=this.config.enableLogging?"debug":"none",l=await F.init(t,s);if(l&&l.success===!1&&l.errors)throw new Error(`Failed to initialize crudify: ${JSON.stringify(l.errors)}`);this.crudifyInitialized=!0,this.log("Crudify SDK initialized successfully")}catch(i){throw p.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(s=>s.errorType==="Unauthorized"||s.message?.includes("Unauthorized")||s.message?.includes("Not Authorized")||s.message?.includes("NOT_AUTHORIZED")||s.message?.includes("Token")||s.message?.includes("TOKEN")||s.message?.includes("Authentication")||s.message?.includes("UNAUTHENTICATED")||s.extensions?.code==="UNAUTHENTICATED"||s.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 s=Object.values(i.errors).flat().find(l=>typeof l=="string"&&(l.includes("NOT_AUTHORIZED")||l.includes("TOKEN_REFRESH_FAILED")||l.includes("TOKEN_HAS_EXPIRED")||l.includes("PLEASE_LOGIN")||l.includes("Unauthorized")||l.includes("UNAUTHENTICATED")||l.includes("SESSION_EXPIRED")||l.includes("INVALID_TOKEN")));s&&typeof s=="string"&&(e.isAuthError=!0,e.errorType="GraphQL Object",e.errorDetails=i.errors,e.shouldTriggerLogout=!0,s.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."):s.includes("TOKEN_HAS_EXPIRED")||s.includes("SESSION_EXPIRED")?(e.isTokenExpired=!0,e.userFriendlyMessage="Tu sesi\xF3n ha expirado. Por favor, inicia sesi\xF3n nuevamente."):s.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(){b.clearTokens(),F.logout(),this.lastActivityTime=0,this.log("Session cleared completely")}getSessionExpiredMessage(){return this.config.translateFn?Te("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 li,useEffect as re,useCallback as W}from"react";function Pe(r={}){let[i,e]=li({isAuthenticated:!1,isLoading:!0,isInitialized:!1,tokens:null,error:null}),t=te.getInstance(),s=W(async()=>{try{e(n=>({...n,isLoading:!0,error:null}));let c={autoRestore:r.autoRestore??!0,enableLogging:r.enableLogging??!1,showNotification:r.showNotification,translateFn:r.translateFn,apiEndpointAdmin:r.apiEndpointAdmin,apiKeyEndpointAdmin:r.apiKeyEndpointAdmin,publicApiKey:r.publicApiKey,env:r.env||"stg",onSessionExpired:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:"Session expired"})),r.onSessionExpired?.()},onSessionRestored:n=>{e(E=>({...E,isAuthenticated:!0,tokens:n,error:null})),r.onSessionRestored?.(n)},onLoginSuccess:n=>{e(E=>({...E,isAuthenticated:!0,tokens:n,error:null}))},onLogout:()=>{e(n=>({...n,isAuthenticated:!1,tokens:null,error:null}))}};await t.initialize(c),t.setupResponseInterceptor();let o=t.isAuthenticated(),d=t.getTokenInfo();e(n=>({...n,isAuthenticated:o,isInitialized:!0,isLoading:!1,tokens:d.crudifyTokens.accessToken?{accessToken:d.crudifyTokens.accessToken,refreshToken:d.crudifyTokens.refreshToken,expiresAt:d.crudifyTokens.expiresAt,refreshExpiresAt:d.crudifyTokens.refreshExpiresAt}:null}))}catch(c){let o=c instanceof Error?c.message:"Initialization failed";p.error("[useSession] Initialize failed",c instanceof Error?c:{message:o}),e(d=>({...d,isLoading:!1,isInitialized:!0,error:o}))}},[r.autoRestore,r.enableLogging,r.onSessionExpired,r.onSessionRestored]),l=W(async(c,o)=>{e(d=>({...d,isLoading:!0,error:null}));try{let d=await t.login(c,o);return d.success&&d.tokens?e(n=>({...n,isAuthenticated:!0,tokens:d.tokens,isLoading:!1,error:null})):e(n=>({...n,isAuthenticated:!1,tokens:null,isLoading:!1,error:null})),d}catch(d){let n=d instanceof Error?d.message:"Login failed";p.error("[useSession] Login error",d instanceof Error?d:{message:n});let E=n.includes("INVALID_CREDENTIALS")||n.includes("Invalid email")||n.includes("Invalid password")||n.includes("credentials");return e(I=>({...I,isAuthenticated:!1,tokens:null,isLoading:!1,error:E?null:n})),{success:!1,error:n}}},[t]),f=W(async()=>{e(c=>({...c,isLoading:!0}));try{await t.logout(),e(c=>({...c,isAuthenticated:!1,tokens:null,isLoading:!1,error:null}))}catch(c){e(o=>({...o,isAuthenticated:!1,tokens:null,isLoading:!1,error:c instanceof Error?c.message:"Logout error"}))}},[t]),T=W(async()=>{try{let c=await t.refreshTokens();if(c){let o=t.getTokenInfo();e(d=>({...d,tokens:o.crudifyTokens.accessToken?{accessToken:o.crudifyTokens.accessToken,refreshToken:o.crudifyTokens.refreshToken,expiresAt:o.crudifyTokens.expiresAt,refreshExpiresAt:o.crudifyTokens.refreshExpiresAt}:null,error:null}))}else e(o=>({...o,isAuthenticated:!1,tokens:null,error:"Token refresh failed"}));return c}catch(c){return e(o=>({...o,isAuthenticated:!1,tokens:null,error:c instanceof Error?c.message:"Token refresh failed"})),!1}},[t]),P=W(()=>{e(c=>({...c,error:null}))},[]),A=W(()=>t.getTokenInfo(),[t]);re(()=>{s()},[s]),re(()=>{if(!i.isAuthenticated||!i.tokens)return;let c=be.getInstance(),o=()=>{t.updateLastActivity()},d=c.subscribe(o);window.addEventListener("popstate",o);let n=()=>{let R=t.getTokenInfo().crudifyTokens.expiresIn||0;return R<300*1e3?30*1e3:R<1800*1e3?60*1e3:120*1e3},E,I=()=>{let S=n();E=setTimeout(async()=>{if(t.isRefreshing()){I();return}let R=t.getTokenInfo(),x=R.crudifyTokens.expiresIn||0,C=((R.crudifyTokens.expiresAt||0)-(Date.now()-x))*.5;if(x>0&&x<=C)if(e(z=>({...z,isLoading:!0})),await t.refreshTokens()){let z=t.getTokenInfo();e(ue=>({...ue,isLoading:!1,tokens:z.crudifyTokens.accessToken?{accessToken:z.crudifyTokens.accessToken,refreshToken:z.crudifyTokens.refreshToken,expiresAt:z.crudifyTokens.expiresAt,refreshExpiresAt:z.crudifyTokens.refreshExpiresAt}:null}))}else e(z=>({...z,isLoading:!1,isAuthenticated:!1,tokens:null}));let v=t.getTimeSinceLastActivity(),X=1800*1e3;v>X?await f():I()},S)};return I(),()=>{clearTimeout(E),window.removeEventListener("popstate",o),d()}},[i.isAuthenticated,i.tokens,t,r.enableLogging,f]),re(()=>{let c=V.subscribe(async o=>{if(o.type==="TOKEN_EXPIRED"){if(t.isRefreshing())return;e(d=>({...d,isLoading:!0}));try{if(await t.refreshTokens()){let n=t.getTokenInfo();e(E=>({...E,isLoading:!1,tokens:n.crudifyTokens.accessToken?{accessToken:n.crudifyTokens.accessToken,refreshToken:n.crudifyTokens.refreshToken,expiresAt:n.crudifyTokens.expiresAt,refreshExpiresAt:n.crudifyTokens.refreshExpiresAt}:null}))}else V.emit("SESSION_EXPIRED",{message:"Failed to refresh token after detecting expiration",source:"useSession.TOKEN_EXPIRED handler"})}catch(d){V.emit("SESSION_EXPIRED",{message:d instanceof Error?d.message:"Unknown error during refresh",source:"useSession.TOKEN_EXPIRED handler (error)"})}}(o.type==="SESSION_EXPIRED"||o.type==="TOKEN_REFRESH_FAILED")&&(e(d=>({...d,isAuthenticated:!1,tokens:null,isLoading:!1,error:o.details?.message||"Session expired"})),r.onSessionExpired?.())});return()=>c()},[r.onSessionExpired,t]),re(()=>{let c=b.subscribeToChanges((o,d,n)=>{d===b.SYNC_EVENTS.TOKENS_CLEARED?n&&i.isAuthenticated?(p.debug("[useSession] Cross-tab logout detected"),e(E=>({...E,isAuthenticated:!1,tokens:null})),r.onSessionExpired?.()):n&&e(E=>({...E,isAuthenticated:!1,tokens:null})):d===b.SYNC_EVENTS.TOKENS_UPDATED&&o&&(p.debug("[useSession] Cross-tab login/refresh detected"),e(E=>({...E,tokens:o,isAuthenticated:!0,error:null})))});return()=>c()},[i.isAuthenticated,r.onSessionExpired]);let L=W(()=>{t.updateLastActivity()},[t]);return{...i,login:l,logout:f,refreshTokens:T,clearError:P,getTokenInfo:A,updateActivity:L,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 we,createContext as ci,useContext as ui,useCallback as ne,useEffect as di}from"react";import{Snackbar as fi,Alert as gi,Box as pi,Portal as mi}from"@mui/material";import{v4 as yi}from"uuid";import hi from"dompurify";import{jsx as B,jsxs as Ti}from"react/jsx-runtime";var Ne=ci(null),Ei=r=>hi.sanitize(r,{ALLOWED_TAGS:["b","i","em","strong","br","span"],ALLOWED_ATTR:["class"],FORBID_TAGS:["script","iframe","object","embed"],FORBID_ATTR:["onload","onerror","onclick","onmouseover","onfocus","onblur"],WHOLE_DOCUMENT:!1,RETURN_DOM:!1,RETURN_DOM_FRAGMENT:!1,RETURN_TRUSTED_TYPE:!1}),pe=({children:r,maxNotifications:i=5,defaultAutoHideDuration:e=6e3,position:t={vertical:"top",horizontal:"right"},enabled:s=!1,allowHtml:l=!1})=>{let[f,T]=we([]),P=ne((o,d="info",n)=>{if(!s)return"";if(!o||typeof o!="string")return p.warn("GlobalNotificationProvider: Invalid message provided"),"";o.length>1e3&&(p.warn("GlobalNotificationProvider: Message too long, truncating"),o=o.substring(0,1e3)+"...");let E=yi(),I={id:E,message:o,severity:d,autoHideDuration:n?.autoHideDuration??e,persistent:n?.persistent??!1,allowHtml:n?.allowHtml??l};return T(S=>[...S.length>=i?S.slice(-(i-1)):S,I]),E},[i,e,s,l]),A=ne(o=>{T(d=>d.filter(n=>n.id!==o))},[]),L=ne(()=>{T([])},[]),c={showNotification:P,hideNotification:A,clearAllNotifications:L};return Ti(Ne.Provider,{value:c,children:[r,s&&B(mi,{children:B(pi,{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(o=>B(vi,{notification:o,onClose:()=>A(o.id)},o.id))})})]})},vi=({notification:r,onClose:i})=>{let[e,t]=we(!0),s=ne((l,f)=>{f!=="clickaway"&&(t(!1),setTimeout(i,300))},[i]);return di(()=>{if(!r.persistent&&r.autoHideDuration){let l=setTimeout(()=>{s()},r.autoHideDuration);return()=>clearTimeout(l)}},[r.autoHideDuration,r.persistent,s]),B(fi,{open:e,onClose:s,sx:{position:"relative","& .MuiSnackbarContent-root":{minWidth:"auto"}},TransitionProps:{enter:!0,exit:!0},children:B(gi,{variant:"filled",severity:r.severity,onClose:s,sx:{width:"100%",minWidth:"280px",maxWidth:"400px",wordBreak:"break-word"},children:r.allowHtml?B("span",{dangerouslySetInnerHTML:{__html:Ei(r.message)}}):B("span",{children:r.message})})})},Re=()=>{let r=ui(Ne);if(!r)throw new Error("useGlobalNotification debe ser usado dentro de un GlobalNotificationProvider");return r};import bi,{createContext as Ai,useContext as ki,useMemo as me}from"react";import{Fragment as Si,jsx as D,jsxs as M}from"react/jsx-runtime";var De=Ai(void 0);function Ce({children:r,options:i={},config:e,showNotifications:t=!1,notificationOptions:s={}}){let l;try{let{showNotification:n}=Re();l=n}catch{}let f={};try{let n=xe();n.isInitialized&&n.adminCredentials&&(f=n.adminCredentials)}catch{}let T=me(()=>{let n=fe({publicApiKey:e?.publicApiKey,env:e?.env,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env||"prod"}},[e,i?.enableLogging]),P=bi.useMemo(()=>({...i,showNotification:l,apiEndpointAdmin:f.apiEndpointAdmin,apiKeyEndpointAdmin:f.apiKeyEndpointAdmin,publicApiKey:T.publicApiKey,env:T.env,onSessionExpired:()=>{i.onSessionExpired?.()}}),[i,l,f.apiEndpointAdmin,f.apiKeyEndpointAdmin,T]),A=Pe(P),L=me(()=>{let n=fe({publicApiKey:e?.publicApiKey,env:e?.env,appName:e?.appName,logo:e?.logo,loginActions:e?.loginActions,enableDebug:i?.enableLogging});return{publicApiKey:n.publicApiKey,env:n.env,appName:n.appName,loginActions:n.loginActions,logo:n.logo}},[e,i?.enableLogging]),c=me(()=>{if(!A.tokens?.accessToken||!A.isAuthenticated)return null;try{let n=Ae(A.tokens.accessToken);if(n&&n.sub&&n.email&&n.subscriber){let E={_id:n.sub,email:n.email,subscriberKey:n.subscriber};return Object.keys(n).forEach(I=>{["sub","email","subscriber"].includes(I)||(E[I]=n[I])}),E}}catch(n){p.error("Error decoding JWT token for sessionData",n instanceof Error?n:{message:String(n)})}return null},[A.tokens?.accessToken,A.isAuthenticated]),o={...A,sessionData:c,config:L},d={enabled:t,maxNotifications:s.maxNotifications||5,defaultAutoHideDuration:s.defaultAutoHideDuration||6e3,position:s.position||{vertical:"top",horizontal:"right"}};return D(De.Provider,{value:o,children:r})}function xt(r){let i={enabled:r.showNotifications,maxNotifications:r.notificationOptions?.maxNotifications||5,defaultAutoHideDuration:r.notificationOptions?.defaultAutoHideDuration||6e3,position:r.notificationOptions?.position||{vertical:"top",horizontal:"right"},allowHtml:r.notificationOptions?.allowHtml||!1};return r.config?.publicApiKey?D(Se,{config:{publicApiKey:r.config.publicApiKey,env:r.config.env||"prod",appName:r.config.appName,loginActions:r.config.loginActions,logo:r.config.logo},children:D(pe,{...i,children:D(Ce,{...r})})}):D(pe,{...i,children:D(Ce,{...r})})}function Ii(){let r=ki(De);if(r===void 0)throw new Error("useSessionContext must be used within a SessionProvider");return r}function Pt(){let r=Ii();return r.isInitialized?M("div",{style:{padding:"10px",margin:"10px",border:"1px solid #ccc",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace"},children:[D("h4",{children:"Session Debug Info"}),M("div",{children:[D("strong",{children:"Authenticated:"})," ",r.isAuthenticated?"Yes":"No"]}),M("div",{children:[D("strong",{children:"Loading:"})," ",r.isLoading?"Yes":"No"]}),M("div",{children:[D("strong",{children:"Error:"})," ",r.error||"None"]}),r.tokens&&M(Si,{children:[M("div",{children:[D("strong",{children:"Access Token:"})," ",r.tokens.accessToken.substring(0,20),"..."]}),M("div",{children:[D("strong",{children:"Refresh Token:"})," ",r.tokens.refreshToken.substring(0,20),"..."]}),M("div",{children:[D("strong",{children:"Access Expires In:"})," ",Math.round(r.expiresIn/1e3/60)," minutes"]}),M("div",{children:[D("strong",{children:"Refresh Expires In:"})," ",Math.round(r.refreshExpiresIn/1e3/60/60)," hours"]}),M("div",{children:[D("strong",{children:"Expiring Soon:"})," ",r.isExpiringSoon?"Yes":"No"]})]})]}):D("div",{children:"Session not initialized"})}import{useState as se,useEffect as Fe,useCallback as Le,useRef as oe}from"react";import xi from"@nocios/crudify-browser";var Ft=(r={})=>{let{autoFetch:i=!0,retryOnError:e=!1,maxRetries:t=3}=r,[s,l]=se(null),[f,T]=se(!1),[P,A]=se(null),[L,c]=se({}),o=oe(null),d=oe(!0),n=oe(0),E=oe(0),I=Le(()=>{l(null),A(null),T(!1),c({})},[]),S=Le(async()=>{let R=ke();if(!R){d.current&&(A("No user email available"),T(!1));return}o.current&&o.current.abort();let x=new AbortController;o.current=x;let K=++n.current;try{d.current&&(T(!0),A(null));let U=await xi.readItems("users",{filter:{email:R},pagination:{limit:1}});if(K===n.current&&d.current&&!x.signal.aborted){let C=U.data;if(U.success&&C&&C.length>0){let v=C[0];l(v);let X={fullProfile:v,totalFields:Object.keys(v).length,displayData:{id:v.id,email:v.email,username:v.username,firstName:v.firstName,lastName:v.lastName,fullName:v.fullName||`${v.firstName||""} ${v.lastName||""}`.trim(),role:v.role,permissions:v.permissions||[],isActive:v.isActive,lastLogin:v.lastLogin,createdAt:v.createdAt,updatedAt:v.updatedAt,...Object.keys(v).filter(_=>!["id","email","username","firstName","lastName","fullName","role","permissions","isActive","lastLogin","createdAt","updatedAt"].includes(_)).reduce((_,z)=>({..._,[z]:v[z]}),{})}};c(X),A(null),E.current=0}else A("User profile not found"),l(null),c({})}}catch(U){if(K===n.current&&d.current){let C=U;if(C.name==="AbortError")return;e&&E.current<t&&(C.message?.includes("Network Error")||C.message?.includes("Failed to fetch"))?(E.current++,setTimeout(()=>{d.current&&S()},1e3*E.current)):(A("Failed to load user profile"),l(null),c({}))}}finally{K===n.current&&d.current&&T(!1),o.current===x&&(o.current=null)}},[e,t]);return Fe(()=>{i&&S()},[i,S]),Fe(()=>(d.current=!0,()=>{d.current=!1,o.current&&(o.current.abort(),o.current=null)}),[]),{userProfile:s,loading:f,error:P,extendedData:L,refreshProfile:S,clearProfile:I}};import{useState as ye,useEffect as Pi,useCallback as ae,useRef as wi}from"react";import Ni from"@nocios/crudify-browser";var Ut=(r,i={})=>{let{autoFetch:e=!0,onSuccess:t,onError:s}=i,{prefix:l,padding:f=0,separator:T=""}=r,[P,A]=ye(""),[L,c]=ye(!1),[o,d]=ye(null),n=wi(!1),E=ae(x=>{let K=String(x).padStart(f,"0");return`${l}${T}${K}`},[l,f,T]),I=ae(async()=>{c(!0),d(null);try{let x=await Ni.getNextSequence(l),K=x.data;if(x.success&&K?.value){let U=E(K.value);A(U),t?.(U)}else{let U=x.errors?._error?.[0]||"Failed to generate code";d(U),s?.(U)}}catch(x){let K=x instanceof Error?x.message:"Unknown error";d(K),s?.(K)}finally{c(!1)}},[l,E,t,s]),S=ae(async()=>{await I()},[I]),R=ae(()=>{d(null)},[]);return Pi(()=>{e&&!P&&!n.current&&(n.current=!0,I())},[e,P,I]),{value:P,loading:L,error:o,regenerate:S,clearError:R}};import he from"@nocios/crudify-browser";var Ee=class r{constructor(){this.state={status:"UNINITIALIZED",priority:null,publicApiKey:null,env:null,error:null,initializedBy:null};this.initializationPromise=null;this.highPriorityInitializerPresent=!1;this.waitingForHighPriority=new Set;this.HIGH_PRIORITY_WAIT_TIMEOUT=100}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerHighPriorityInitializer(){this.highPriorityInitializerPresent=!0}isHighPriorityInitializerPresent(){return this.highPriorityInitializerPresent}getState(){return{...this.state}}async initialize(i){let{priority:e,publicApiKey:t,env:s,enableLogging:l,requestedBy:f}=i;if(this.state.status==="INITIALIZED"){this.state.publicApiKey!==t&&p.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 l&&p.debug(`[CrudifyInitialization] ${f} waiting for ongoing initialization...`),this.initializationPromise;if(e==="LOW"&&this.highPriorityInitializerPresent&&this.state.status==="UNINITIALIZED"){if(l&&p.debug(`[CrudifyInitialization] ${f} (LOW priority) waiting for HIGH priority initializer...`),this.waitingForHighPriority.add(f),await this.waitForHighPriorityOrTimeout(l),this.waitingForHighPriority.delete(f),this.getState().status==="INITIALIZED"){l&&p.debug(`[CrudifyInitialization] ${f} found initialization completed by HIGH priority`);return}l&&p.warn(`[CrudifyInitialization] ${f} timeout waiting for HIGH priority, initializing with LOW priority`)}e==="HIGH"&&this.state.status==="INITIALIZING"&&this.state.priority==="LOW"&&(p.warn(`[CrudifyInitialization] HIGH priority request from ${f} interrupting LOW priority initialization by ${this.state.initializedBy}`),this.state.status="UNINITIALIZED",this.initializationPromise=null),l&&p.debug(`[CrudifyInitialization] ${f} starting initialization (${e} priority)...`),this.state.status="INITIALIZING",this.state.priority=e,this.state.initializedBy=f,this.initializationPromise=this.performInitialization(t,s,l);try{await this.initializationPromise,this.state.status="INITIALIZED",this.state.publicApiKey=t,this.state.env=s,this.state.error=null,l&&p.info(`[CrudifyInitialization] Successfully initialized by ${f} (${e} priority)`)}catch(T){throw this.state.status="ERROR",this.state.error=T instanceof Error?T:new Error(String(T)),this.initializationPromise=null,p.error(`[CrudifyInitialization] Initialization failed for ${f}`,T instanceof Error?T:{message:String(T)}),T}}async waitForHighPriorityOrTimeout(i){return new Promise(e=>{let s=0,l=setInterval(()=>{if(s+=10,this.state.status==="INITIALIZED"&&this.state.priority==="HIGH"){clearInterval(l),e();return}if(this.state.status==="INITIALIZING"&&this.state.priority==="HIGH"){s=0;return}s>=this.HIGH_PRIORITY_WAIT_TIMEOUT&&(clearInterval(l),i&&p.debug(`[CrudifyInitialization] Timeout waiting for HIGH priority (${this.HIGH_PRIORITY_WAIT_TIMEOUT}ms)`),e())},10)})}async performInitialization(i,e,t){let s=he.getTokenData();if(s&&s.endpoint){t&&p.debug("[CrudifyInitialization] SDK already initialized externally");return}he.config(e);let l=t?"debug":"none",f=await he.init(i,l);if(f.success===!1)throw new Error(`Crudify initialization failed: ${JSON.stringify(f.errors||"Unknown error")}`);f.apiEndpointAdmin&&f.apiKeyEndpointAdmin&&ee.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}}},Q=Ee.getInstance();import{useState as le,useCallback as N,useRef as Ri,useMemo as q}from"react";import ce from"@nocios/crudify-browser";var Ke=()=>`file_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,Ci=r=>{let i=r.lastIndexOf("."),e=i>0?r.substring(i):"",t=Date.now(),s=Math.random().toString(36).substring(2,8);return`${t}_${s}${e}`},ve=(r,i)=>{if(r.startsWith("http://")||r.startsWith("https://"))try{let e=new URL(r);return e.pathname.startsWith("/")?e.pathname.substring(1):e.pathname}catch{if(i&&r.startsWith(i))return r.substring(i.length)}return i&&r.startsWith(i)?r.substring(i.length):r},Bt=(r={})=>{let{acceptedTypes:i,maxFileSize:e=10*1024*1024,maxFiles:t,minFiles:s=0,visibility:l="private",onUploadComplete:f,onUploadError:T,onFileRemoved:P,onFilesChange:A,mode:L="edit"}=r,[c,o]=le([]),[d,n]=le(!1),[E,I]=le(!1),[S,R]=le([]),x=Ri(new Map),K=N(()=>{n(!0)},[]),U=N(()=>{I(!0),n(!0)},[]),C=N((a,g)=>{o(u=>u.map(h=>h.id===a?{...h,...g}:h))},[]),v=N(a=>{A?.(a)},[A]),X=N(a=>i&&i.length>0&&!i.includes(a.type)?{valid:!1,error:`File type not allowed: ${a.type}`}:a.size>e?{valid:!1,error:`File exceeds maximum size of ${(e/1048576).toFixed(1)}MB`}:{valid:!0},[i,e]),_=N(async(a,g)=>{try{if(!Q.isInitialized())throw new Error("Crudify is not initialized. Please wait for the application to finish loading.");let u=Ci(g.name),y=await ce.generateSignedUrl({fileName:u,contentType:g.type,visibility:l});if(!y.success||!y.data)throw new Error("Failed to get upload URL");let h=y.data,{uploadUrl:w,s3Key:k,publicUrl:H}=h;if(!w||!k)throw new Error("Incomplete signed URL response");let $=k.indexOf("/"),ii=$>0?k.substring($+1):k;C(a.id,{status:"uploading",progress:0}),await new Promise((de,Y)=>{let O=new XMLHttpRequest;O.upload.addEventListener("progress",G=>{if(G.lengthComputable){let ri=Math.round(G.loaded/G.total*100);C(a.id,{progress:ri})}}),O.addEventListener("load",()=>{O.status>=200&&O.status<300?de():Y(new Error(`Upload failed with status ${O.status}`))}),O.addEventListener("error",()=>{Y(new Error("Network error during upload"))}),O.addEventListener("abort",()=>{Y(new Error("Upload cancelled"))}),O.open("PUT",w),O.setRequestHeader("Content-Type",g.type),O.send(g)});let ti={status:"completed",progress:100,filePath:ii,visibility:l,publicUrl:l==="public"?H:void 0,file:void 0};o(de=>{let Y=de.map(G=>G.id===a.id?{...G,...ti}:G);v(Y);let O=Y.find(G=>G.id===a.id);return O&&f?.(O),Y})}catch(u){let y=u instanceof Error?u.message:"Unknown error";C(a.id,{status:"error",progress:0,errorMessage:y}),o(h=>{let w=h.find(k=>k.id===a.id);return w&&T?.(w,y),h})}},[C,f,T,l]),z=N(async a=>{let g=Array.from(a),u=[];o(y=>{if(t!==void 0){let k=y.filter($=>$.status!=="pendingDeletion"&&$.status!=="error").length,H=t-k;if(H<=0)return p.warn(`File limit of ${t} already reached`),y;g.length>H&&(g=g.slice(0,H),p.warn(`Only ${H} files will be added to not exceed limit`))}let h=[];for(let k of g){let H=X(k),$={id:Ke(),name:k.name,size:k.size,contentType:k.type,status:H.valid?"pending":"error",progress:0,createdAt:Date.now(),file:H.valid?k:void 0,errorMessage:H.error,isExisting:!1};h.push($)}u=h;let w=[...y,...h];return v(w),w}),setTimeout(()=>{let y=u.filter(h=>h.status==="pending"&&h.file);for(let h of y)if(h.file){let w=_(h,h.file);x.current.set(h.id,w),w.finally(()=>{x.current.delete(h.id)})}},0)},[t,X,_,v]),ue=N(async a=>{let g=c.find(y=>y.id===a);if(!g)return{needsConfirmation:!1,isExisting:!1};let u=g.isExisting===!0;return L==="create"||!u?{needsConfirmation:!0,isExisting:u}:(R(y=>[...y,a]),o(y=>{let h=y.map(k=>k.id===a?{...k,status:"pendingDeletion"}:k),w=h.filter(k=>k.status!=="pendingDeletion");return v(w),h}),{needsConfirmation:!1,isExisting:u})},[c,L,v]),ze=N(async a=>{let g=c.find(u=>u.id===a);if(!g)return{success:!1,error:"File not found"};if(!g.filePath)return o(u=>{let y=u.filter(h=>h.id!==a);return v(y),y}),{success:!0};try{if(!Q.isInitialized())return{success:!1,error:"Crudify not initialized"};let u=ve(g.filePath);return(await ce.disableFile({filePath:u})).success?(o(h=>{let w=h.filter(k=>k.id!==a);return v(w),w}),P?.(g),{success:!0}):{success:!1,error:"Failed to delete file"}}catch(u){return{success:!1,error:u instanceof Error?u.message:"Unknown error"}}},[c,v,P]),Ue=N(a=>{let g=c.find(u=>u.id===a);return!g||!g.isExisting?!1:(R(u=>u.filter(y=>y!==a)),o(u=>{let y=u.map(h=>h.id===a?{...h,status:"completed"}:h);return v(y),y}),!0)},[c,v]),Oe=N(()=>{S.length!==0&&(o(a=>{let g=a.map(u=>S.includes(u.id)?{...u,status:"completed"}:u);return v(g),g}),R([]))},[S,v]),He=N(async()=>{if(S.length===0)return{success:!0,errors:[]};let a=[],g=[];if(!Q.isInitialized())return{success:!1,errors:["Crudify is not initialized. Please wait for the application to finish loading."]};for(let u of S){let y=c.find(h=>h.id===u);if(!y?.filePath){g.push(u);continue}try{let h=ve(y.filePath);(await ce.disableFile({filePath:h})).success?(g.push(u),P?.(y)):a.push(`Failed to delete ${y.name}`)}catch(h){a.push(`Error deleting ${y.name}: ${h instanceof Error?h.message:"Unknown error"}`)}}return g.length>0&&(o(u=>u.filter(h=>!g.includes(h.id))),R(u=>u.filter(y=>!g.includes(y)))),{success:a.length===0,errors:a}},[c,S,P]),Me=N(()=>{o([]),v([])},[v]),_e=N(async a=>{let g=c.find(y=>y.id===a);if(!g||g.status!=="error"||!g.file){p.warn("Cannot retry: file not found or no original file");return}C(a,{status:"pending",progress:0,errorMessage:void 0});let u=_(g,g.file);x.current.set(a,u),u.finally(()=>{x.current.delete(a)})},[c,C,_]),Ge=N(async()=>{let a=Array.from(x.current.values());a.length>0&&await Promise.allSettled(a)},[]),Ve=a=>{let g=a.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"}[g]||"application/octet-stream"},$e=N((a,g)=>{let u=a.map(y=>{let h=ve(y.filePath,g),w=h.includes("/public/")||h.startsWith("public/")?"public":"private",k=y.contentType||Ve(y.name);return{id:Ke(),name:y.name,size:y.size||0,contentType:k,status:"completed",progress:100,filePath:h,visibility:w,createdAt:Date.now(),isExisting:!0}});o(u),v(u)},[v]),Ye=N(async a=>{let g=c.find(u=>u.id===a);if(!g||!g.filePath)return null;if(g.visibility==="public"&&g.publicUrl)return g.publicUrl;try{if(!Q.isInitialized())return null;let u=await ce.getFileUrl({filePath:g.filePath,expiresIn:3600}),y=u.data;return u.success&&y?.url?y.url:null}catch{return null}},[c]),We=q(()=>c.some(a=>a.status==="uploading"||a.status==="pending"),[c]),Be=q(()=>c.filter(a=>a.status==="uploading"||a.status==="pending").length,[c]),Xe=q(()=>c.filter(a=>a.status==="completed"&&a.filePath).map(a=>a.filePath),[c]),Z=q(()=>c.filter(a=>a.status!=="pendingDeletion"),[c]),Ze=q(()=>Z.filter(a=>a.status==="completed"||a.status==="pending"||a.status==="uploading").length,[Z]),{isValid:qe,validationError:je,validationErrorKey:Je,validationErrorParams:Qe}=q(()=>{let a=Z.filter(u=>u.status==="completed").length;if(a<s){let u=s===1?"file.validation.minFilesRequired":"file.validation.minFilesRequiredPlural";return{isValid:!1,validationError:u,validationErrorKey:u,validationErrorParams:{count:s}}}return t!==void 0&&a>t?{isValid:!1,validationError:"file.validation.maxFilesExceeded",validationErrorKey:"file.validation.maxFilesExceeded",validationErrorParams:{count:t}}:Z.some(u=>u.status==="error")?{isValid:!1,validationError:"file.validation.filesWithErrors",validationErrorKey:"file.validation.filesWithErrors",validationErrorParams:{}}:{isValid:!0,validationError:null,validationErrorKey:null,validationErrorParams:{}}},[Z,s,t]),ei=S.length>0;return{files:c,activeFiles:Z,activeFileCount:Ze,isUploading:We,pendingCount:Be,addFiles:z,removeFile:ue,deleteFileImmediately:ze,restoreFile:Ue,clearFiles:Me,retryUpload:_e,isValid:qe,validationError:je,validationErrorKey:Je,validationErrorParams:Qe,waitForUploads:Ge,completedFilePaths:Xe,initializeFiles:$e,isTouched:d,markAsTouched:K,isSubmitted:E,markAsSubmitted:U,getPreviewUrl:Ye,pendingDeletions:S,hasPendingDeletions:ei,commitDeletions:He,restorePendingDeletions:Oe}};export{ee as a,Se as b,xe as c,b as d,te as e,Pe as f,pe as g,Re as h,xt as i,Ii as j,Pt as k,Ft as l,Ut as m,Ee as n,Q as o,Bt as p};
|