alex-evo-sh-auth 0.0.16 → 0.0.21

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