@archbase/security 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2056 @@
1
+ import "reflect-metadata";
2
+ import * as I from "inversify";
3
+ import { decorate as vt, injectable as bt } from "inversify";
4
+ import { compressString as At, decompressString as Et, IOCContainer as xt, ARCHBASE_IOC_API_TYPE as H, processErrorMessage as ee, IsNotEmpty as G, IsOptional as te, IsBoolean as K, IsEmail as St, getKeyByEnumValue as je, useArchbasePasswordRemember as kt, getI18nextInstance as x, useArchbaseTheme as It, isEmailValidate as Pt, useArchbaseAppContext as Tt } from "@archbase/core";
5
+ import F from "crypto-js";
6
+ import { jwtDecode as Ct } from "jwt-decode";
7
+ import { jsx as u, jsxs as L, Fragment as re } from "react/jsx-runtime";
8
+ import He, { useState as m, useEffect as z, createContext as De, useMemo as Ut, useRef as Dt, useCallback as pe, useContext as _e } from "react";
9
+ import { BehaviorSubject as Fe } from "rxjs";
10
+ import { ArchbaseRemoteApiService as ce, useArchbaseStore as Ge } from "@archbase/data";
11
+ import { v4 as J } from "uuid";
12
+ import { Card as Je, Text as ne, Divider as ge, Group as Ve, Select as _t, Tooltip as Rt, Button as ie, TextInput as Pe, Loader as Nt, PasswordInput as Te, Checkbox as Mt, Anchor as Bt, useMantineColorScheme as Ot } from "@mantine/core";
13
+ import { useFocusTrap as Ke } from "@mantine/hooks";
14
+ import { IconCopy as Lt } from "@tabler/icons-react";
15
+ import { ArchbaseDialog as ze } from "@archbase/components";
16
+ import { useContainer as ye } from "inversify-react";
17
+ class qe {
18
+ id;
19
+ displayName;
20
+ email;
21
+ photo;
22
+ isAdmin;
23
+ constructor(e) {
24
+ this.id = e.id, this.displayName = e.displayName, this.email = e.email, this.photo = e.photo, this.isAdmin = e.isAdmin;
25
+ }
26
+ static newInstance() {
27
+ return new qe({});
28
+ }
29
+ }
30
+ class Ye {
31
+ username;
32
+ password;
33
+ remember;
34
+ constructor(e) {
35
+ this.username = e.username, this.password = e.password, this.remember = e.remember;
36
+ }
37
+ static newInstance() {
38
+ return new Ye({});
39
+ }
40
+ }
41
+ const Q = "YngzI1guK3dGaElFcFY9MywqK3xgPzg/Ojg7eD8xRmg=", xe = "c1ab58e7-c113-4225-a190-a9e59d1207fc", Se = "6faf6932-a0b5-457b-83b1-8d89ddbd91fd", ke = "602b05c5-ec46-451e-aba6-187e463bc245", Ie = "8b4a7c2d-9e5f-4163-b8a7-3f2c9d8e5a1b";
42
+ class $t {
43
+ getUsernameAndPassword() {
44
+ try {
45
+ const e = localStorage.getItem(Se);
46
+ if (e) {
47
+ const t = F.AES.decrypt(e, Q).toString(F.enc.Utf8), o = atob(t).split(":");
48
+ return { username: o[0], password: o[1], remember: !0 };
49
+ } else
50
+ return null;
51
+ } catch {
52
+ return null;
53
+ }
54
+ }
55
+ saveUsernameAndPassword(e, t) {
56
+ const s = btoa(`${e}:${t}`), o = F.AES.encrypt(s, Q).toString();
57
+ localStorage.setItem(Se, o);
58
+ }
59
+ getUsername() {
60
+ try {
61
+ const e = localStorage.getItem(ke);
62
+ if (e) {
63
+ const t = F.AES.decrypt(e, Q).toString(F.enc.Utf8);
64
+ return atob(t);
65
+ } else
66
+ return null;
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+ saveUsername(e) {
72
+ const t = btoa(e), s = F.AES.encrypt(t, Q).toString();
73
+ localStorage.setItem(ke, s);
74
+ }
75
+ isTokenExpired(e, t = 300) {
76
+ let s = e;
77
+ if (!s && !this.getToken())
78
+ return !0;
79
+ try {
80
+ const o = Ct(s.access_token);
81
+ if (!o)
82
+ return !0;
83
+ const a = Math.floor(Date.now() / 1e3), d = o.exp;
84
+ return a > d - t;
85
+ } catch {
86
+ return !0;
87
+ }
88
+ }
89
+ saveToken(e) {
90
+ if (e) {
91
+ const t = JSON.stringify(e), s = F.AES.encrypt(t, Q).toString(), o = At(s);
92
+ localStorage.setItem(xe, o);
93
+ } else
94
+ this.clearToken();
95
+ }
96
+ clearUsernameAndPassword() {
97
+ localStorage.removeItem(Se), localStorage.removeItem(ke);
98
+ }
99
+ clearToken() {
100
+ localStorage.removeItem(xe);
101
+ }
102
+ getToken() {
103
+ try {
104
+ const e = localStorage.getItem(xe);
105
+ if (!e)
106
+ return null;
107
+ const t = Et(e), s = F.AES.decrypt(t, Q).toString(F.enc.Utf8);
108
+ return JSON.parse(s);
109
+ } catch {
110
+ return null;
111
+ }
112
+ }
113
+ saveContext(e) {
114
+ try {
115
+ const t = F.AES.encrypt(e, Q).toString();
116
+ localStorage.setItem(Ie, t);
117
+ } catch (t) {
118
+ console.warn("Erro ao salvar contexto:", t);
119
+ }
120
+ }
121
+ getContext() {
122
+ try {
123
+ const e = localStorage.getItem(Ie);
124
+ return e ? F.AES.decrypt(e, Q).toString(F.enc.Utf8) : null;
125
+ } catch {
126
+ return null;
127
+ }
128
+ }
129
+ clearContext() {
130
+ localStorage.removeItem(Ie);
131
+ }
132
+ }
133
+ vt(bt(), $t);
134
+ function Xe(r) {
135
+ const t = new Uint8Array(1);
136
+ return window.crypto.getRandomValues(t), t[0] >= Math.floor(256 / r) * r ? Xe(r) : t[0] % r;
137
+ }
138
+ function jt(r) {
139
+ let e = "";
140
+ const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
141
+ for (let s = 0; s < r; s++)
142
+ e += t.charAt(Xe(t.length - 1));
143
+ return e;
144
+ }
145
+ async function Ft(r) {
146
+ if (!window.crypto.subtle?.digest)
147
+ throw new Error(
148
+ "The context/environment is not secure, and does not support the 'crypto.subtle' module. See: https://developer.mozilla.org/en-US/docs/Web/API/Crypto/subtle for details"
149
+ );
150
+ const t = new TextEncoder().encode(r), s = await window.crypto.subtle.digest("SHA-256", t), o = String.fromCharCode(...new Uint8Array(s));
151
+ return btoa(o).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
152
+ }
153
+ class Qe extends Error {
154
+ status;
155
+ statusText;
156
+ constructor(e, t, s) {
157
+ super(s), this.name = "FetchError", this.status = e, this.statusText = t;
158
+ }
159
+ }
160
+ function Vt(r) {
161
+ let e = "";
162
+ return Object.entries(r).forEach(([t, s]) => {
163
+ e += (e ? "&" : "") + t + "=" + encodeURIComponent(s);
164
+ }), e;
165
+ }
166
+ async function zt(r, e) {
167
+ return fetch(r, {
168
+ method: "POST",
169
+ body: Vt(e),
170
+ headers: { "Content-Type": "application/x-www-form-urlencoded" }
171
+ }).then(async (t) => {
172
+ if (!t.ok) {
173
+ const s = await t.text();
174
+ throw new Qe(t.status, t.statusText, s);
175
+ }
176
+ return t;
177
+ });
178
+ }
179
+ const Ze = "PKCE_code_verifier", Ce = "ROCP_auth_state";
180
+ async function Wt(r, e) {
181
+ const t = jt(96);
182
+ return sessionStorage.setItem(Ze, t), Ft(t).then((s) => {
183
+ const o = new URLSearchParams({
184
+ response_type: "code",
185
+ client_id: r.clientId,
186
+ redirect_uri: r.redirectUri,
187
+ code_challenge: s,
188
+ code_challenge_method: "S256",
189
+ ...r.extraAuthParameters
190
+ });
191
+ r.scope !== void 0 && o.append("scope", r.scope), sessionStorage.removeItem(Ce);
192
+ const a = e ?? r.state;
193
+ a && (sessionStorage.setItem(Ce, a), o.append("state", a)), r?.preLogin && r.preLogin(), window.location.replace(`${r.authorizationEndpoint}?${o.toString()}`);
194
+ });
195
+ }
196
+ function Ht(r) {
197
+ return r.access_token !== void 0;
198
+ }
199
+ function et(r, e) {
200
+ return zt(r, e).then((t) => t.json().then((s) => {
201
+ if (Ht(s))
202
+ return s;
203
+ throw Error(s);
204
+ }));
205
+ }
206
+ const Gt = (r) => {
207
+ const t = new URLSearchParams(window.location.search).get("code"), s = window.sessionStorage.getItem(Ze);
208
+ if (!t)
209
+ throw Error(`Parâmetro 'código' não encontrado na URL.
210
+ A autenticação ocorreu?`);
211
+ if (!s)
212
+ throw Error(`Não é possível obter tokens sem o CodeVerifier.
213
+ A autenticação ocorreu?`);
214
+ const o = {
215
+ grant_type: "authorization_code",
216
+ code: t,
217
+ scope: r.scope,
218
+ client_id: r.clientId,
219
+ redirect_uri: r.redirectUri,
220
+ code_verifier: s,
221
+ ...r.extraTokenParameters,
222
+ ...r.extraAuthParams
223
+ };
224
+ return et(r.tokenEndpoint, o);
225
+ }, Jt = (r) => {
226
+ const { config: e, refreshToken: t } = r, s = {
227
+ grant_type: "refresh_token",
228
+ refresh_token: t,
229
+ scope: e.scope,
230
+ client_id: e.clientId,
231
+ redirect_uri: e.redirectUri,
232
+ ...e.extraTokenParameters
233
+ };
234
+ return et(e.tokenEndpoint, s);
235
+ };
236
+ function Kt(r, e, t, s, o, a) {
237
+ const d = new URLSearchParams({
238
+ token: t || e,
239
+ token_type_hint: t ? "refresh_token" : "access_token",
240
+ client_id: r.clientId,
241
+ post_logout_redirect_uri: r.logoutRedirect ?? r.redirectUri,
242
+ ui_locales: window.navigator.languages.reduce((i, l) => i + " " + l),
243
+ ...r.extraLogoutParameters
244
+ });
245
+ s && d.append("id_token_hint", s), o && d.append("state", o), a && d.append("logout_hint", a), window.location.replace(`${r.logoutEndpoint}?${d.toString()}`);
246
+ }
247
+ function qt(r) {
248
+ const e = r.get("state"), t = sessionStorage.getItem(Ce);
249
+ if (e !== t)
250
+ throw new Error(
251
+ '"state" valor recebido do servidor de autenticação não corresponde à solicitação do cliente. Possível falsificação de solicitação entre sites'
252
+ );
253
+ }
254
+ function Z(r, e, t) {
255
+ const s = t === "session" ? sessionStorage : localStorage, [o, a] = m(() => {
256
+ const i = s.getItem(r);
257
+ try {
258
+ return i ? JSON.parse(i) : e;
259
+ } catch (l) {
260
+ return console.warn(
261
+ `Falha ao analisar o valor armazenado para '${r}'.
262
+ Continuando com o valor padrão.
263
+ Error: ${l.message}`
264
+ ), e;
265
+ }
266
+ }), d = (i) => {
267
+ if (i === void 0) {
268
+ a(i), s.removeItem(r);
269
+ return;
270
+ }
271
+ try {
272
+ const l = i instanceof Function ? i(o) : i;
273
+ a(l), s.setItem(r, JSON.stringify(l));
274
+ } catch {
275
+ console.log(`Falha ao armazenar valor '${i}' para chave '${r}'`);
276
+ }
277
+ };
278
+ return z(() => {
279
+ const i = (l) => {
280
+ l.storageArea === s && l.key === r && a(JSON.parse(l.newValue ?? ""));
281
+ };
282
+ return window.addEventListener("storage", i, !1), () => window.removeEventListener("storage", i, !1);
283
+ }), [o, d];
284
+ }
285
+ const kr = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
286
+ __proto__: null,
287
+ default: Z
288
+ }, Symbol.toStringTag, { value: "Module" }));
289
+ function fe(r) {
290
+ return ["", void 0, null].includes(r);
291
+ }
292
+ function Yt(r) {
293
+ const {
294
+ autoLogin: e = !0,
295
+ clearURL: t = !0,
296
+ decodeToken: s = !0,
297
+ scope: o = void 0,
298
+ preLogin: a = () => null,
299
+ postLogin: d = () => null,
300
+ onRefreshTokenExpire: i = void 0,
301
+ storage: l = "local"
302
+ } = r, w = {
303
+ ...r,
304
+ autoLogin: e,
305
+ clearURL: t,
306
+ decodeToken: s,
307
+ scope: o,
308
+ preLogin: a,
309
+ postLogin: d,
310
+ onRefreshTokenExpire: i,
311
+ storage: l
312
+ };
313
+ return Xt(w), w;
314
+ }
315
+ function Xt(r) {
316
+ if (fe(r?.clientId))
317
+ throw Error(
318
+ "'clientId' deve ser definido no objeto 'ArchbaseAuthConfig' passado para ArchbaseAuthProvider"
319
+ );
320
+ if (fe(r?.authorizationEndpoint))
321
+ throw Error(
322
+ "'authorizationEndpoint' deve ser definido no objeto 'ArchbaseAuthConfig' passado para ArchbaseAuthProvider"
323
+ );
324
+ if (fe(r?.tokenEndpoint))
325
+ throw Error(
326
+ "'tokenEndpoint' deve ser definido no objeto 'ArchbaseAuthConfig' passado para ArchbaseAuthProvider"
327
+ );
328
+ if (fe(r?.redirectUri))
329
+ throw Error(
330
+ "'redirectUri' deve ser definido no objeto 'ArchbaseAuthConfig' passado para ArchbaseAuthProvider"
331
+ );
332
+ if (!["session", "local"].includes(r.storage))
333
+ throw Error("'storage' deve ser um dos ('session', 'local')");
334
+ r?.extraAuthParams && console.warn(
335
+ "O parâmetro de configuração 'extraAuthParams' é obsoleto. Você deveria usar 'extraTokenParameters' em vez de 'extraAuthParams'."
336
+ ), r?.extraAuthParams && r?.extraTokenParameters && console.warn(
337
+ "Usar 'extraAuthParams' e 'extraTokenParameters' não é recomendado. Eles fazem a mesma coisa e você deve usar apenas 'extraTokenParameters'"
338
+ );
339
+ }
340
+ const oe = 600, se = (r) => Math.round(Date.now() / 1e3 + r);
341
+ function We(r) {
342
+ return Math.round(Date.now()) / 1e3 + 30 >= r;
343
+ }
344
+ const Qt = [
345
+ "refresh_expires_in",
346
+ // KeyCloak
347
+ "refresh_token_expires_in"
348
+ // Azure AD
349
+ ];
350
+ function Zt(r, e) {
351
+ for (const t of Qt)
352
+ if (t in e)
353
+ return e[t];
354
+ return e.refresh_token ? r + oe : r;
355
+ }
356
+ const me = (r) => {
357
+ try {
358
+ const t = r.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"), s = decodeURIComponent(
359
+ atob(t).split("").map(function(o) {
360
+ return "%" + ("00" + o.charCodeAt(0).toString(16)).slice(-2);
361
+ }).join("")
362
+ );
363
+ return JSON.parse(s);
364
+ } catch (e) {
365
+ throw console.error(e), Error(
366
+ `Falha ao decodificar o token de acesso.
367
+ É um JSON Web Token adequado?
368
+ Você pode desativar a decodificação JWT definindo o valor 'decodeToken' como 'falso' na configuração.`
369
+ );
370
+ }
371
+ }, er = De({
372
+ token: "",
373
+ login: () => null,
374
+ logOut: () => null,
375
+ error: null,
376
+ loginInProgress: !1
377
+ }), Ir = ({ authConfig: r, children: e }) => {
378
+ const t = Ut(() => Yt(r), [r]), [s, o] = Z(
379
+ "ROCP_refreshToken",
380
+ void 0,
381
+ t.storage
382
+ ), [a, d] = Z(
383
+ "ROCP_refreshTokenExpire",
384
+ se(2 * oe),
385
+ t.storage
386
+ ), [i, l] = Z("ROCP_token", "", t.storage), [w, A] = Z(
387
+ "ROCP_tokenExpire",
388
+ se(oe),
389
+ t.storage
390
+ ), [p, P] = Z(
391
+ "ROCP_idToken",
392
+ void 0,
393
+ t.storage
394
+ ), [E, y] = Z(
395
+ "ROCP_loginInProgress",
396
+ !1,
397
+ t.storage
398
+ ), [S, _] = Z(
399
+ "ROCP_refreshInProgress",
400
+ !1,
401
+ t.storage
402
+ ), [C, B] = m(), [U, D] = m(), [f, k] = m(null);
403
+ let N;
404
+ function O() {
405
+ o(void 0), l(""), A(se(oe)), d(se(oe)), P(void 0), B(void 0), D(void 0), y(!1);
406
+ }
407
+ function q(h, n) {
408
+ O(), k(null), t?.logoutEndpoint && Kt(t, i, s, p, h, n);
409
+ }
410
+ function R(h) {
411
+ O(), y(!0);
412
+ let n = h;
413
+ h && typeof h != "string" && (console.warn(
414
+ `O estado de login aprovado deve ser do tipo 'string'. Recebido'${h}'. Ignorando o valor...`
415
+ ), n = void 0), Wt(t, n).catch((v) => {
416
+ console.error(v), k(v.message), y(!1);
417
+ });
418
+ }
419
+ function W(h) {
420
+ l(h.access_token), o(h.refresh_token);
421
+ const n = t.tokenExpiresIn ?? h.expires_in ?? oe;
422
+ A(se(n));
423
+ const v = t.refreshTokenExpiresIn ?? Zt(n, h);
424
+ d(se(v)), P(h.id_token);
425
+ try {
426
+ h.id_token && D(me(h.id_token));
427
+ } catch (c) {
428
+ console.warn(`Falha ao decodificar idToken: ${c.message}`);
429
+ }
430
+ try {
431
+ t.decodeToken && B(me(h.access_token));
432
+ } catch (c) {
433
+ console.warn(`Falha ao decodificar o token de acesso: ${c.message}`);
434
+ }
435
+ }
436
+ function Y(h = !1) {
437
+ return h || !t.onRefreshTokenExpire ? R() : t.onRefreshTokenExpire({ login: R });
438
+ }
439
+ function $(h = !1) {
440
+ if (i && We(w) && !(S && !h)) {
441
+ if (We(a))
442
+ return Y(h);
443
+ if (s) {
444
+ _(!0), Jt({ config: t, refreshToken: s }).then((n) => W(n)).catch((n) => {
445
+ if (n instanceof Qe) {
446
+ if (n.status === 400)
447
+ return Y(h);
448
+ console.error(n), k(n.message), h && R();
449
+ } else
450
+ n instanceof Error && (console.error(n), k(n.message), h && R());
451
+ }).finally(() => {
452
+ _(!1);
453
+ });
454
+ return;
455
+ }
456
+ console.warn(
457
+ "Falha ao atualizar access_token. Muito provavelmente não há refresh_token ou o servidor de autenticação não respondeu com um tempo de expiração explícito e os tempos de expiração padrão são maiores do que o tempo de expiração real dos tokens"
458
+ );
459
+ }
460
+ }
461
+ z(() => (N = setInterval(() => $(), 1e4), () => clearInterval(N)), [i, s, a, w]);
462
+ const X = Dt(!1);
463
+ return z(() => {
464
+ if (E) {
465
+ const h = new URLSearchParams(window.location.search);
466
+ if (!h.get("code")) {
467
+ const n = h.get("error_description") || "Estado de autorização inválido. Atualizar a página pode resolver o problema.";
468
+ console.error(n), k(n), q();
469
+ return;
470
+ }
471
+ if (!X.current) {
472
+ X.current = !0;
473
+ try {
474
+ qt(h);
475
+ } catch (n) {
476
+ console.error(n), k(n.message);
477
+ }
478
+ Gt(t).then((n) => {
479
+ W(n), t?.postLogin && t.postLogin();
480
+ }).catch((n) => {
481
+ console.error(n), k(n.message);
482
+ }).finally(() => {
483
+ t.clearURL && window.history.replaceState(null, "", window.location.pathname), y(!1);
484
+ });
485
+ }
486
+ return;
487
+ }
488
+ if (!i && t.autoLogin)
489
+ return R();
490
+ try {
491
+ p && D(me(p));
492
+ } catch (h) {
493
+ console.warn(`Falha ao decodificar idToken: ${h.message}`);
494
+ }
495
+ try {
496
+ t.decodeToken && B(me(i));
497
+ } catch (h) {
498
+ console.warn(`Falha ao decodificar o token de acesso: ${h.message}`);
499
+ }
500
+ $(!0);
501
+ }, []), /* @__PURE__ */ u(
502
+ er.Provider,
503
+ {
504
+ value: { token: i, tokenData: C, idToken: p, idTokenData: U, login: R, logOut: q, error: f, loginInProgress: E },
505
+ children: e
506
+ }
507
+ );
508
+ };
509
+ class tt {
510
+ resourceService;
511
+ resource;
512
+ actions;
513
+ permissions;
514
+ alreadyApplied;
515
+ error;
516
+ isAdmin;
517
+ constructor(e, t, s) {
518
+ this.resourceService = xt.getContainer().get(H.Resource), this.resource = { resourceName: e, resourceDescription: t }, this.alreadyApplied = !1, this.actions = [], this.permissions = [], this.error = "", this.isAdmin = s;
519
+ }
520
+ registerAction(e, t) {
521
+ !this.alreadyApplied && this.actions.findIndex((s) => s.actionName === e) < 0 && this.actions.push({ actionName: e, actionDescription: t });
522
+ }
523
+ async apply(e) {
524
+ this.alreadyApplied || (this.alreadyApplied = !0, this.resourceService.registerResource({ resource: this.resource, actions: this.actions }).then((t) => {
525
+ this.permissions = t.permissions, this.error = "", e && e();
526
+ }).catch((t) => {
527
+ this.alreadyApplied = !1, this.error = ee(t);
528
+ }));
529
+ }
530
+ hasPermission(e) {
531
+ return this.permissions.includes(e) || this.isAdmin;
532
+ }
533
+ isError() {
534
+ return !!this.error;
535
+ }
536
+ getError() {
537
+ return this.error;
538
+ }
539
+ /**
540
+ * Retorna todas as permissões atuais
541
+ */
542
+ getPermissions() {
543
+ return [...this.permissions];
544
+ }
545
+ /**
546
+ * Retorna o status de carregamento
547
+ */
548
+ isLoading() {
549
+ return !this.alreadyApplied;
550
+ }
551
+ /**
552
+ * Verifica múltiplas permissões
553
+ */
554
+ hasAnyPermission(e) {
555
+ return e.some((t) => this.hasPermission(t));
556
+ }
557
+ /**
558
+ * Verifica se tem todas as permissões
559
+ */
560
+ hasAllPermissions(e) {
561
+ return e.every((t) => this.hasPermission(t));
562
+ }
563
+ /**
564
+ * Retorna informações detalhadas sobre uma permissão
565
+ */
566
+ getPermissionInfo(e) {
567
+ const t = this.hasPermission(e);
568
+ return {
569
+ hasPermission: t,
570
+ isAdmin: this.isAdmin,
571
+ reason: t ? this.isAdmin ? "Usuário é administrador" : "Usuário tem permissão específica" : "Usuário não tem permissão"
572
+ };
573
+ }
574
+ /**
575
+ * Registra múltiplas ações de uma vez
576
+ */
577
+ registerActions(e) {
578
+ e.forEach(({ actionName: t, actionDescription: s }) => {
579
+ this.registerAction(t, s);
580
+ });
581
+ }
582
+ /**
583
+ * Retorna todas as ações registradas
584
+ */
585
+ getRegisteredActions() {
586
+ return [...this.actions];
587
+ }
588
+ }
589
+ class V {
590
+ static instance;
591
+ _currentTenant = new Fe(null);
592
+ _availableTenants = new Fe([]);
593
+ constructor() {
594
+ const e = localStorage.getItem("tenant_info");
595
+ if (e)
596
+ try {
597
+ this._currentTenant.next(JSON.parse(e));
598
+ } catch (t) {
599
+ console.error("Erro ao carregar tenant armazenado:", t);
600
+ }
601
+ }
602
+ static getInstance() {
603
+ return V.instance || (V.instance = new V()), V.instance;
604
+ }
605
+ get currentTenant$() {
606
+ return this._currentTenant.asObservable();
607
+ }
608
+ get currentTenant() {
609
+ return this._currentTenant.getValue();
610
+ }
611
+ get availableTenants$() {
612
+ return this._availableTenants.asObservable();
613
+ }
614
+ get availableTenants() {
615
+ return this._availableTenants.getValue();
616
+ }
617
+ setCurrentTenant(e) {
618
+ this._currentTenant.next(e), e ? (localStorage.setItem("tenant_id", e.id), localStorage.setItem("tenant_info", JSON.stringify(e))) : (localStorage.removeItem("tenant_id"), localStorage.removeItem("tenant_info"));
619
+ }
620
+ setAvailableTenants(e) {
621
+ this._availableTenants.next(e);
622
+ }
623
+ clear() {
624
+ this._currentTenant.next(null), this._availableTenants.next([]), localStorage.removeItem("tenant_id"), localStorage.removeItem("tenant_info");
625
+ }
626
+ // Helper para headers de API
627
+ getHeaders() {
628
+ const e = {}, t = this.currentTenant;
629
+ return t && (e["X-TENANT-ID"] = t.id), e;
630
+ }
631
+ }
632
+ function Pr() {
633
+ return V.getInstance();
634
+ }
635
+ var ae = /* @__PURE__ */ ((r) => (r.USER = "user", r.PROFILE = "profile", r.GROUP = "group", r))(ae || {}), tr = Object.defineProperty, b = (r, e, t, s) => {
636
+ for (var o = void 0, a = r.length - 1, d; a >= 0; a--)
637
+ (d = r[a]) && (o = d(e, t, o) || o);
638
+ return o && tr(e, t, o), o;
639
+ }, rr = /* @__PURE__ */ ((r) => (r.VIEW = "VIEW", r.API = "API", r))(rr || {});
640
+ const rt = class st {
641
+ id;
642
+ code;
643
+ version;
644
+ createEntityDate;
645
+ updateEntityDate;
646
+ createdByUser;
647
+ lastModifiedByUser;
648
+ description;
649
+ intervals;
650
+ constructor(e) {
651
+ this.id = e.id || "", this.code = e.code || "", this.version = e.version || 0, this.createEntityDate = e.createEntityDate || "", this.updateEntityDate = e.updateEntityDate || "", this.createdByUser = e.createdByUser || "", this.lastModifiedByUser = e.lastModifiedByUser || "", this.description = e.description || "", this.intervals = e.intervals ? e.intervals.map((t) => new sr(t)) : [];
652
+ }
653
+ static newInstance = () => new st({
654
+ id: J(),
655
+ intervals: []
656
+ });
657
+ };
658
+ b([
659
+ G({
660
+ message: "archbase:Informe a descrição do cronograma de acesso"
661
+ })
662
+ ], rt.prototype, "description");
663
+ let ot = rt;
664
+ const we = class nt {
665
+ id;
666
+ code;
667
+ version;
668
+ createEntityDate;
669
+ updateEntityDate;
670
+ createdByUser;
671
+ lastModifiedByUser;
672
+ accessSchedule;
673
+ dayOfWeek;
674
+ startTime;
675
+ endTime;
676
+ constructor(e) {
677
+ this.id = e.id || "", this.code = e.code || "", this.version = e.version || 0, this.createEntityDate = e.createEntityDate || (/* @__PURE__ */ new Date()).toISOString(), this.updateEntityDate = e.updateEntityDate || (/* @__PURE__ */ new Date()).toISOString(), this.createdByUser = e.createdByUser || "", this.lastModifiedByUser = e.lastModifiedByUser || "", this.accessSchedule = e.accessSchedule ? new ot(e.accessSchedule) : void 0, this.dayOfWeek = e.dayOfWeek || 0, this.startTime = e.startTime || "", this.endTime = e.endTime || "";
678
+ }
679
+ static newInstance = () => new nt({
680
+ id: J(),
681
+ dayOfWeek: (/* @__PURE__ */ new Date()).getDay(),
682
+ startTime: "08:00",
683
+ endTime: "17:00"
684
+ });
685
+ };
686
+ b([
687
+ te()
688
+ ], we.prototype, "accessSchedule");
689
+ b([
690
+ G({
691
+ message: "archbase:Informe a hora de início"
692
+ })
693
+ ], we.prototype, "startTime");
694
+ b([
695
+ G({
696
+ message: "archbase:Informe a hora de término"
697
+ })
698
+ ], we.prototype, "endTime");
699
+ let sr = we;
700
+ class le {
701
+ id;
702
+ code;
703
+ version;
704
+ createEntityDate;
705
+ updateEntityDate;
706
+ createdByUser;
707
+ lastModifiedByUser;
708
+ name;
709
+ description;
710
+ actions;
711
+ constructor(e) {
712
+ this.id = e.id || "", this.code = e.code || "", this.version = e.version || 0, this.createEntityDate = e.createEntityDate || "", this.updateEntityDate = e.updateEntityDate || "", this.createdByUser = e.createdByUser || "", this.lastModifiedByUser = e.lastModifiedByUser || "", this.name = e.name || "", this.description = e.description || "", this.actions = e.actions || [];
713
+ }
714
+ }
715
+ b([
716
+ G({
717
+ message: "archbase:Informe o nome"
718
+ })
719
+ ], le.prototype, "name");
720
+ b([
721
+ G({
722
+ message: "archbase:Informe a descrição"
723
+ })
724
+ ], le.prototype, "description");
725
+ b([
726
+ te()
727
+ ], le.prototype, "actions");
728
+ const de = class it {
729
+ id;
730
+ code;
731
+ version;
732
+ createEntityDate;
733
+ updateEntityDate;
734
+ createdByUser;
735
+ lastModifiedByUser;
736
+ name;
737
+ description;
738
+ resource;
739
+ category;
740
+ active;
741
+ actionVersion;
742
+ isNewAction;
743
+ constructor(e) {
744
+ this.id = e.id || "", this.code = e.code || "", this.version = e.version || 0, this.createEntityDate = e.createEntityDate || (/* @__PURE__ */ new Date()).toISOString(), this.updateEntityDate = e.updateEntityDate || (/* @__PURE__ */ new Date()).toISOString(), this.createdByUser = e.createdByUser || "", this.lastModifiedByUser = e.lastModifiedByUser || "", this.name = e.name || "", this.description = e.description || "", this.resource = e.resource ? new ct(e.resource) : void 0, this.category = e.category || "", this.active = e.active || !1, this.actionVersion = e.actionVersion || "", this.isNewAction = e.isNewAction || !1;
745
+ }
746
+ static newInstance = () => new it({
747
+ id: J(),
748
+ active: !0,
749
+ isNewAction: !0
750
+ });
751
+ };
752
+ b([
753
+ G({
754
+ message: "archbase:Informe o nome para a ação"
755
+ })
756
+ ], de.prototype, "name");
757
+ b([
758
+ G({
759
+ message: "archbase:Informe a descrição para a ação"
760
+ })
761
+ ], de.prototype, "description");
762
+ b([
763
+ te()
764
+ ], de.prototype, "resource");
765
+ b([
766
+ G({
767
+ message: "archbase:Informe a categoria para a ação"
768
+ })
769
+ ], de.prototype, "category");
770
+ b([
771
+ K()
772
+ ], de.prototype, "active");
773
+ let or = de;
774
+ class ue extends le {
775
+ type;
776
+ isNewProfile;
777
+ constructor(e) {
778
+ super(e), this.type = ae.PROFILE, this.isNewProfile = e.isNewProfile || !1;
779
+ }
780
+ static newInstance = () => new ue({
781
+ id: J(),
782
+ isNewProfile: !0
783
+ });
784
+ }
785
+ class Re {
786
+ id;
787
+ code;
788
+ version;
789
+ createEntityDate;
790
+ updateEntityDate;
791
+ createdByUser;
792
+ lastModifiedByUser;
793
+ group;
794
+ constructor(e) {
795
+ this.id = e.id, this.code = e.code || "", this.version = e.version || 0, this.createEntityDate = e.createEntityDate || (/* @__PURE__ */ new Date()).toISOString(), this.updateEntityDate = e.updateEntityDate || (/* @__PURE__ */ new Date()).toISOString(), this.createdByUser = e.createdByUser || "", this.lastModifiedByUser = e.lastModifiedByUser || "", this.group = e.group ? new he(e.group) : void 0;
796
+ }
797
+ static newInstance = (e) => new Re({
798
+ id: J(),
799
+ group: e
800
+ });
801
+ }
802
+ class he extends le {
803
+ type;
804
+ isNewGroup;
805
+ constructor(e) {
806
+ super(e), this.type = ae.GROUP, this.isNewGroup = e.isNewGroup || !1;
807
+ }
808
+ static newInstance = () => new he({
809
+ id: J(),
810
+ isNewGroup: !0
811
+ });
812
+ }
813
+ const ve = class at {
814
+ id;
815
+ code;
816
+ version;
817
+ createEntityDate;
818
+ updateEntityDate;
819
+ createdByUser;
820
+ lastModifiedByUser;
821
+ name;
822
+ description;
823
+ actions;
824
+ active;
825
+ type;
826
+ isNewResource;
827
+ constructor(e) {
828
+ this.id = e.id || "", this.code = e.code || "", this.version = e.version || 0, this.createEntityDate = e.createEntityDate || "", this.updateEntityDate = e.updateEntityDate || "", this.createdByUser = e.createdByUser || "", this.lastModifiedByUser = e.lastModifiedByUser || "", this.name = e.name || "", this.description = e.description || "", this.actions = e.actions || [], this.active = e.active || !1, this.type = e.type || "VIEW", this.isNewResource = e.isNewResource || !1;
829
+ }
830
+ static newInstance = () => new at({
831
+ id: J(),
832
+ actions: [],
833
+ active: !0,
834
+ isNewResource: !0
835
+ });
836
+ };
837
+ b([
838
+ G({
839
+ message: "archbase:Informe o nome para o recurso"
840
+ })
841
+ ], ve.prototype, "name");
842
+ b([
843
+ G({
844
+ message: "archbase:Informe a descrição para o recurso"
845
+ })
846
+ ], ve.prototype, "description");
847
+ b([
848
+ K()
849
+ ], ve.prototype, "active");
850
+ let ct = ve;
851
+ const M = class lt extends le {
852
+ userName;
853
+ password;
854
+ changePasswordOnNextLogin;
855
+ allowPasswordChange;
856
+ allowMultipleLogins;
857
+ passwordNeverExpires;
858
+ accountDeactivated;
859
+ accountLocked;
860
+ unlimitedAccessHours;
861
+ isAdministrator;
862
+ accessSchedule;
863
+ groups;
864
+ profile;
865
+ avatar;
866
+ nickname;
867
+ email;
868
+ type;
869
+ isNewUser;
870
+ constructor(e) {
871
+ super(e), this.type = ae.USER, this.userName = e.userName || "", this.password = e.password || "", this.changePasswordOnNextLogin = e.changePasswordOnNextLogin || !1, this.allowPasswordChange = e.allowPasswordChange || !1, this.allowMultipleLogins = e.allowMultipleLogins || !1, this.passwordNeverExpires = e.passwordNeverExpires || !1, this.accountDeactivated = e.accountDeactivated || !1, this.accountLocked = e.accountLocked || !1, this.unlimitedAccessHours = e.unlimitedAccessHours || !1, this.isAdministrator = e.isAdministrator || !1, this.accessSchedule = e.accessSchedule ? new ot(e.accessSchedule) : void 0, this.groups = e.groups ? e.groups.map((t) => new Re(t)) : [], this.profile = e.profile ? new ue(e.profile) : void 0, this.email = e.email || "", this.avatar = e.avatar || void 0, this.isNewUser = e.isNewUser || !1, this.nickname = e.nickname;
872
+ }
873
+ static newInstance = () => new lt({
874
+ id: J(),
875
+ userName: "",
876
+ password: "",
877
+ groups: [],
878
+ avatar: null,
879
+ isAdministrator: !1,
880
+ allowPasswordChange: !0,
881
+ passwordNeverExpires: !0,
882
+ isNewUser: !0
883
+ });
884
+ };
885
+ b([
886
+ G({
887
+ message: "archbase:Informe o nome de usuário"
888
+ })
889
+ ], M.prototype, "userName");
890
+ b([
891
+ K()
892
+ ], M.prototype, "changePasswordOnNextLogin");
893
+ b([
894
+ K()
895
+ ], M.prototype, "allowPasswordChange");
896
+ b([
897
+ K()
898
+ ], M.prototype, "allowMultipleLogins");
899
+ b([
900
+ K()
901
+ ], M.prototype, "passwordNeverExpires");
902
+ b([
903
+ K()
904
+ ], M.prototype, "accountDeactivated");
905
+ b([
906
+ K()
907
+ ], M.prototype, "accountLocked");
908
+ b([
909
+ K()
910
+ ], M.prototype, "unlimitedAccessHours");
911
+ b([
912
+ K()
913
+ ], M.prototype, "isAdministrator");
914
+ b([
915
+ te()
916
+ ], M.prototype, "accessSchedule");
917
+ b([
918
+ te()
919
+ ], M.prototype, "groups");
920
+ b([
921
+ te()
922
+ ], M.prototype, "profile");
923
+ b([
924
+ St(
925
+ {},
926
+ {
927
+ message: "archbase:Informe um email válido"
928
+ }
929
+ )
930
+ ], M.prototype, "email");
931
+ let be = M;
932
+ const Ne = class Ue {
933
+ id;
934
+ code;
935
+ version;
936
+ createEntityDate;
937
+ updateEntityDate;
938
+ createdByUser;
939
+ lastModifiedByUser;
940
+ security;
941
+ action;
942
+ tenantId;
943
+ companyId;
944
+ projectId;
945
+ constructor(e) {
946
+ this.id = e.id || "", this.code = e.code || "", this.version = e.version || 0, this.createEntityDate = e.createEntityDate || "", this.updateEntityDate = e.updateEntityDate || "", this.createdByUser = e.createdByUser || "", this.lastModifiedByUser = e.lastModifiedByUser || "", this.security = e.security ? Ue.createDtoFromJson(e.security) : void 0, this.action = e.action ? new or(e.action) : void 0, this.tenantId = e.tenantId || "", this.companyId = e.companyId || "", this.projectId = e.projectId || "";
947
+ }
948
+ static createDtoFromJson(e) {
949
+ switch (e.type) {
950
+ case "profile":
951
+ return new ue(e);
952
+ case "group":
953
+ return new he(e);
954
+ case "user":
955
+ return new be(e);
956
+ default:
957
+ throw new Error("Unknown DTO type");
958
+ }
959
+ }
960
+ static newInstance = () => new Ue({
961
+ id: J(),
962
+ tenantId: "",
963
+ companyId: "",
964
+ projectId: ""
965
+ });
966
+ };
967
+ b([
968
+ te()
969
+ ], Ne.prototype, "security");
970
+ b([
971
+ te()
972
+ ], Ne.prototype, "action");
973
+ let Tr = Ne;
974
+ class Me {
975
+ id;
976
+ code;
977
+ version;
978
+ createEntityDate;
979
+ updateEntityDate;
980
+ createdByUser;
981
+ lastModifiedByUser;
982
+ tenantId;
983
+ name;
984
+ description;
985
+ token;
986
+ user;
987
+ expirationDate;
988
+ revoked;
989
+ activated;
990
+ isNovoToken;
991
+ constructor(e) {
992
+ this.id = e.id || "", this.code = e.code || "", this.version = e.version || 0, this.createEntityDate = e.createEntityDate || "", this.updateEntityDate = e.updateEntityDate || "", this.createdByUser = e.createdByUser || "", this.lastModifiedByUser = e.lastModifiedByUser || "", this.tenantId = e.tenantId || "", this.user = e.user ? new be(e.user) : void 0, this.name = e.name || "", this.description = e.description || "", this.token = e.token || "", this.expirationDate = e.expirationDate, this.revoked = e.revoked, this.activated = e.activated || !1;
993
+ }
994
+ static newInstance = () => new Me({
995
+ id: J()
996
+ });
997
+ }
998
+ class Be {
999
+ id;
1000
+ code;
1001
+ version;
1002
+ createEntityDate;
1003
+ updateEntityDate;
1004
+ createdByUser;
1005
+ lastModifiedByUser;
1006
+ token;
1007
+ tokenType;
1008
+ revoked;
1009
+ expired;
1010
+ expirationTime;
1011
+ expirationDate;
1012
+ user;
1013
+ isNewAccessToken;
1014
+ constructor(e) {
1015
+ this.id = e.id || "", this.code = e.code || "", this.version = e.version || 0, this.createEntityDate = e.createEntityDate || (/* @__PURE__ */ new Date()).toISOString(), this.updateEntityDate = e.updateEntityDate || (/* @__PURE__ */ new Date()).toISOString(), this.createdByUser = e.createdByUser || "", this.lastModifiedByUser = e.lastModifiedByUser || "", this.token = e.token || "", this.tokenType = e.tokenType || void 0, this.user = e.user ? new be(e.user) : void 0, this.revoked = e.revoked || !1, this.expired = e.expired || !1, this.expirationTime = e.expirationTime || 0, this.expirationDate = e.expirationDate || "", this.isNewAccessToken = e.isNewAccessToken || !1;
1016
+ }
1017
+ static newInstance = () => new Be({
1018
+ id: J(),
1019
+ active: !0,
1020
+ isNewAccessToken: !0
1021
+ });
1022
+ }
1023
+ class dt extends ce {
1024
+ constructor(e) {
1025
+ super(e);
1026
+ }
1027
+ configureHeaders() {
1028
+ return V.getInstance().getHeaders();
1029
+ }
1030
+ transform(e) {
1031
+ return new be(e);
1032
+ }
1033
+ getEndpoint() {
1034
+ return "/api/v1/user";
1035
+ }
1036
+ getId(e) {
1037
+ return e.id;
1038
+ }
1039
+ isNewRecord(e) {
1040
+ return e.isNewUser;
1041
+ }
1042
+ async getUserByEmail(e) {
1043
+ const t = await this.client.get(
1044
+ `${this.getEndpoint()}/byEmail/${e}`,
1045
+ this.configureHeaders()
1046
+ );
1047
+ return this.transform(t);
1048
+ }
1049
+ }
1050
+ I.decorate(I.inject(H.ApiClient), dt, 0);
1051
+ I.decorate(I.injectable(), dt);
1052
+ class ut extends ce {
1053
+ constructor(e) {
1054
+ super(e);
1055
+ }
1056
+ configureHeaders() {
1057
+ return V.getInstance().getHeaders();
1058
+ }
1059
+ transform(e) {
1060
+ return new he(e);
1061
+ }
1062
+ getEndpoint() {
1063
+ return "/api/v1/group";
1064
+ }
1065
+ getId(e) {
1066
+ return e.id;
1067
+ }
1068
+ isNewRecord(e) {
1069
+ return e.isNewGroup;
1070
+ }
1071
+ }
1072
+ I.decorate(I.inject(H.ApiClient), ut, 0);
1073
+ I.decorate(I.injectable(), ut);
1074
+ class ht extends ce {
1075
+ constructor(e) {
1076
+ super(e);
1077
+ }
1078
+ configureHeaders() {
1079
+ return V.getInstance().getHeaders();
1080
+ }
1081
+ transform(e) {
1082
+ return new ue(e);
1083
+ }
1084
+ getEndpoint() {
1085
+ return "/api/v1/userProfile";
1086
+ }
1087
+ getId(e) {
1088
+ return e.id;
1089
+ }
1090
+ isNewRecord(e) {
1091
+ return e.isNewProfile;
1092
+ }
1093
+ }
1094
+ I.decorate(I.inject(H.ApiClient), ht, 0);
1095
+ I.decorate(I.injectable(), ht);
1096
+ class pt extends ce {
1097
+ constructor(e) {
1098
+ super(e);
1099
+ }
1100
+ configureHeaders() {
1101
+ return V.getInstance().getHeaders();
1102
+ }
1103
+ transform(e) {
1104
+ return new Me(e);
1105
+ }
1106
+ getEndpoint() {
1107
+ return "/api/v1/apiToken";
1108
+ }
1109
+ getId(e) {
1110
+ return e.id;
1111
+ }
1112
+ isNewRecord(e) {
1113
+ return e.isNovoToken;
1114
+ }
1115
+ async create(e, t, s, o) {
1116
+ const a = await this.client.post(
1117
+ `${this.getEndpoint()}/create?email=${e}&expirationDate=${t}&name=${s}&description=${o}`,
1118
+ void 0,
1119
+ this.configureHeaders()
1120
+ );
1121
+ return this.transform(a);
1122
+ }
1123
+ async revoke(e) {
1124
+ await this.client.post(
1125
+ `${this.getEndpoint()}/revoke?token=${e}`,
1126
+ void 0,
1127
+ this.configureHeaders()
1128
+ );
1129
+ }
1130
+ }
1131
+ I.decorate(I.inject(H.ApiClient), pt, 0);
1132
+ I.decorate(I.injectable(), pt);
1133
+ class ft extends ce {
1134
+ constructor(e) {
1135
+ super(e);
1136
+ }
1137
+ configureHeaders() {
1138
+ return V.getInstance().getHeaders();
1139
+ }
1140
+ transform(e) {
1141
+ return new Be(e);
1142
+ }
1143
+ getEndpoint() {
1144
+ return "/api/v1/accessToken";
1145
+ }
1146
+ getId(e) {
1147
+ return e.id;
1148
+ }
1149
+ isNewRecord(e) {
1150
+ return e.isNewAccessToken;
1151
+ }
1152
+ async revoke(e) {
1153
+ await this.client.post(
1154
+ `${this.getEndpoint()}/revoke?token=${e}`,
1155
+ void 0,
1156
+ this.configureHeaders()
1157
+ );
1158
+ }
1159
+ }
1160
+ I.decorate(I.inject(H.ApiClient), ft, 0);
1161
+ I.decorate(I.injectable(), ft);
1162
+ class mt extends ce {
1163
+ constructor(e) {
1164
+ super(e);
1165
+ }
1166
+ configureHeaders() {
1167
+ return V.getInstance().getHeaders();
1168
+ }
1169
+ transform(e) {
1170
+ return new ct(e);
1171
+ }
1172
+ getEndpoint() {
1173
+ return "/api/v1/resource";
1174
+ }
1175
+ getId(e) {
1176
+ return e.id;
1177
+ }
1178
+ isNewRecord(e) {
1179
+ return e.isNewResource;
1180
+ }
1181
+ getAllPermissionsAvailable() {
1182
+ return this.client.get(
1183
+ `${this.getEndpoint()}/permissions`,
1184
+ this.configureHeaders()
1185
+ );
1186
+ }
1187
+ getPermissionsBySecurityId(e, t) {
1188
+ return this.client.get(
1189
+ `${this.getEndpoint()}/permissions/security/${e}`,
1190
+ this.configureHeaders(),
1191
+ !1,
1192
+ {
1193
+ params: {
1194
+ type: je(ae, t)
1195
+ }
1196
+ }
1197
+ );
1198
+ }
1199
+ createPermission(e, t, s) {
1200
+ return this.client.post(
1201
+ `${this.getEndpoint()}/permissions`,
1202
+ {
1203
+ securityId: e,
1204
+ actionId: t,
1205
+ type: je(ae, s)
1206
+ },
1207
+ this.configureHeaders()
1208
+ );
1209
+ }
1210
+ deletePermission(e) {
1211
+ return this.client.delete(
1212
+ `${this.getEndpoint()}/permissions/${e}`,
1213
+ this.configureHeaders()
1214
+ );
1215
+ }
1216
+ registerResource(e) {
1217
+ return this.client.post(
1218
+ `${this.getEndpoint()}/register`,
1219
+ e,
1220
+ this.configureHeaders()
1221
+ );
1222
+ }
1223
+ }
1224
+ I.decorate(I.inject(H.ApiClient), mt, 0);
1225
+ I.decorate(I.injectable(), mt);
1226
+ function Cr({
1227
+ onLogin: r,
1228
+ error: e,
1229
+ onClickForgotPassword: t,
1230
+ loginLabel: s = "Email",
1231
+ loginPlaceholder: o,
1232
+ afterInputs: a,
1233
+ showMockUsersSelector: d = !1,
1234
+ mockUsers: i = [],
1235
+ mockUsersGroupMap: l,
1236
+ options: w = {},
1237
+ onChangeUsername: A,
1238
+ disabledLogin: p = !1,
1239
+ isCheckingUsername: P = !1,
1240
+ showSignIn: E = !0
1241
+ }) {
1242
+ const y = Ke(), {
1243
+ username: S,
1244
+ password: _,
1245
+ rememberMe: C,
1246
+ clearRememberMe: B
1247
+ } = kt(), [U, D] = m(S), [f, k] = m(_), [N, O] = m(C), [q, R] = m(!1), [W, Y] = m(null);
1248
+ z(() => {
1249
+ R(!!e);
1250
+ }, [e]), z(() => {
1251
+ S !== U && (D(S), A?.(S)), _ !== f && k(_), C !== N && O(C);
1252
+ }, [S, _, C]);
1253
+ const $ = () => {
1254
+ R(!1);
1255
+ }, X = () => {
1256
+ U && f && r(U, f, N).finally(() => R(!0));
1257
+ }, h = () => {
1258
+ if (!l)
1259
+ return i.map((g) => ({
1260
+ value: g.email,
1261
+ label: g.email
1262
+ }));
1263
+ const c = i.reduce((g, T) => {
1264
+ const j = l[T.type];
1265
+ return j && (g[j] || (g[j] = []), g[j].push({
1266
+ value: T.email,
1267
+ label: T.email
1268
+ })), g;
1269
+ }, {});
1270
+ return Object.entries(c).map(([g, T]) => ({
1271
+ group: g,
1272
+ items: T
1273
+ }));
1274
+ }, n = () => {
1275
+ if (W) {
1276
+ const c = i.find((g) => g.email === W);
1277
+ c && (D(c.email), k(c.password), $());
1278
+ }
1279
+ }, v = {
1280
+ withBorder: !0,
1281
+ shadow: "md",
1282
+ p: 30,
1283
+ mt: 30,
1284
+ radius: "md",
1285
+ w: 400,
1286
+ ...w.cardProps
1287
+ };
1288
+ return /* @__PURE__ */ L(
1289
+ Je,
1290
+ {
1291
+ ...v,
1292
+ pos: "relative",
1293
+ ref: y,
1294
+ children: [
1295
+ E && /* @__PURE__ */ L(re, { children: [
1296
+ /* @__PURE__ */ u(
1297
+ ne,
1298
+ {
1299
+ c: "light-dark(var(--mantine-color-black), var(--mantine-color-white))",
1300
+ fw: 800,
1301
+ fz: { base: "20px", md: "35px" },
1302
+ style: { textAlign: "center", letterSpacing: "-1px" },
1303
+ mt: "xs",
1304
+ children: x().t("archbase:signIn")
1305
+ }
1306
+ ),
1307
+ /* @__PURE__ */ u(ge, { m: "md" })
1308
+ ] }),
1309
+ w?.customContentBefore,
1310
+ d && /* @__PURE__ */ L(re, { children: [
1311
+ /* @__PURE__ */ L(Ve, { gap: "sm", mb: "md", children: [
1312
+ /* @__PURE__ */ u(
1313
+ _t,
1314
+ {
1315
+ placeholder: "Selecione um usuário mock",
1316
+ data: h(),
1317
+ value: W,
1318
+ onChange: Y,
1319
+ searchable: !0,
1320
+ clearable: !0,
1321
+ style: { flexGrow: 1 }
1322
+ }
1323
+ ),
1324
+ /* @__PURE__ */ u(Rt, { label: "Aplicar", children: /* @__PURE__ */ u(
1325
+ ie,
1326
+ {
1327
+ variant: "light",
1328
+ size: "sm",
1329
+ onClick: n,
1330
+ disabled: !W,
1331
+ "aria-label": "Aplicar usuário mock selecionado",
1332
+ children: /* @__PURE__ */ u(Lt, { size: 16 })
1333
+ }
1334
+ ) })
1335
+ ] }),
1336
+ /* @__PURE__ */ u(ge, { mb: "md" })
1337
+ ] }),
1338
+ /* @__PURE__ */ u(
1339
+ Pe,
1340
+ {
1341
+ label: s,
1342
+ placeholder: o ?? x().t("archbase:usuario@email.com"),
1343
+ rightSection: P ? /* @__PURE__ */ u(Nt, { size: "xs" }) : null,
1344
+ value: U || "",
1345
+ required: !0,
1346
+ onChange: (c) => {
1347
+ D(c.currentTarget.value), A?.(c.currentTarget.value), $();
1348
+ }
1349
+ }
1350
+ ),
1351
+ /* @__PURE__ */ u(
1352
+ Te,
1353
+ {
1354
+ label: x().t("archbase:Password"),
1355
+ placeholder: x().t("archbase:Sua senha"),
1356
+ onChange: (c) => {
1357
+ k(c.currentTarget.value), $();
1358
+ },
1359
+ value: f || "",
1360
+ required: !0,
1361
+ mt: "md"
1362
+ }
1363
+ ),
1364
+ /* @__PURE__ */ L(Ve, { justify: "space-between", mt: "md", children: [
1365
+ /* @__PURE__ */ u(
1366
+ Mt,
1367
+ {
1368
+ label: x().t("archbase:Lembre-me"),
1369
+ checked: N,
1370
+ onChange: (c) => {
1371
+ const g = c.currentTarget.checked;
1372
+ O(g), g || B();
1373
+ }
1374
+ }
1375
+ ),
1376
+ t && /* @__PURE__ */ u(
1377
+ Bt,
1378
+ {
1379
+ component: "button",
1380
+ c: "var(--mantine-text-color)",
1381
+ fz: 14,
1382
+ lh: "20px",
1383
+ styles: { root: { cursor: "pointer" } },
1384
+ onClick: t,
1385
+ children: x().t("archbase:Esqueci minha senha")
1386
+ }
1387
+ )
1388
+ ] }),
1389
+ w?.afterInputs || a,
1390
+ /* @__PURE__ */ u(
1391
+ ie,
1392
+ {
1393
+ disabled: !f || !U || p,
1394
+ fullWidth: !0,
1395
+ mt: "xl",
1396
+ onClick: X,
1397
+ children: x().t("archbase:signIn")
1398
+ }
1399
+ ),
1400
+ w?.customContentAfter,
1401
+ q && e && /* @__PURE__ */ u(ne, { c: "red", mt: "sm", children: e })
1402
+ ]
1403
+ }
1404
+ );
1405
+ }
1406
+ const nr = {
1407
+ position: "relative",
1408
+ width: "90%",
1409
+ maxWidth: 400,
1410
+ padding: 30,
1411
+ marginTop: 30
1412
+ };
1413
+ function Ur({ error: r, onSendResetPasswordEmail: e, onResetPassword: t, onClickBackToLogin: s, validatePassword: o, validateToken: a, initialEmail: d = "", description: i, style: l }) {
1414
+ const w = Ke(), A = It(), { colorScheme: p } = Ot(), [P, E] = m(r ?? ""), [y, S] = m(d), [_, C] = m(""), [B, U] = m(""), [D, f] = m(""), [k, N] = m(!1), [O, q] = m(""), [R, W] = m(""), [Y, $] = m(""), [X, h] = m("");
1415
+ async function n(c) {
1416
+ c && (Pt(c) ? await e(c).then(() => {
1417
+ ze.showSuccess(`${x().t("archbase:Um e-mail com instruções para redefinir sua senha foi enviado. Verifique sua caixa de entrada.")}`), N(!0);
1418
+ }).catch(() => {
1419
+ }) : q(`${x().t("archbase:Email inválido")}`));
1420
+ }
1421
+ async function v(c, g, T, j) {
1422
+ if (c && g && T) {
1423
+ let Ae = "", Ee = "", $e = "";
1424
+ a && (Ae = a(), $(Ae)), o && (Ee = o(), $(Ee)), T !== j && ($e = `${x().t("archbase:A nova senha e a confirmação devem ser iguais.")}`, h($e)), !Ee && !Ae && await t(c, g, T).then(() => {
1425
+ ze.showSuccess(`${x().t("archbase:Senha redefinida com sucesso.")}`), s(), N(!1);
1426
+ }).catch(() => {
1427
+ E(r || `${x().t("archbase:Erro ao redefinir senha.")}`);
1428
+ });
1429
+ }
1430
+ }
1431
+ return z(() => {
1432
+ r && E(r);
1433
+ }, [r]), z(() => {
1434
+ E("");
1435
+ }, [y, _, B, D]), /* @__PURE__ */ L(
1436
+ Je,
1437
+ {
1438
+ withBorder: !0,
1439
+ shadow: "md",
1440
+ radius: "md",
1441
+ ref: w,
1442
+ style: {
1443
+ ...nr,
1444
+ ...l
1445
+ },
1446
+ children: [
1447
+ k ? /* @__PURE__ */ L(re, { children: [
1448
+ /* @__PURE__ */ u(
1449
+ ne,
1450
+ {
1451
+ c: "light-dark(var(--mantine-color-black), var(--mantine-color-white))",
1452
+ fw: 800,
1453
+ fz: { base: "20px", md: "35px" },
1454
+ style: { textAlign: "center", letterSpacing: "-1px" },
1455
+ mt: "xs",
1456
+ children: x().t("archbase:Redefinir senha")
1457
+ }
1458
+ ),
1459
+ /* @__PURE__ */ u(ge, { m: "xs" }),
1460
+ /* @__PURE__ */ u(
1461
+ Pe,
1462
+ {
1463
+ label: x().t("archbase:Código de segurança"),
1464
+ placeholder: `${x().t("archbase:Código enviado no seu e-mail")}`,
1465
+ value: _ || "",
1466
+ required: !0,
1467
+ onChange: (c) => {
1468
+ C(c.currentTarget.value), W("");
1469
+ },
1470
+ error: R
1471
+ }
1472
+ ),
1473
+ /* @__PURE__ */ u(
1474
+ Te,
1475
+ {
1476
+ label: x().t("archbase:Nova senha"),
1477
+ placeholder: x().t("archbase:Nova senha"),
1478
+ onChange: (c) => {
1479
+ U(c.currentTarget.value), $(""), h("");
1480
+ },
1481
+ value: B,
1482
+ required: !0,
1483
+ error: Y
1484
+ }
1485
+ ),
1486
+ /* @__PURE__ */ u(
1487
+ Te,
1488
+ {
1489
+ label: x().t("archbase:Confirmar senha"),
1490
+ placeholder: x().t("archbase:Confirmar senha"),
1491
+ onChange: (c) => {
1492
+ f(c.currentTarget.value), h("");
1493
+ },
1494
+ value: D || "",
1495
+ required: !0,
1496
+ error: X
1497
+ }
1498
+ ),
1499
+ /* @__PURE__ */ u(
1500
+ ie,
1501
+ {
1502
+ disabled: !y || !_ || !B || !D,
1503
+ mt: "md",
1504
+ fullWidth: !0,
1505
+ onClick: () => v(y, _, B, D),
1506
+ children: `${x().t("archbase:Redefinir senha")}`
1507
+ }
1508
+ ),
1509
+ /* @__PURE__ */ u(
1510
+ ie,
1511
+ {
1512
+ mt: "6px",
1513
+ fullWidth: !0,
1514
+ color: p === "dark" ? A.colors.dark[4] : A.colors.gray[7],
1515
+ onClick: () => {
1516
+ O || N(!1);
1517
+ },
1518
+ children: `${x().t("archbase:Voltar")}`
1519
+ }
1520
+ )
1521
+ ] }) : /* @__PURE__ */ L(re, { children: [
1522
+ /* @__PURE__ */ u(
1523
+ ne,
1524
+ {
1525
+ c: "light-dark(var(--mantine-color-black), var(--mantine-color-white))",
1526
+ fw: 800,
1527
+ fz: { base: "20px", md: "35px" },
1528
+ style: { textAlign: "center", letterSpacing: "-1px" },
1529
+ mt: "xs",
1530
+ children: x().t("archbase:Redefinir senha")
1531
+ }
1532
+ ),
1533
+ /* @__PURE__ */ u(ne, { c: "dimmed", fz: 14, style: { textAlign: "justify" }, children: i }),
1534
+ /* @__PURE__ */ u(ge, { m: "md" }),
1535
+ /* @__PURE__ */ u(
1536
+ Pe,
1537
+ {
1538
+ label: "Email",
1539
+ placeholder: `${x().t("archbase:usuario@email.com")}`,
1540
+ value: y || "",
1541
+ required: !0,
1542
+ onChange: (c) => {
1543
+ S(c.currentTarget.value), q("");
1544
+ },
1545
+ error: O
1546
+ }
1547
+ ),
1548
+ /* @__PURE__ */ u(
1549
+ ie,
1550
+ {
1551
+ disabled: !y,
1552
+ mt: "md",
1553
+ fullWidth: !0,
1554
+ onClick: () => n(y),
1555
+ children: `${x().t("archbase:Enviar")}`
1556
+ }
1557
+ ),
1558
+ /* @__PURE__ */ u(
1559
+ ie,
1560
+ {
1561
+ mt: "6px",
1562
+ fullWidth: !0,
1563
+ color: p === "dark" ? A.colors.dark[4] : A.colors.gray[7],
1564
+ onClick: () => s && s(),
1565
+ children: `${x().t("archbase:Voltar")}`
1566
+ }
1567
+ )
1568
+ ] }),
1569
+ P ? /* @__PURE__ */ u(ne, { c: "red", style: { textAlign: "justify" }, children: P }) : null
1570
+ ]
1571
+ }
1572
+ );
1573
+ }
1574
+ const ir = () => Tt().user, gt = "archbaseSecurityManagerStore", ar = (r, e, t, s) => r && r.existsValue(e) ? r.getValue(e) : new tt(e, t, s), Dr = ({ resourceName: r, resourceDescription: e, enableSecurity: t = !0 }) => {
1575
+ const s = Ge(gt), o = ir(), [a, d] = m({
1576
+ securityManager: t && ar(s, r, e, o.isAdmin)
1577
+ });
1578
+ return z(() => {
1579
+ t && s.setValue(r, a.securityManager);
1580
+ }, [r]), { securityManager: a.securityManager };
1581
+ }, _r = ({
1582
+ checkIntervalTokenHasExpired: r = 3e4,
1583
+ // Verificar a 30 segundos
1584
+ expirationThresholdOfToken: e = 300
1585
+ // Antecipar em 5 minutos
1586
+ }) => {
1587
+ const t = ye(
1588
+ (n) => n.get(H.TokenManager)
1589
+ ), s = ye(
1590
+ (n) => n.get(H.Authenticator)
1591
+ ), [o, a] = m(null), [d, i] = m(!1), [l, w] = m(!0), [A, p] = m(!1), [P, E] = m(!1), [y, S] = m(""), [_, C] = m(""), [B, U] = m(null), D = Ge(gt), f = {
1592
+ hasContextualLogin: typeof s.loginWithContext == "function",
1593
+ hasFlexibleLogin: typeof s.loginFlexible == "function",
1594
+ hasSocialLogin: typeof s.loginSocial == "function",
1595
+ hasRegistration: typeof s.register == "function",
1596
+ hasContextSupport: typeof t.saveContext == "function"
1597
+ };
1598
+ z(() => {
1599
+ const n = t.getUsername();
1600
+ if (n && n != "" && C(n), f.hasContextSupport && t.getContext) {
1601
+ const c = t.getContext();
1602
+ if (c)
1603
+ try {
1604
+ const g = typeof c == "string" ? JSON.parse(c) : c;
1605
+ U(g);
1606
+ } catch (g) {
1607
+ console.warn("Erro ao carregar contexto salvo:", g);
1608
+ }
1609
+ }
1610
+ const v = t.getToken();
1611
+ v && (p(!0), S(""), E(!1), a(v)), w(!1);
1612
+ }, []);
1613
+ const k = () => {
1614
+ E(!1), S("");
1615
+ }, N = (n) => {
1616
+ i(!1), p(!1), t.clearToken(), n && t.clearUsernameAndPassword(), f.hasContextSupport && t.clearContext && t.clearContext(), C(""), U(null), S(""), E(!1), D.clearAllValues();
1617
+ }, O = async (n, v, c) => {
1618
+ try {
1619
+ i(!0), p(!1);
1620
+ const g = await s.login(n, v);
1621
+ t.saveToken(g), c && t.saveUsernameAndPassword(n, v), t.saveUsername(n), C(n), a(g), i(!1), p(!0);
1622
+ } catch (g) {
1623
+ i(!1), p(!1), S(ee(g)), E(!0);
1624
+ }
1625
+ }, q = async (n, v = !1) => {
1626
+ if (!f.hasContextualLogin || !s.loginWithContext)
1627
+ throw new Error("Login contextual não suportado por esta implementação do ArchbaseAuthenticator");
1628
+ try {
1629
+ i(!0), p(!1);
1630
+ const { context: c, user: g, ...T } = await s.loginWithContext(n), j = {
1631
+ scope: "",
1632
+ ext_expires_in: T.expires_in,
1633
+ ...T
1634
+ };
1635
+ t.saveToken(j), v ? t.saveUsernameAndPassword(n.email, n.password) : t.clearUsernameAndPassword(), t.saveUsername(n.email), f.hasContextSupport && t.saveContext && c && (t.saveContext(JSON.stringify(c)), U(c)), C(n.email), a(j), i(!1), p(!0);
1636
+ } catch (c) {
1637
+ throw i(!1), p(!1), S(ee(c)), E(!0), c;
1638
+ }
1639
+ }, R = async (n, v = !1) => {
1640
+ if (!f.hasFlexibleLogin || !s.loginFlexible)
1641
+ throw new Error("Login flexível não suportado por esta implementação do ArchbaseAuthenticator");
1642
+ try {
1643
+ i(!0), p(!1);
1644
+ const { context: c, user: g, ...T } = await s.loginFlexible(n), j = {
1645
+ scope: "",
1646
+ ext_expires_in: T.expires_in,
1647
+ ...T
1648
+ };
1649
+ t.saveToken(j), v && t.saveUsernameAndPassword(n.identifier, n.password), t.saveUsername(g.email || n.identifier), f.hasContextSupport && t.saveContext && c && (t.saveContext(JSON.stringify(c)), U(c)), C(g.email || n.identifier), a(j), i(!1), p(!0);
1650
+ } catch (c) {
1651
+ throw i(!1), p(!1), S(ee(c)), E(!0), c;
1652
+ }
1653
+ }, W = async (n) => {
1654
+ if (!f.hasSocialLogin || !s.loginSocial)
1655
+ throw new Error("Login social não suportado por esta implementação do ArchbaseAuthenticator");
1656
+ try {
1657
+ i(!0), p(!1);
1658
+ const { context: v, user: c, ...g } = await s.loginSocial(n), T = {
1659
+ scope: "",
1660
+ ext_expires_in: g.expires_in,
1661
+ ...g
1662
+ };
1663
+ t.saveToken(T), t.saveUsername(c.email), f.hasContextSupport && t.saveContext && v && (t.saveContext(JSON.stringify(v)), U(v)), C(c.email), a(T), i(!1), p(!0);
1664
+ } catch (v) {
1665
+ throw i(!1), p(!1), S(ee(v)), E(!0), v;
1666
+ }
1667
+ }, Y = async (n) => {
1668
+ if (!f.hasRegistration || !s.register)
1669
+ throw new Error("Registro não suportado por esta implementação do ArchbaseAuthenticator");
1670
+ try {
1671
+ i(!0);
1672
+ const v = await s.register(n);
1673
+ return i(!1), v;
1674
+ } catch (v) {
1675
+ throw i(!1), S(ee(v)), E(!0), v;
1676
+ }
1677
+ }, $ = async () => s.getSupportedContexts ? await s.getSupportedContexts() : { supportedContexts: ["DEFAULT"], defaultContext: "DEFAULT" }, X = async (n) => s.validateContext ? await s.validateContext(n) : { context: n, supported: n === "DEFAULT" };
1678
+ z(() => {
1679
+ const n = setInterval(() => {
1680
+ o && o.access_token && t.isTokenExpired(o, e) && h();
1681
+ }, r);
1682
+ return () => {
1683
+ clearInterval(n);
1684
+ };
1685
+ }, [o]);
1686
+ const h = async () => {
1687
+ if (o)
1688
+ try {
1689
+ const n = await s.refreshToken(o?.refresh_token);
1690
+ t.saveToken(n), a(n);
1691
+ } catch (n) {
1692
+ console.error("Erro ao renovar o token:", n), N();
1693
+ }
1694
+ };
1695
+ return {
1696
+ // Métodos básicos (compatibilidade)
1697
+ login: O,
1698
+ logout: N,
1699
+ username: _,
1700
+ isAuthenticated: A,
1701
+ isAuthenticating: d,
1702
+ isInitializing: l,
1703
+ isError: P,
1704
+ error: y,
1705
+ clearError: k,
1706
+ accessToken: o ? o.access_token : null,
1707
+ // Métodos opcionais para autenticação avançada
1708
+ loginWithContext: f.hasContextualLogin ? q : void 0,
1709
+ loginFlexible: f.hasFlexibleLogin ? R : void 0,
1710
+ loginSocial: f.hasSocialLogin ? W : void 0,
1711
+ register: f.hasRegistration ? Y : void 0,
1712
+ getSupportedContexts: $,
1713
+ validateContext: X,
1714
+ // Informações de contexto
1715
+ context: B,
1716
+ // Detecção de capacidades
1717
+ capabilities: f
1718
+ };
1719
+ }, Rr = () => {
1720
+ const r = ye(
1721
+ (s) => s.get(H.TokenManager)
1722
+ ), [e, t] = m(null);
1723
+ return z(() => {
1724
+ const s = r.getToken();
1725
+ s && t(s.access_token);
1726
+ }, []), {
1727
+ token: e
1728
+ };
1729
+ }, Nr = () => {
1730
+ const r = ye(
1731
+ (l) => l.get(H.Authenticator)
1732
+ ), [e, t] = m(!1), [s, o] = m("");
1733
+ return {
1734
+ sendResetPasswordEmail: async (l) => {
1735
+ try {
1736
+ return await r.sendResetPasswordEmail(l);
1737
+ } catch (w) {
1738
+ throw o(ee(w)), t(!0), w;
1739
+ }
1740
+ },
1741
+ resetPassword: async (l, w, A) => {
1742
+ try {
1743
+ return await r.resetPassword(l, w, A);
1744
+ } catch (p) {
1745
+ throw o(ee(p)), t(!0), p;
1746
+ }
1747
+ },
1748
+ isError: e,
1749
+ error: s,
1750
+ clearError: () => {
1751
+ t(!1), o("");
1752
+ }
1753
+ };
1754
+ }, Oe = De(null), Mr = ({
1755
+ children: r,
1756
+ user: e,
1757
+ onError: t
1758
+ }) => {
1759
+ const [s, o] = m(!1), [a, d] = m(null), [i] = m([]), l = e?.isAdministrator || !1, w = pe((y) => l ? !0 : i.includes(y), [i, l]), A = pe((y) => l ? !0 : y.some((S) => i.includes(S)), [i, l]), p = pe((y) => l ? !0 : y.every((S) => i.includes(S)), [i, l]), P = pe((y) => {
1760
+ d(y), y && t && t(y);
1761
+ }, [t]), E = {
1762
+ user: e,
1763
+ isLoading: s,
1764
+ hasGlobalPermission: w,
1765
+ hasAnyGlobalPermission: A,
1766
+ hasAllGlobalPermissions: p,
1767
+ isAdmin: l,
1768
+ error: a,
1769
+ setError: P
1770
+ };
1771
+ return /* @__PURE__ */ u(Oe.Provider, { value: E, children: r });
1772
+ }, yt = De(null), cr = ({
1773
+ children: r,
1774
+ resourceName: e,
1775
+ resourceDescription: t,
1776
+ requiredPermissions: s = [],
1777
+ fallbackComponent: o,
1778
+ onSecurityReady: a,
1779
+ onError: d
1780
+ }) => {
1781
+ const i = _e(Oe);
1782
+ if (!i)
1783
+ throw new Error("ArchbaseViewSecurityProvider deve ser usado dentro de um ArchbaseSecurityProvider");
1784
+ const { user: l, isAdmin: w } = i, [A, p] = m(null), [P, E] = m(!0), [y, S] = m(null);
1785
+ if (He.useEffect(() => {
1786
+ if (!l) {
1787
+ E(!1);
1788
+ return;
1789
+ }
1790
+ const f = new tt(e, t, w);
1791
+ (async () => {
1792
+ E(!0);
1793
+ try {
1794
+ await f.apply(() => {
1795
+ p(f), E(!1), a && a(f);
1796
+ });
1797
+ } catch {
1798
+ const O = f.getError() || "Erro ao carregar permissões";
1799
+ S(O), E(!1), d && d(O);
1800
+ }
1801
+ })();
1802
+ }, [e, t, l, w, a, d]), P)
1803
+ return /* @__PURE__ */ u("div", { className: "archbase-security-loading", children: /* @__PURE__ */ u("div", { children: "Carregando permissões..." }) });
1804
+ if (y)
1805
+ return /* @__PURE__ */ u("div", { className: "archbase-security-error", children: /* @__PURE__ */ L("div", { children: [
1806
+ "Erro ao carregar permissões: ",
1807
+ y
1808
+ ] }) });
1809
+ if (!l)
1810
+ return o || /* @__PURE__ */ u("div", { className: "archbase-security-no-user", children: /* @__PURE__ */ u("div", { children: "É necessário fazer login para acessar esta área" }) });
1811
+ if (s.length > 0 && A && !s.every(
1812
+ (k) => A.hasPermission(k)
1813
+ ))
1814
+ return o || /* @__PURE__ */ L("div", { className: "archbase-security-access-denied", children: [
1815
+ /* @__PURE__ */ u("div", { children: "Você não possui permissão para acessar esta área" }),
1816
+ /* @__PURE__ */ L("small", { children: [
1817
+ "Permissões necessárias: ",
1818
+ s.join(", ")
1819
+ ] })
1820
+ ] });
1821
+ const D = {
1822
+ securityManager: A,
1823
+ hasPermission: (f) => A?.hasPermission(f) || !1,
1824
+ hasAnyPermission: (f) => f.some((k) => A?.hasPermission(k) || !1),
1825
+ hasAllPermissions: (f) => f.every((k) => A?.hasPermission(k) || !1),
1826
+ registerAction: (f, k) => {
1827
+ A?.registerAction(f, k);
1828
+ },
1829
+ isLoading: P,
1830
+ error: y
1831
+ };
1832
+ return /* @__PURE__ */ u(yt.Provider, { value: D, children: r });
1833
+ }, lr = () => {
1834
+ const r = _e(Oe);
1835
+ if (!r)
1836
+ throw new Error("useArchbaseSecurity deve ser usado dentro de um ArchbaseSecurityProvider");
1837
+ return r;
1838
+ }, Le = () => {
1839
+ const r = _e(yt);
1840
+ if (!r)
1841
+ throw new Error("useArchbaseViewSecurity deve ser usado dentro de um ArchbaseViewSecurityProvider");
1842
+ return r;
1843
+ }, Br = (r, e) => {
1844
+ const t = Le(), { hasPermission: s, hasAnyPermission: o, hasAllPermissions: a, registerAction: d, securityManager: i, isLoading: l, error: w } = t;
1845
+ return He.useEffect(() => {
1846
+ r && e && (d("create", `Criar ${e}`), d("edit", `Editar ${e}`), d("delete", `Deletar ${e}`), d("view", `Visualizar ${e}`), d("list", `Listar ${e}`));
1847
+ }, [r, e, d]), {
1848
+ hasPermission: s,
1849
+ hasAnyPermission: o,
1850
+ hasAllPermissions: a,
1851
+ registerAction: d,
1852
+ securityManager: i,
1853
+ canCreate: s("create"),
1854
+ canEdit: s("edit"),
1855
+ canDelete: s("delete"),
1856
+ canView: s("view"),
1857
+ canList: s("list"),
1858
+ isLoading: l,
1859
+ error: w
1860
+ };
1861
+ }, Or = () => {
1862
+ const r = Le();
1863
+ return {
1864
+ check: r.hasPermission,
1865
+ checkAny: r.hasAnyPermission,
1866
+ checkAll: r.hasAllPermissions,
1867
+ isAdmin: lr().isAdmin
1868
+ };
1869
+ }, wt = ({
1870
+ children: r,
1871
+ actionName: e,
1872
+ requiredPermissions: t = [],
1873
+ requireAll: s = !0,
1874
+ actionDescription: o,
1875
+ fallback: a = null,
1876
+ autoRegister: d = !0
1877
+ }) => {
1878
+ const { hasPermission: i, hasAnyPermission: l, hasAllPermissions: w, registerAction: A } = Le();
1879
+ z(() => {
1880
+ d && e && o && A(e, o);
1881
+ }, [e, o, d, A]);
1882
+ let p = !1;
1883
+ return e ? p = i(e) : t.length > 0 ? p = s ? w(t) : l(t) : p = !0, p ? /* @__PURE__ */ u(re, { children: r }) : /* @__PURE__ */ u(re, { children: a });
1884
+ }, Lr = ({
1885
+ actionName: r,
1886
+ actionDescription: e,
1887
+ children: t,
1888
+ onClick: s,
1889
+ disabled: o = !1,
1890
+ className: a = "",
1891
+ style: d = {},
1892
+ variant: i = "primary",
1893
+ size: l = "medium",
1894
+ type: w = "button"
1895
+ }) => {
1896
+ const A = () => {
1897
+ const P = "archbase-secure-btn", E = `archbase-secure-btn--${i}`, y = `archbase-secure-btn--${l}`;
1898
+ return `${P} ${E} ${y} ${a}`.trim();
1899
+ }, p = () => {
1900
+ const P = {
1901
+ small: { padding: "4px 8px", fontSize: "12px" },
1902
+ medium: { padding: "8px 16px", fontSize: "14px" },
1903
+ large: { padding: "12px 24px", fontSize: "16px" }
1904
+ }, E = {
1905
+ primary: { backgroundColor: "#007bff", color: "white" },
1906
+ secondary: { backgroundColor: "#6c757d", color: "white" },
1907
+ danger: { backgroundColor: "#dc3545", color: "white" },
1908
+ success: { backgroundColor: "#28a745", color: "white" },
1909
+ warning: { backgroundColor: "#ffc107", color: "#212529" }
1910
+ };
1911
+ return {
1912
+ border: "none",
1913
+ borderRadius: "4px",
1914
+ cursor: o ? "not-allowed" : "pointer",
1915
+ fontWeight: "500",
1916
+ opacity: o ? 0.6 : 1,
1917
+ ...P[l],
1918
+ ...E[i],
1919
+ ...d
1920
+ };
1921
+ };
1922
+ return /* @__PURE__ */ u(
1923
+ wt,
1924
+ {
1925
+ actionName: r,
1926
+ actionDescription: e,
1927
+ fallback: null,
1928
+ children: /* @__PURE__ */ u(
1929
+ "button",
1930
+ {
1931
+ type: w,
1932
+ onClick: s,
1933
+ disabled: o,
1934
+ className: A(),
1935
+ style: p(),
1936
+ children: t
1937
+ }
1938
+ )
1939
+ }
1940
+ );
1941
+ }, $r = ({
1942
+ children: r,
1943
+ actionName: e,
1944
+ actionDescription: t,
1945
+ showLabel: s = !0,
1946
+ label: o,
1947
+ fallbackText: a = "Campo não disponível",
1948
+ fallbackComponent: d
1949
+ }) => e ? /* @__PURE__ */ u(
1950
+ wt,
1951
+ {
1952
+ actionName: e,
1953
+ actionDescription: t,
1954
+ fallback: d || /* @__PURE__ */ L("div", { className: "archbase-secure-field-fallback", style: {
1955
+ padding: "8px",
1956
+ color: "#666",
1957
+ fontStyle: "italic",
1958
+ backgroundColor: "#f8f9fa",
1959
+ border: "1px dashed #dee2e6",
1960
+ borderRadius: "4px"
1961
+ }, children: [
1962
+ s && o && /* @__PURE__ */ L("label", { style: { fontWeight: "bold" }, children: [
1963
+ o,
1964
+ ": "
1965
+ ] }),
1966
+ a
1967
+ ] }),
1968
+ children: r
1969
+ }
1970
+ ) : /* @__PURE__ */ u(re, { children: r });
1971
+ function jr(r, e) {
1972
+ return function(s) {
1973
+ const { resourceName: o, resourceDescription: a, requiredPermissions: d, fallbackComponent: i } = e;
1974
+ return /* @__PURE__ */ u(
1975
+ cr,
1976
+ {
1977
+ resourceName: o,
1978
+ resourceDescription: a,
1979
+ requiredPermissions: d,
1980
+ fallbackComponent: i,
1981
+ children: /* @__PURE__ */ u(r, { ...s })
1982
+ }
1983
+ );
1984
+ };
1985
+ }
1986
+ export {
1987
+ gt as ARCHBASE_SECURITY_MANAGER_STORE,
1988
+ sr as AccessIntervalDto,
1989
+ ot as AccessScheduleDto,
1990
+ Be as AccessTokenDto,
1991
+ or as ActionDto,
1992
+ Me as ApiTokenDto,
1993
+ ft as ArchbaseAccessTokenService,
1994
+ pt as ArchbaseApiTokenService,
1995
+ er as ArchbaseAuthContext,
1996
+ Ir as ArchbaseAuthProvider,
1997
+ ut as ArchbaseGroupService,
1998
+ Cr as ArchbaseLogin,
1999
+ ht as ArchbaseProfileService,
2000
+ wt as ArchbaseProtectedComponent,
2001
+ Ur as ArchbaseResetPassword,
2002
+ mt as ArchbaseResourceService,
2003
+ Lr as ArchbaseSecureActionButton,
2004
+ $r as ArchbaseSecureFormField,
2005
+ tt as ArchbaseSecurityManager,
2006
+ Mr as ArchbaseSecurityProvider,
2007
+ V as ArchbaseTenantManager,
2008
+ qe as ArchbaseUser,
2009
+ dt as ArchbaseUserService,
2010
+ Ye as ArchbaseUsernameAndPassword,
2011
+ Ye as ArchbaseUsernameAndPasswordImpl,
2012
+ cr as ArchbaseViewSecurityProvider,
2013
+ Ie as CONTEXT_STORAGE_KEY,
2014
+ $t as DefaultArchbaseTokenManager,
2015
+ Q as ENCRYPTION_KEY,
2016
+ Qe as FetchError,
2017
+ he as GroupDto,
2018
+ Tr as PermissionDto,
2019
+ ue as ProfileDto,
2020
+ ct as ResourceDto,
2021
+ le as SecurityDto,
2022
+ ae as SecurityType,
2023
+ xe as TOKEN_COOKIE_NAME,
2024
+ rr as TipoRecurso,
2025
+ ke as USER_NAME,
2026
+ Se as USER_NAME_AND_PASSWORD,
2027
+ be as UserDto,
2028
+ Re as UserGroupDto,
2029
+ Yt as createInternalConfig,
2030
+ me as decodeJWT,
2031
+ se as epochAtSecondsFromNow,
2032
+ We as epochTimeIsPast,
2033
+ Gt as fetchTokens,
2034
+ Jt as fetchWithRefreshToken,
2035
+ Ft as generateCodeChallenge,
2036
+ jt as generateRandomString,
2037
+ Xe as getRandomInteger,
2038
+ Zt as getRefreshExpiresIn,
2039
+ zt as postWithXForm,
2040
+ Wt as redirectToLogin,
2041
+ Kt as redirectToLogout,
2042
+ _r as useArchbaseAuthenticationManager,
2043
+ Rr as useArchbaseGetCurrentToken,
2044
+ ir as useArchbaseGetLoggedUser,
2045
+ Or as useArchbasePermissionCheck,
2046
+ Nr as useArchbaseResetPassword,
2047
+ Br as useArchbaseSecureForm,
2048
+ lr as useArchbaseSecurity,
2049
+ Dr as useArchbaseSecurityManager,
2050
+ Pr as useArchbaseTenantManager,
2051
+ Le as useArchbaseViewSecurity,
2052
+ kr as useBrowserStorage,
2053
+ Xt as validateConfig,
2054
+ qt as validateState,
2055
+ jr as withArchbaseSecurity
2056
+ };