alex-evo-sh-auth 0.0.21 → 0.0.22

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