alex-evo-sh-auth 0.0.15 → 0.0.17

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.
@@ -1,6 +1,6 @@
1
- import fe, { createContext as de, useState as I, useMemo as me, useCallback as j, useEffect as C, useContext as B } from "react";
1
+ import ue, { createContext as fe, useState as I, useCallback as j, useEffect as N, useContext as B, useRef as de } from "react";
2
2
  import { Outlet as H } from "react-router-dom";
3
- async function he(r) {
3
+ async function me(r) {
4
4
  const t = await fetch(`${r.authServer}/refresh`, {
5
5
  method: "POST",
6
6
  headers: {
@@ -16,10 +16,11 @@ async function he(r) {
16
16
  const o = await t.json();
17
17
  return localStorage.setItem(r.baseKey + "_access", o.access), o.access;
18
18
  }
19
- class ge {
19
+ class Se {
20
20
  constructor(t, o) {
21
21
  this.onAuthFail = o, this.config = t;
22
22
  }
23
+ onAuthFail;
23
24
  refreshPromise = null;
24
25
  config;
25
26
  getToken() {
@@ -30,52 +31,67 @@ class ge {
30
31
  }
31
32
  async getValidToken() {
32
33
  let t = this.getToken();
33
- return t || (this.refreshPromise || (this.refreshPromise = he(this.config).then((o) => (this.setToken(o), o)).finally(() => {
34
+ return t || (this.refreshPromise || (this.refreshPromise = me(this.config).then((o) => (this.setToken(o), o)).finally(() => {
34
35
  this.refreshPromise = null;
35
36
  })), t = await this.refreshPromise, !t && this.onAuthFail && this.onAuthFail(), t);
36
37
  }
37
38
  }
38
- class we {
39
+ class ke {
39
40
  authServer;
40
41
  clientId;
41
42
  redirectUri;
42
43
  homePage;
43
44
  baseKey;
44
- constructor(t, o, s, a, c) {
45
- this.authServer = t, this.clientId = o, this.redirectUri = s, this.homePage = a, this.baseKey = c;
45
+ constructor(t, o, s, a, i) {
46
+ this.authServer = t, this.clientId = o, this.redirectUri = s, this.homePage = a, this.baseKey = i;
46
47
  }
47
48
  }
48
49
  async function X(r, t, o = {}, s) {
49
50
  let a = r.getToken();
50
- const c = (d) => fetch(t, {
51
+ const i = (d) => fetch(t, {
51
52
  ...o,
52
53
  headers: {
53
54
  ...o.headers,
54
55
  Authorization: d ? `Bearer ${d}` : ""
55
56
  }
56
57
  });
57
- let l = await c(a);
58
- return l.status !== 401 ? l : (r.setToken(null), a = await r.getValidToken(), a ? c(a) : (s?.(), l));
58
+ let l = await i(a);
59
+ return l.status !== 401 ? l : (r.setToken(null), a = await r.getValidToken(), a ? i(a) : (s?.(), l));
59
60
  }
60
- async function z(r) {
61
- const t = new URLSearchParams(window.location.search), o = t.get("code"), s = sessionStorage.getItem("oauth_state"), a = t.get("state");
62
- if (!o) return;
63
- if (!a || a !== s)
61
+ async function he(r) {
62
+ const t = new URLSearchParams(window.location.search), o = t.get("code"), s = t.get("state");
63
+ if (!o)
64
+ throw new Error("Missing OAuth code");
65
+ const a = sessionStorage.getItem("oauth_state");
66
+ if (!s || s !== a)
64
67
  throw new Error("Invalid OAuth state");
65
- const c = sessionStorage.getItem("pkce_verifier"), d = await (await fetch(`${r.config.authServer}/token`, {
66
- method: "POST",
67
- headers: {
68
- "Content-Type": "application/json"
69
- },
70
- body: JSON.stringify({
71
- client_id: r.config.clientId,
72
- code: o,
73
- code_verifier: c
74
- })
75
- })).json();
76
- localStorage.setItem(r.config.baseKey + "_access", d.access), window.history.replaceState({}, document.title, r.config.homePage), window.location.href = r.config.homePage;
68
+ const i = sessionStorage.getItem("pkce_verifier");
69
+ if (!i)
70
+ throw new Error("Missing PKCE verifier");
71
+ const l = await fetch(
72
+ `${r.config.authServer}/token`,
73
+ {
74
+ method: "POST",
75
+ headers: {
76
+ "Content-Type": "application/json"
77
+ },
78
+ body: JSON.stringify({
79
+ client_id: r.config.clientId,
80
+ code: o,
81
+ code_verifier: i
82
+ })
83
+ }
84
+ );
85
+ if (!l.ok) {
86
+ const _ = await l.text();
87
+ throw new Error(
88
+ `Token exchange failed: ${l.status} ${_}`
89
+ );
90
+ }
91
+ const d = await l.json();
92
+ r.setToken(d.access), sessionStorage.removeItem("oauth_state"), sessionStorage.removeItem("pkce_verifier");
77
93
  }
78
- function _e(r = 64) {
94
+ function ge(r = 64) {
79
95
  const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
80
96
  let o = "";
81
97
  const s = new Uint8Array(r);
@@ -84,15 +100,15 @@ function _e(r = 64) {
84
100
  o += t[s[a] % t.length];
85
101
  return o;
86
102
  }
87
- async function pe(r) {
103
+ async function _e(r) {
88
104
  const o = new TextEncoder().encode(r), s = await crypto.subtle.digest("SHA-256", o);
89
105
  return new Uint8Array(s);
90
106
  }
91
- function ve(r) {
107
+ function pe(r) {
92
108
  return btoa(String.fromCharCode(...Array.from(r))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
93
109
  }
94
- async function N(r) {
95
- const t = _e(64), o = ve(await pe(t));
110
+ async function C(r) {
111
+ const t = ge(64), o = pe(await _e(t));
96
112
  sessionStorage.setItem("pkce_verifier", t);
97
113
  const s = crypto.randomUUID();
98
114
  sessionStorage.setItem("oauth_state", s);
@@ -106,7 +122,7 @@ async function N(r) {
106
122
  });
107
123
  window.location.href = `${r.config.authServer}/authorize?${a}`;
108
124
  }
109
- async function M(r) {
125
+ async function z(r) {
110
126
  try {
111
127
  await X(r, `${r.config.authServer}/logout`, {
112
128
  method: "POST",
@@ -116,12 +132,12 @@ async function M(r) {
116
132
  body: JSON.stringify({
117
133
  client_id: r.config.clientId
118
134
  })
119
- }), localStorage.removeItem(r.config.baseKey + "_access"), await N(r);
135
+ }), localStorage.removeItem(r.config.baseKey + "_access"), await C(r);
120
136
  } catch (t) {
121
137
  console.error(t);
122
138
  }
123
139
  }
124
- const $ = de({
140
+ const $ = fe({
125
141
  login: () => {
126
142
  },
127
143
  logout: () => {
@@ -132,28 +148,28 @@ const $ = de({
132
148
  user: null,
133
149
  loading: !1
134
150
  });
135
- var T = { exports: {} }, b = {};
151
+ var S = { exports: {} }, v = {};
136
152
  var q;
137
- function be() {
138
- if (q) return b;
153
+ function ve() {
154
+ if (q) return v;
139
155
  q = 1;
140
156
  var r = /* @__PURE__ */ Symbol.for("react.transitional.element"), t = /* @__PURE__ */ Symbol.for("react.fragment");
141
- function o(s, a, c) {
157
+ function o(s, a, i) {
142
158
  var l = null;
143
- if (c !== void 0 && (l = "" + c), a.key !== void 0 && (l = "" + a.key), "key" in a) {
144
- c = {};
159
+ if (i !== void 0 && (l = "" + i), a.key !== void 0 && (l = "" + a.key), "key" in a) {
160
+ i = {};
145
161
  for (var d in a)
146
- d !== "key" && (c[d] = a[d]);
147
- } else c = a;
148
- return a = c.ref, {
162
+ d !== "key" && (i[d] = a[d]);
163
+ } else i = a;
164
+ return a = i.ref, {
149
165
  $$typeof: r,
150
166
  type: s,
151
167
  key: l,
152
168
  ref: a !== void 0 ? a : null,
153
- props: c
169
+ props: i
154
170
  };
155
171
  }
156
- return b.Fragment = t, b.jsx = o, b.jsxs = o, b;
172
+ return v.Fragment = t, v.jsx = o, v.jsxs = o, v;
157
173
  }
158
174
  var E = {};
159
175
  var G;
@@ -165,35 +181,35 @@ function Ee() {
165
181
  return e.$$typeof === ie ? null : e.displayName || e.name || null;
166
182
  if (typeof e == "string") return e;
167
183
  switch (e) {
168
- case w:
184
+ case k:
169
185
  return "Fragment";
170
- case ee:
171
- return "Profiler";
172
186
  case Q:
187
+ return "Profiler";
188
+ case Z:
173
189
  return "StrictMode";
174
- case oe:
190
+ case ne:
175
191
  return "Suspense";
176
- case ae:
192
+ case oe:
177
193
  return "SuspenseList";
178
- case ce:
194
+ case se:
179
195
  return "Activity";
180
196
  }
181
197
  if (typeof e == "object")
182
198
  switch (typeof e.tag == "number" && console.error(
183
199
  "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
184
200
  ), e.$$typeof) {
185
- case Z:
201
+ case M:
186
202
  return "Portal";
187
- case te:
188
- return e.displayName || "Context";
189
203
  case re:
204
+ return e.displayName || "Context";
205
+ case ee:
190
206
  return (e._context.displayName || "Context") + ".Consumer";
191
- case ne:
207
+ case te:
192
208
  var n = e.render;
193
209
  return e = e.displayName, e || (e = n.displayName || n.name || "", e = e !== "" ? "ForwardRef(" + e + ")" : "ForwardRef"), e;
194
- case se:
210
+ case ae:
195
211
  return n = e.displayName || null, n !== null ? n : r(e.type) || "Memo";
196
- case k:
212
+ case R:
197
213
  n = e._payload, e = e._init;
198
214
  try {
199
215
  return r(e(n));
@@ -214,8 +230,8 @@ function Ee() {
214
230
  }
215
231
  if (n) {
216
232
  n = console;
217
- var i = n.error, u = typeof Symbol == "function" && Symbol.toStringTag && e[Symbol.toStringTag] || e.constructor.name || "Object";
218
- return i.call(
233
+ var c = n.error, u = typeof Symbol == "function" && Symbol.toStringTag && e[Symbol.toStringTag] || e.constructor.name || "Object";
234
+ return c.call(
219
235
  n,
220
236
  "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
221
237
  u
@@ -223,8 +239,8 @@ function Ee() {
223
239
  }
224
240
  }
225
241
  function s(e) {
226
- if (e === w) return "<>";
227
- if (typeof e == "object" && e !== null && e.$$typeof === k)
242
+ if (e === k) return "<>";
243
+ if (typeof e == "object" && e !== null && e.$$typeof === R)
228
244
  return "<...>";
229
245
  try {
230
246
  var n = r(e);
@@ -237,45 +253,45 @@ function Ee() {
237
253
  var e = P.A;
238
254
  return e === null ? null : e.getOwner();
239
255
  }
240
- function c() {
256
+ function i() {
241
257
  return Error("react-stack-top-frame");
242
258
  }
243
259
  function l(e) {
244
- if (F.call(e, "key")) {
260
+ if (Y.call(e, "key")) {
245
261
  var n = Object.getOwnPropertyDescriptor(e, "key").get;
246
262
  if (n && n.isReactWarning) return !1;
247
263
  }
248
264
  return e.key !== void 0;
249
265
  }
250
266
  function d(e, n) {
251
- function i() {
267
+ function c() {
252
268
  L || (L = !0, console.error(
253
269
  "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
254
270
  n
255
271
  ));
256
272
  }
257
- i.isReactWarning = !0, Object.defineProperty(e, "key", {
258
- get: i,
273
+ c.isReactWarning = !0, Object.defineProperty(e, "key", {
274
+ get: c,
259
275
  configurable: !0
260
276
  });
261
277
  }
262
- function S() {
278
+ function _() {
263
279
  var e = r(this.type);
264
280
  return D[e] || (D[e] = !0, console.error(
265
281
  "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
266
282
  )), e = this.props.ref, e !== void 0 ? e : null;
267
283
  }
268
- function R(e, n, i, u, y, O) {
269
- var f = i.ref;
284
+ function b(e, n, c, u, T, O) {
285
+ var f = c.ref;
270
286
  return e = {
271
- $$typeof: Y,
287
+ $$typeof: U,
272
288
  type: e,
273
289
  key: n,
274
- props: i,
290
+ props: c,
275
291
  _owner: u
276
292
  }, (f !== void 0 ? f : null) !== null ? Object.defineProperty(e, "ref", {
277
293
  enumerable: !1,
278
- get: S
294
+ get: _
279
295
  }) : Object.defineProperty(e, "ref", { enumerable: !1, value: null }), e._store = {}, Object.defineProperty(e._store, "validated", {
280
296
  configurable: !1,
281
297
  enumerable: !1,
@@ -290,7 +306,7 @@ function Ee() {
290
306
  configurable: !1,
291
307
  enumerable: !1,
292
308
  writable: !0,
293
- value: y
309
+ value: T
294
310
  }), Object.defineProperty(e, "_debugTask", {
295
311
  configurable: !1,
296
312
  enumerable: !1,
@@ -298,25 +314,25 @@ function Ee() {
298
314
  value: O
299
315
  }), Object.freeze && (Object.freeze(e.props), Object.freeze(e)), e;
300
316
  }
301
- function p(e, n, i, u, y, O) {
317
+ function p(e, n, c, u, T, O) {
302
318
  var f = n.children;
303
319
  if (f !== void 0)
304
320
  if (u)
305
- if (le(f)) {
321
+ if (ce(f)) {
306
322
  for (u = 0; u < f.length; u++)
307
- v(f[u]);
323
+ m(f[u]);
308
324
  Object.freeze && Object.freeze(f);
309
325
  } else
310
326
  console.error(
311
327
  "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
312
328
  );
313
- else v(f);
314
- if (F.call(n, "key")) {
329
+ else m(f);
330
+ if (Y.call(n, "key")) {
315
331
  f = r(e);
316
- var g = Object.keys(n).filter(function(ue) {
317
- return ue !== "key";
332
+ var h = Object.keys(n).filter(function(le) {
333
+ return le !== "key";
318
334
  });
319
- u = 0 < g.length ? "{key: someKey, " + g.join(": ..., ") + ": ...}" : "{key: someKey}", W[f + u] || (g = 0 < g.length ? "{" + g.join(": ..., ") + ": ...}" : "{}", console.error(
335
+ u = 0 < h.length ? "{key: someKey, " + h.join(": ..., ") + ": ...}" : "{key: someKey}", W[f + u] || (h = 0 < h.length ? "{" + h.join(": ..., ") + ": ...}" : "{}", console.error(
320
336
  `A props object containing a "key" prop is being spread into JSX:
321
337
  let props = %s;
322
338
  <%s {...props} />
@@ -325,61 +341,61 @@ React keys must be passed directly to JSX without using spread:
325
341
  <%s key={someKey} {...props} />`,
326
342
  u,
327
343
  f,
328
- g,
344
+ h,
329
345
  f
330
346
  ), W[f + u] = !0);
331
347
  }
332
- if (f = null, i !== void 0 && (o(i), f = "" + i), l(n) && (o(n.key), f = "" + n.key), "key" in n) {
333
- i = {};
348
+ if (f = null, c !== void 0 && (o(c), f = "" + c), l(n) && (o(n.key), f = "" + n.key), "key" in n) {
349
+ c = {};
334
350
  for (var x in n)
335
- x !== "key" && (i[x] = n[x]);
336
- } else i = n;
351
+ x !== "key" && (c[x] = n[x]);
352
+ } else c = n;
337
353
  return f && d(
338
- i,
354
+ c,
339
355
  typeof e == "function" ? e.displayName || e.name || "Unknown" : e
340
- ), R(
356
+ ), b(
341
357
  e,
342
358
  f,
343
- i,
359
+ c,
344
360
  a(),
345
- y,
361
+ T,
346
362
  O
347
363
  );
348
364
  }
349
- function v(e) {
350
- m(e) ? e._store && (e._store.validated = 1) : typeof e == "object" && e !== null && e.$$typeof === k && (e._payload.status === "fulfilled" ? m(e._payload.value) && e._payload.value._store && (e._payload.value._store.validated = 1) : e._store && (e._store.validated = 1));
351
- }
352
365
  function m(e) {
353
- return typeof e == "object" && e !== null && e.$$typeof === Y;
366
+ w(e) ? e._store && (e._store.validated = 1) : typeof e == "object" && e !== null && e.$$typeof === R && (e._payload.status === "fulfilled" ? w(e._payload.value) && e._payload.value._store && (e._payload.value._store.validated = 1) : e._store && (e._store.validated = 1));
367
+ }
368
+ function w(e) {
369
+ return typeof e == "object" && e !== null && e.$$typeof === U;
354
370
  }
355
- var h = fe, Y = /* @__PURE__ */ Symbol.for("react.transitional.element"), Z = /* @__PURE__ */ Symbol.for("react.portal"), w = /* @__PURE__ */ Symbol.for("react.fragment"), Q = /* @__PURE__ */ Symbol.for("react.strict_mode"), ee = /* @__PURE__ */ Symbol.for("react.profiler"), re = /* @__PURE__ */ Symbol.for("react.consumer"), te = /* @__PURE__ */ Symbol.for("react.context"), ne = /* @__PURE__ */ Symbol.for("react.forward_ref"), oe = /* @__PURE__ */ Symbol.for("react.suspense"), ae = /* @__PURE__ */ Symbol.for("react.suspense_list"), se = /* @__PURE__ */ Symbol.for("react.memo"), k = /* @__PURE__ */ Symbol.for("react.lazy"), ce = /* @__PURE__ */ Symbol.for("react.activity"), ie = /* @__PURE__ */ Symbol.for("react.client.reference"), P = h.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, F = Object.prototype.hasOwnProperty, le = Array.isArray, A = console.createTask ? console.createTask : function() {
371
+ var y = ue, U = /* @__PURE__ */ Symbol.for("react.transitional.element"), M = /* @__PURE__ */ Symbol.for("react.portal"), k = /* @__PURE__ */ Symbol.for("react.fragment"), Z = /* @__PURE__ */ Symbol.for("react.strict_mode"), Q = /* @__PURE__ */ Symbol.for("react.profiler"), ee = /* @__PURE__ */ Symbol.for("react.consumer"), re = /* @__PURE__ */ Symbol.for("react.context"), te = /* @__PURE__ */ Symbol.for("react.forward_ref"), ne = /* @__PURE__ */ Symbol.for("react.suspense"), oe = /* @__PURE__ */ Symbol.for("react.suspense_list"), ae = /* @__PURE__ */ Symbol.for("react.memo"), R = /* @__PURE__ */ Symbol.for("react.lazy"), se = /* @__PURE__ */ Symbol.for("react.activity"), ie = /* @__PURE__ */ Symbol.for("react.client.reference"), P = y.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, Y = Object.prototype.hasOwnProperty, ce = Array.isArray, A = console.createTask ? console.createTask : function() {
356
372
  return null;
357
373
  };
358
- h = {
374
+ y = {
359
375
  react_stack_bottom_frame: function(e) {
360
376
  return e();
361
377
  }
362
378
  };
363
- var L, D = {}, J = h.react_stack_bottom_frame.bind(
364
- h,
365
- c
366
- )(), V = A(s(c)), W = {};
367
- E.Fragment = w, E.jsx = function(e, n, i) {
379
+ var L, D = {}, J = y.react_stack_bottom_frame.bind(
380
+ y,
381
+ i
382
+ )(), V = A(s(i)), W = {};
383
+ E.Fragment = k, E.jsx = function(e, n, c) {
368
384
  var u = 1e4 > P.recentlyCreatedOwnerStacks++;
369
385
  return p(
370
386
  e,
371
387
  n,
372
- i,
388
+ c,
373
389
  !1,
374
390
  u ? Error("react-stack-top-frame") : J,
375
391
  u ? A(s(e)) : V
376
392
  );
377
- }, E.jsxs = function(e, n, i) {
393
+ }, E.jsxs = function(e, n, c) {
378
394
  var u = 1e4 > P.recentlyCreatedOwnerStacks++;
379
395
  return p(
380
396
  e,
381
397
  n,
382
- i,
398
+ c,
383
399
  !0,
384
400
  u ? Error("react-stack-top-frame") : J,
385
401
  u ? A(s(e)) : V
@@ -388,83 +404,95 @@ React keys must be passed directly to JSX without using spread:
388
404
  })()), E;
389
405
  }
390
406
  var K;
391
- function ye() {
392
- return K || (K = 1, process.env.NODE_ENV === "production" ? T.exports = be() : T.exports = Ee()), T.exports;
407
+ function be() {
408
+ return K || (K = 1, process.env.NODE_ENV === "production" ? S.exports = ve() : S.exports = Ee()), S.exports;
393
409
  }
394
- var _ = ye();
395
- const ke = ({ children: r, authConfig: t }) => {
396
- const [o, s] = I(null), [a, c] = I(!0), l = me(() => new ge(t), [t]), d = j(async () => {
397
- c(!0);
398
- const p = localStorage.getItem(l.config.baseKey + "_access");
399
- if (!p) {
400
- s(null), c(!1);
410
+ var g = be();
411
+ const Re = ({ children: r, authManager: t }) => {
412
+ const [o, s] = I(null), [a, i] = I(!0), l = j(async () => {
413
+ i(!0);
414
+ const b = localStorage.getItem(t.config.baseKey + "_access");
415
+ if (!b) {
416
+ s(null), i(!1);
401
417
  return;
402
418
  }
403
419
  try {
404
- const v = await X(l, `${l.config.authServer}/me`, {
420
+ const p = await X(t, `${t.config.authServer}/me`, {
405
421
  headers: {
406
- Authorization: `Bearer ${p}`
422
+ Authorization: `Bearer ${b}`
407
423
  }
408
424
  });
409
- if (!v.ok) throw new Error("not found");
410
- const m = await v.json();
425
+ if (!p.ok) throw new Error("not found");
426
+ const m = await p.json();
411
427
  s({
412
428
  role: m.role.role_name,
413
429
  userId: m.user_id,
414
430
  userName: m.user_name,
415
- privileges: m.role.privileges.map((h) => h.privilege.trim())
431
+ privileges: m.role.privileges.map((w) => w.privilege.trim())
416
432
  });
417
433
  } catch {
418
434
  s(null);
419
435
  }
420
- c(!1);
436
+ i(!1);
421
437
  }, []);
422
- C(() => {
423
- d();
424
- }, [d]);
425
- const S = j(() => {
426
- N(l);
427
- }, [N, l]), R = j(() => {
428
- M(l), s(null);
429
- }, [M, l]);
430
- return /* @__PURE__ */ _.jsx($.Provider, { value: { loadMe: d, loading: a, user: o, login: S, authManager: l, logout: R }, children: r });
438
+ N(() => {
439
+ l();
440
+ }, [l]);
441
+ const d = j(() => {
442
+ C(t);
443
+ }, [C, t]), _ = j(() => {
444
+ z(t), s(null);
445
+ }, [z, t]);
446
+ return /* @__PURE__ */ g.jsx($.Provider, { value: { loadMe: l, loading: a, user: o, login: d, authManager: t, logout: _ }, children: r });
431
447
  }, Pe = () => {
432
- const { authManager: r, loadMe: t } = B($);
433
- return C(() => {
434
- r && (z(r), t());
435
- }, [z, r, t]), /* @__PURE__ */ _.jsx("div", {});
436
- }, U = () => {
448
+ const { authManager: r, loadMe: t } = B($), o = de(!1);
449
+ return N(() => {
450
+ if (!r || o.current)
451
+ return;
452
+ o.current = !0, (async () => {
453
+ try {
454
+ await he(r), await t(), window.location.replace(
455
+ r.config.homePage
456
+ );
457
+ } catch (a) {
458
+ console.error("Authentication callback failed:", a), window.location.replace(
459
+ r.config.homePage
460
+ );
461
+ }
462
+ })();
463
+ }, [r, t]), /* @__PURE__ */ g.jsx("div", { children: "Авторизация..." });
464
+ }, F = () => {
437
465
  const r = B($);
438
466
  if (!r || !r.authManager) throw new Error("AuthContext not found");
439
467
  return r;
440
- }, Te = (r) => {
441
- const { user: t } = U();
468
+ }, we = (r) => {
469
+ const { user: t } = F();
442
470
  return !!t?.privileges?.includes(r);
443
471
  };
444
472
  function Ae({ privilege: r, invalidPage: t, loadingPage: o }) {
445
- const { loading: s } = U(), a = Te(r);
446
- return s ? o : a ? /* @__PURE__ */ _.jsx(H, {}) : t;
473
+ const { loading: s } = F(), a = we(r);
474
+ return s ? o : a ? /* @__PURE__ */ g.jsx(H, {}) : t;
447
475
  }
448
476
  function Oe({ loadingPage: r }) {
449
- const { authManager: t, login: o, user: s } = U(), [a, c] = I(!0);
450
- return C(() => {
477
+ const { authManager: t, login: o, user: s } = F(), [a, i] = I(!0);
478
+ return N(() => {
451
479
  if (!t) return;
452
- t.getToken() ? c(!1) : o();
453
- }, [t, s]), t ? a ? r ?? /* @__PURE__ */ _.jsx("div", { children: "Loading..." }) : /* @__PURE__ */ _.jsx(H, {}) : /* @__PURE__ */ _.jsx("p", { children: "invalud config" });
480
+ t.getToken() ? i(!1) : o();
481
+ }, [t, s]), t ? a ? r ?? /* @__PURE__ */ g.jsx("div", { children: "Loading..." }) : /* @__PURE__ */ g.jsx(H, {}) : /* @__PURE__ */ g.jsx("p", { children: "invalud config" });
454
482
  }
455
483
  export {
456
484
  $ as AuthContext,
457
- ge as AuthManager,
458
- ke as AuthProvider,
485
+ Se as AuthManager,
486
+ Re as AuthProvider,
459
487
  Pe as CallbackPage,
460
- we as Config,
488
+ ke as Config,
461
489
  Ae as PrivilegeGate,
462
490
  Oe as ProtectGate,
463
491
  X as apiFetch,
464
- z as handleCallback,
465
- N as login,
466
- M as logout,
467
- he as refreshToken,
468
- U as useAuth,
469
- Te as usePrivilege
492
+ he as handleCallback,
493
+ C as login,
494
+ z as logout,
495
+ me as refreshToken,
496
+ F as useAuth,
497
+ we as usePrivilege
470
498
  };
@@ -1,6 +1,6 @@
1
- (function(l,m){typeof exports=="object"&&typeof module<"u"?m(exports,require("react"),require("react-router-dom")):typeof define=="function"&&define.amd?define(["exports","react","react-router-dom"],m):(l=typeof globalThis<"u"?globalThis:l||self,m(l["alex-evo-sh-auth"]={},l.React,l.ReactRouterDOM))})(this,(function(l,m,D){"use strict";async function M(t){const r=await fetch(`${t.authServer}/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:t.clientId})});if(r.status===401)return localStorage.removeItem(t.baseKey+"_access"),null;const o=await r.json();return localStorage.setItem(t.baseKey+"_access",o.access),o.access}class J{constructor(r,o){this.onAuthFail=o,this.config=r}refreshPromise=null;config;getToken(){return localStorage.getItem(this.config.baseKey+"_access")}setToken(r){r?localStorage.setItem(this.config.baseKey+"_access",r):localStorage.removeItem(this.config.baseKey+"_access")}async getValidToken(){let r=this.getToken();return r||(this.refreshPromise||(this.refreshPromise=M(this.config).then(o=>(this.setToken(o),o)).finally(()=>{this.refreshPromise=null})),r=await this.refreshPromise,!r&&this.onAuthFail&&this.onAuthFail(),r)}}class q{authServer;clientId;redirectUri;homePage;baseKey;constructor(r,o,s,a,c){this.authServer=r,this.clientId=o,this.redirectUri=s,this.homePage=a,this.baseKey=c}}async function A(t,r,o={},s){let a=t.getToken();const c=h=>fetch(r,{...o,headers:{...o.headers,Authorization:h?`Bearer ${h}`:""}});let u=await c(a);return u.status!==401?u:(t.setToken(null),a=await t.getValidToken(),a?c(a):(s?.(),u))}async function O(t){const r=new URLSearchParams(window.location.search),o=r.get("code"),s=sessionStorage.getItem("oauth_state"),a=r.get("state");if(!o)return;if(!a||a!==s)throw new Error("Invalid OAuth state");const c=sessionStorage.getItem("pkce_verifier"),h=await(await fetch(`${t.config.authServer}/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t.config.clientId,code:o,code_verifier:c})})).json();localStorage.setItem(t.config.baseKey+"_access",h.access),window.history.replaceState({},document.title,t.config.homePage),window.location.href=t.config.homePage}function ee(t=64){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let o="";const s=new Uint8Array(t);crypto.getRandomValues(s);for(let a=0;a<s.length;a++)o+=r[s[a]%r.length];return o}async function te(t){const o=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",o);return new Uint8Array(s)}function re(t){return btoa(String.fromCharCode(...Array.from(t))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function S(t){const r=ee(64),o=re(await te(r));sessionStorage.setItem("pkce_verifier",r);const s=crypto.randomUUID();sessionStorage.setItem("oauth_state",s);const a=new URLSearchParams({response_type:"code",client_id:t.config.clientId,redirect_uri:t.config.redirectUri,code_challenge:o,code_challenge_method:"S256",state:s});window.location.href=`${t.config.authServer}/authorize?${a}`}async function j(t){try{await A(t,`${t.config.authServer}/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t.config.clientId})}),localStorage.removeItem(t.config.baseKey+"_access"),await S(t)}catch(r){console.error(r)}}const k=m.createContext({login:()=>{},logout:()=>{},loadMe:()=>{},authManager:null,user:null,loading:!1});var R={exports:{}},p={};var V;function ne(){if(V)return p;V=1;var t=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function o(s,a,c){var u=null;if(c!==void 0&&(u=""+c),a.key!==void 0&&(u=""+a.key),"key"in a){c={};for(var h in a)h!=="key"&&(c[h]=a[h])}else c=a;return a=c.ref,{$$typeof:t,type:s,key:u,ref:a!==void 0?a:null,props:c}}return p.Fragment=r,p.jsx=o,p.jsxs=o,p}var E={};var W;function oe(){return W||(W=1,process.env.NODE_ENV!=="production"&&(function(){function t(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===Ee?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case I:return"Fragment";case de:return"Profiler";case fe:return"StrictMode";case _e:return"Suspense";case ve:return"SuspenseList";case pe:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case ue:return"Portal";case he:return e.displayName||"Context";case me:return(e._context.displayName||"Context")+".Consumer";case ge:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case be:return n=e.displayName||null,n!==null?n:t(e.type)||"Memo";case N:n=e._payload,e=e._init;try{return t(e(n))}catch{}}return null}function r(e){return""+e}function o(e){try{r(e);var n=!1}catch{n=!0}if(n){n=console;var i=n.error,f=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return i.call(n,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",f),r(e)}}function s(e){if(e===I)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===N)return"<...>";try{var n=t(e);return n?"<"+n+">":"<...>"}catch{return"<...>"}}function a(){var e=F.A;return e===null?null:e.getOwner()}function c(){return Error("react-stack-top-frame")}function u(e){if(B.call(e,"key")){var n=Object.getOwnPropertyDescriptor(e,"key").get;if(n&&n.isReactWarning)return!1}return e.key!==void 0}function h(e,n){function i(){H||(H=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",n))}i.isReactWarning=!0,Object.defineProperty(e,"key",{get:i,configurable:!0})}function C(){var e=t(this.type);return X[e]||(X[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function x(e,n,i,f,P,Y){var d=i.ref;return e={$$typeof:K,type:e,key:n,props:i,_owner:f},(d!==void 0?d:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:C}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:P}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:Y}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function y(e,n,i,f,P,Y){var d=n.children;if(d!==void 0)if(f)if(ye(d)){for(f=0;f<d.length;f++)T(d[f]);Object.freeze&&Object.freeze(d)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else T(d);if(B.call(n,"key")){d=t(e);var b=Object.keys(n).filter(function(Te){return Te!=="key"});f=0<b.length?"{key: someKey, "+b.join(": ..., ")+": ...}":"{key: someKey}",$[d+f]||(b=0<b.length?"{"+b.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
1
+ (function(l,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("react"),require("react-router-dom")):typeof define=="function"&&define.amd?define(["exports","react","react-router-dom"],h):(l=typeof globalThis<"u"?globalThis:l||self,h(l["alex-evo-sh-auth"]={},l.React,l.ReactRouterDOM))})(this,(function(l,h,L){"use strict";async function D(t){const r=await fetch(`${t.authServer}/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:t.clientId})});if(r.status===401)return localStorage.removeItem(t.baseKey+"_access"),null;const o=await r.json();return localStorage.setItem(t.baseKey+"_access",o.access),o.access}class ${constructor(r,o){this.onAuthFail=o,this.config=r}onAuthFail;refreshPromise=null;config;getToken(){return localStorage.getItem(this.config.baseKey+"_access")}setToken(r){r?localStorage.setItem(this.config.baseKey+"_access",r):localStorage.removeItem(this.config.baseKey+"_access")}async getValidToken(){let r=this.getToken();return r||(this.refreshPromise||(this.refreshPromise=D(this.config).then(o=>(this.setToken(o),o)).finally(()=>{this.refreshPromise=null})),r=await this.refreshPromise,!r&&this.onAuthFail&&this.onAuthFail(),r)}}class q{authServer;clientId;redirectUri;homePage;baseKey;constructor(r,o,s,a,c){this.authServer=r,this.clientId=o,this.redirectUri=s,this.homePage=a,this.baseKey=c}}async function j(t,r,o={},s){let a=t.getToken();const c=m=>fetch(r,{...o,headers:{...o.headers,Authorization:m?`Bearer ${m}`:""}});let u=await c(a);return u.status!==401?u:(t.setToken(null),a=await t.getValidToken(),a?c(a):(s?.(),u))}async function J(t){const r=new URLSearchParams(window.location.search),o=r.get("code"),s=r.get("state");if(!o)throw new Error("Missing OAuth code");const a=sessionStorage.getItem("oauth_state");if(!s||s!==a)throw new Error("Invalid OAuth state");const c=sessionStorage.getItem("pkce_verifier");if(!c)throw new Error("Missing PKCE verifier");const u=await fetch(`${t.config.authServer}/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t.config.clientId,code:o,code_verifier:c})});if(!u.ok){const E=await u.text();throw new Error(`Token exchange failed: ${u.status} ${E}`)}const m=await u.json();t.setToken(m.access),sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("pkce_verifier")}function ee(t=64){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let o="";const s=new Uint8Array(t);crypto.getRandomValues(s);for(let a=0;a<s.length;a++)o+=r[s[a]%r.length];return o}async function te(t){const o=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",o);return new Uint8Array(s)}function re(t){return btoa(String.fromCharCode(...Array.from(t))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function T(t){const r=ee(64),o=re(await te(r));sessionStorage.setItem("pkce_verifier",r);const s=crypto.randomUUID();sessionStorage.setItem("oauth_state",s);const a=new URLSearchParams({response_type:"code",client_id:t.config.clientId,redirect_uri:t.config.redirectUri,code_challenge:o,code_challenge_method:"S256",state:s});window.location.href=`${t.config.authServer}/authorize?${a}`}async function x(t){try{await j(t,`${t.config.authServer}/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t.config.clientId})}),localStorage.removeItem(t.config.baseKey+"_access"),await T(t)}catch(r){console.error(r)}}const k=h.createContext({login:()=>{},logout:()=>{},loadMe:()=>{},authManager:null,user:null,loading:!1});var w={exports:{}},p={};var V;function ne(){if(V)return p;V=1;var t=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function o(s,a,c){var u=null;if(c!==void 0&&(u=""+c),a.key!==void 0&&(u=""+a.key),"key"in a){c={};for(var m in a)m!=="key"&&(c[m]=a[m])}else c=a;return a=c.ref,{$$typeof:t,type:s,key:u,ref:a!==void 0?a:null,props:c}}return p.Fragment=r,p.jsx=o,p.jsxs=o,p}var b={};var W;function oe(){return W||(W=1,process.env.NODE_ENV!=="production"&&(function(){function t(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===Ee?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case C:return"Fragment";case de:return"Profiler";case fe:return"StrictMode";case _e:return"Suspense";case ve:return"SuspenseList";case be:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case ue:return"Portal";case me:return e.displayName||"Context";case he:return(e._context.displayName||"Context")+".Consumer";case ge:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case pe:return n=e.displayName||null,n!==null?n:t(e.type)||"Memo";case I:n=e._payload,e=e._init;try{return t(e(n))}catch{}}return null}function r(e){return""+e}function o(e){try{r(e);var n=!1}catch{n=!0}if(n){n=console;var i=n.error,f=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return i.call(n,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",f),r(e)}}function s(e){if(e===C)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===I)return"<...>";try{var n=t(e);return n?"<"+n+">":"<...>"}catch{return"<...>"}}function a(){var e=N.A;return e===null?null:e.getOwner()}function c(){return Error("react-stack-top-frame")}function u(e){if(M.call(e,"key")){var n=Object.getOwnPropertyDescriptor(e,"key").get;if(n&&n.isReactWarning)return!1}return e.key!==void 0}function m(e,n){function i(){B||(B=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",n))}i.isReactWarning=!0,Object.defineProperty(e,"key",{get:i,configurable:!0})}function E(){var e=t(this.type);return H[e]||(H[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function R(e,n,i,f,O,U){var d=i.ref;return e={$$typeof:K,type:e,key:n,props:i,_owner:f},(d!==void 0?d:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:E}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:O}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:U}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function y(e,n,i,f,O,U){var d=n.children;if(d!==void 0)if(f)if(ye(d)){for(f=0;f<d.length;f++)g(d[f]);Object.freeze&&Object.freeze(d)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else g(d);if(M.call(n,"key")){d=t(e);var v=Object.keys(n).filter(function(Te){return Te!=="key"});f=0<v.length?"{key: someKey, "+v.join(": ..., ")+": ...}":"{key: someKey}",Q[d+f]||(v=0<v.length?"{"+v.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
2
2
  let props = %s;
3
3
  <%s {...props} />
4
4
  React keys must be passed directly to JSX without using spread:
5
5
  let props = %s;
6
- <%s key={someKey} {...props} />`,f,d,b,d),$[d+f]=!0)}if(d=null,i!==void 0&&(o(i),d=""+i),u(n)&&(o(n.key),d=""+n.key),"key"in n){i={};for(var L in n)L!=="key"&&(i[L]=n[L])}else i=n;return d&&h(i,typeof e=="function"?e.displayName||e.name||"Unknown":e),x(e,d,i,a(),P,Y)}function T(e){g(e)?e._store&&(e._store.validated=1):typeof e=="object"&&e!==null&&e.$$typeof===N&&(e._payload.status==="fulfilled"?g(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function g(e){return typeof e=="object"&&e!==null&&e.$$typeof===K}var v=m,K=Symbol.for("react.transitional.element"),ue=Symbol.for("react.portal"),I=Symbol.for("react.fragment"),fe=Symbol.for("react.strict_mode"),de=Symbol.for("react.profiler"),me=Symbol.for("react.consumer"),he=Symbol.for("react.context"),ge=Symbol.for("react.forward_ref"),_e=Symbol.for("react.suspense"),ve=Symbol.for("react.suspense_list"),be=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),pe=Symbol.for("react.activity"),Ee=Symbol.for("react.client.reference"),F=v.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,B=Object.prototype.hasOwnProperty,ye=Array.isArray,U=console.createTask?console.createTask:function(){return null};v={react_stack_bottom_frame:function(e){return e()}};var H,X={},Z=v.react_stack_bottom_frame.bind(v,c)(),Q=U(s(c)),$={};E.Fragment=I,E.jsx=function(e,n,i){var f=1e4>F.recentlyCreatedOwnerStacks++;return y(e,n,i,!1,f?Error("react-stack-top-frame"):Z,f?U(s(e)):Q)},E.jsxs=function(e,n,i){var f=1e4>F.recentlyCreatedOwnerStacks++;return y(e,n,i,!0,f?Error("react-stack-top-frame"):Z,f?U(s(e)):Q)}})()),E}var z;function ae(){return z||(z=1,process.env.NODE_ENV==="production"?R.exports=ne():R.exports=oe()),R.exports}var _=ae();const se=({children:t,authConfig:r})=>{const[o,s]=m.useState(null),[a,c]=m.useState(!0),u=m.useMemo(()=>new J(r),[r]),h=m.useCallback(async()=>{c(!0);const y=localStorage.getItem(u.config.baseKey+"_access");if(!y){s(null),c(!1);return}try{const T=await A(u,`${u.config.authServer}/me`,{headers:{Authorization:`Bearer ${y}`}});if(!T.ok)throw new Error("not found");const g=await T.json();s({role:g.role.role_name,userId:g.user_id,userName:g.user_name,privileges:g.role.privileges.map(v=>v.privilege.trim())})}catch{s(null)}c(!1)},[]);m.useEffect(()=>{h()},[h]);const C=m.useCallback(()=>{S(u)},[S,u]),x=m.useCallback(()=>{j(u),s(null)},[j,u]);return _.jsx(k.Provider,{value:{loadMe:h,loading:a,user:o,login:C,authManager:u,logout:x},children:t})},ce=()=>{const{authManager:t,loadMe:r}=m.useContext(k);return m.useEffect(()=>{t&&(O(t),r())},[O,t,r]),_.jsx("div",{})},w=()=>{const t=m.useContext(k);if(!t||!t.authManager)throw new Error("AuthContext not found");return t},G=t=>{const{user:r}=w();return!!r?.privileges?.includes(t)};function ie({privilege:t,invalidPage:r,loadingPage:o}){const{loading:s}=w(),a=G(t);return s?o:a?_.jsx(D.Outlet,{}):r}function le({loadingPage:t}){const{authManager:r,login:o,user:s}=w(),[a,c]=m.useState(!0);return m.useEffect(()=>{if(!r)return;r.getToken()?c(!1):o()},[r,s]),r?a?t??_.jsx("div",{children:"Loading..."}):_.jsx(D.Outlet,{}):_.jsx("p",{children:"invalud config"})}l.AuthContext=k,l.AuthManager=J,l.AuthProvider=se,l.CallbackPage=ce,l.Config=q,l.PrivilegeGate=ie,l.ProtectGate=le,l.apiFetch=A,l.handleCallback=O,l.login=S,l.logout=j,l.refreshToken=M,l.useAuth=w,l.usePrivilege=G,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})}));
6
+ <%s key={someKey} {...props} />`,f,d,v,d),Q[d+f]=!0)}if(d=null,i!==void 0&&(o(i),d=""+i),u(n)&&(o(n.key),d=""+n.key),"key"in n){i={};for(var Y in n)Y!=="key"&&(i[Y]=n[Y])}else i=n;return d&&m(i,typeof e=="function"?e.displayName||e.name||"Unknown":e),R(e,d,i,a(),O,U)}function g(e){P(e)?e._store&&(e._store.validated=1):typeof e=="object"&&e!==null&&e.$$typeof===I&&(e._payload.status==="fulfilled"?P(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function P(e){return typeof e=="object"&&e!==null&&e.$$typeof===K}var A=h,K=Symbol.for("react.transitional.element"),ue=Symbol.for("react.portal"),C=Symbol.for("react.fragment"),fe=Symbol.for("react.strict_mode"),de=Symbol.for("react.profiler"),he=Symbol.for("react.consumer"),me=Symbol.for("react.context"),ge=Symbol.for("react.forward_ref"),_e=Symbol.for("react.suspense"),ve=Symbol.for("react.suspense_list"),pe=Symbol.for("react.memo"),I=Symbol.for("react.lazy"),be=Symbol.for("react.activity"),Ee=Symbol.for("react.client.reference"),N=A.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,M=Object.prototype.hasOwnProperty,ye=Array.isArray,F=console.createTask?console.createTask:function(){return null};A={react_stack_bottom_frame:function(e){return e()}};var B,H={},X=A.react_stack_bottom_frame.bind(A,c)(),Z=F(s(c)),Q={};b.Fragment=C,b.jsx=function(e,n,i){var f=1e4>N.recentlyCreatedOwnerStacks++;return y(e,n,i,!1,f?Error("react-stack-top-frame"):X,f?F(s(e)):Z)},b.jsxs=function(e,n,i){var f=1e4>N.recentlyCreatedOwnerStacks++;return y(e,n,i,!0,f?Error("react-stack-top-frame"):X,f?F(s(e)):Z)}})()),b}var z;function ae(){return z||(z=1,process.env.NODE_ENV==="production"?w.exports=ne():w.exports=oe()),w.exports}var _=ae();const se=({children:t,authManager:r})=>{const[o,s]=h.useState(null),[a,c]=h.useState(!0),u=h.useCallback(async()=>{c(!0);const R=localStorage.getItem(r.config.baseKey+"_access");if(!R){s(null),c(!1);return}try{const y=await j(r,`${r.config.authServer}/me`,{headers:{Authorization:`Bearer ${R}`}});if(!y.ok)throw new Error("not found");const g=await y.json();s({role:g.role.role_name,userId:g.user_id,userName:g.user_name,privileges:g.role.privileges.map(P=>P.privilege.trim())})}catch{s(null)}c(!1)},[]);h.useEffect(()=>{u()},[u]);const m=h.useCallback(()=>{T(r)},[T,r]),E=h.useCallback(()=>{x(r),s(null)},[x,r]);return _.jsx(k.Provider,{value:{loadMe:u,loading:a,user:o,login:m,authManager:r,logout:E},children:t})},ce=()=>{const{authManager:t,loadMe:r}=h.useContext(k),o=h.useRef(!1);return h.useEffect(()=>{if(!t||o.current)return;o.current=!0,(async()=>{try{await J(t),await r(),window.location.replace(t.config.homePage)}catch(a){console.error("Authentication callback failed:",a),window.location.replace(t.config.homePage)}})()},[t,r]),_.jsx("div",{children:"Авторизация..."})},S=()=>{const t=h.useContext(k);if(!t||!t.authManager)throw new Error("AuthContext not found");return t},G=t=>{const{user:r}=S();return!!r?.privileges?.includes(t)};function ie({privilege:t,invalidPage:r,loadingPage:o}){const{loading:s}=S(),a=G(t);return s?o:a?_.jsx(L.Outlet,{}):r}function le({loadingPage:t}){const{authManager:r,login:o,user:s}=S(),[a,c]=h.useState(!0);return h.useEffect(()=>{if(!r)return;r.getToken()?c(!1):o()},[r,s]),r?a?t??_.jsx("div",{children:"Loading..."}):_.jsx(L.Outlet,{}):_.jsx("p",{children:"invalud config"})}l.AuthContext=k,l.AuthManager=$,l.AuthProvider=se,l.CallbackPage=ce,l.Config=q,l.PrivilegeGate=ie,l.ProtectGate=le,l.apiFetch=j,l.handleCallback=J,l.login=T,l.logout=x,l.refreshToken=D,l.useAuth=S,l.usePrivilege=G,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})}));
@@ -1,7 +1,7 @@
1
- import { Config } from '../helpers/config';
1
+ import { AuthManager } from '../helpers/authManager';
2
2
  type IAuthProvider = {
3
- authConfig: Config;
3
+ authManager: AuthManager;
4
4
  children: React.ReactNode;
5
5
  };
6
- export declare const AuthProvider: ({ children, authConfig }: IAuthProvider) => import("react/jsx-runtime").JSX.Element;
6
+ export declare const AuthProvider: ({ children, authManager }: IAuthProvider) => import("react").JSX.Element;
7
7
  export {};
@@ -1 +1 @@
1
- export declare const CallbackPage: () => import("react/jsx-runtime").JSX.Element;
1
+ export declare const CallbackPage: () => import("react").JSX.Element;
@@ -3,4 +3,4 @@ export declare function PrivilegeGate({ privilege, invalidPage, loadingPage }: {
3
3
  privilege: string;
4
4
  invalidPage: React.ReactNode;
5
5
  loadingPage: React.ReactNode;
6
- }): string | number | boolean | Iterable<React.ReactNode> | import("react/jsx-runtime").JSX.Element | null | undefined;
6
+ }): string | number | bigint | boolean | Iterable<React.ReactNode> | Promise<string | number | bigint | boolean | React.ReactPortal | React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | null | undefined> | React.JSX.Element | null | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "alex-evo-sh-auth",
3
- "version": "0.0.15",
3
+ "version": "0.0.17",
4
4
  "type": "module",
5
5
  "main": "./dist/alex-evo-sh-auth.umd.js",
6
6
  "module": "./dist/alex-evo-sh-auth.es.js",