@forward-software/react-auth 1.1.0 → 2.0.1

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,789 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
-
7
- var React = require('react');
8
- var React__default = _interopDefault(React);
9
- var shim = require('use-sync-external-store/shim');
10
-
11
- function _regeneratorRuntime() {
12
- _regeneratorRuntime = function () {
13
- return exports;
14
- };
15
- var exports = {},
16
- Op = Object.prototype,
17
- hasOwn = Op.hasOwnProperty,
18
- defineProperty = Object.defineProperty || function (obj, key, desc) {
19
- obj[key] = desc.value;
20
- },
21
- $Symbol = "function" == typeof Symbol ? Symbol : {},
22
- iteratorSymbol = $Symbol.iterator || "@@iterator",
23
- asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
24
- toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
25
- function define(obj, key, value) {
26
- return Object.defineProperty(obj, key, {
27
- value: value,
28
- enumerable: !0,
29
- configurable: !0,
30
- writable: !0
31
- }), obj[key];
32
- }
33
- try {
34
- define({}, "");
35
- } catch (err) {
36
- define = function (obj, key, value) {
37
- return obj[key] = value;
38
- };
39
- }
40
- function wrap(innerFn, outerFn, self, tryLocsList) {
41
- var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
42
- generator = Object.create(protoGenerator.prototype),
43
- context = new Context(tryLocsList || []);
44
- return defineProperty(generator, "_invoke", {
45
- value: makeInvokeMethod(innerFn, self, context)
46
- }), generator;
47
- }
48
- function tryCatch(fn, obj, arg) {
49
- try {
50
- return {
51
- type: "normal",
52
- arg: fn.call(obj, arg)
53
- };
54
- } catch (err) {
55
- return {
56
- type: "throw",
57
- arg: err
58
- };
59
- }
60
- }
61
- exports.wrap = wrap;
62
- var ContinueSentinel = {};
63
- function Generator() {}
64
- function GeneratorFunction() {}
65
- function GeneratorFunctionPrototype() {}
66
- var IteratorPrototype = {};
67
- define(IteratorPrototype, iteratorSymbol, function () {
68
- return this;
69
- });
70
- var getProto = Object.getPrototypeOf,
71
- NativeIteratorPrototype = getProto && getProto(getProto(values([])));
72
- NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
73
- var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
74
- function defineIteratorMethods(prototype) {
75
- ["next", "throw", "return"].forEach(function (method) {
76
- define(prototype, method, function (arg) {
77
- return this._invoke(method, arg);
78
- });
79
- });
80
- }
81
- function AsyncIterator(generator, PromiseImpl) {
82
- function invoke(method, arg, resolve, reject) {
83
- var record = tryCatch(generator[method], generator, arg);
84
- if ("throw" !== record.type) {
85
- var result = record.arg,
86
- value = result.value;
87
- return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
88
- invoke("next", value, resolve, reject);
89
- }, function (err) {
90
- invoke("throw", err, resolve, reject);
91
- }) : PromiseImpl.resolve(value).then(function (unwrapped) {
92
- result.value = unwrapped, resolve(result);
93
- }, function (error) {
94
- return invoke("throw", error, resolve, reject);
95
- });
96
- }
97
- reject(record.arg);
98
- }
99
- var previousPromise;
100
- defineProperty(this, "_invoke", {
101
- value: function (method, arg) {
102
- function callInvokeWithMethodAndArg() {
103
- return new PromiseImpl(function (resolve, reject) {
104
- invoke(method, arg, resolve, reject);
105
- });
106
- }
107
- return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
108
- }
109
- });
110
- }
111
- function makeInvokeMethod(innerFn, self, context) {
112
- var state = "suspendedStart";
113
- return function (method, arg) {
114
- if ("executing" === state) throw new Error("Generator is already running");
115
- if ("completed" === state) {
116
- if ("throw" === method) throw arg;
117
- return doneResult();
118
- }
119
- for (context.method = method, context.arg = arg;;) {
120
- var delegate = context.delegate;
121
- if (delegate) {
122
- var delegateResult = maybeInvokeDelegate(delegate, context);
123
- if (delegateResult) {
124
- if (delegateResult === ContinueSentinel) continue;
125
- return delegateResult;
126
- }
127
- }
128
- if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
129
- if ("suspendedStart" === state) throw state = "completed", context.arg;
130
- context.dispatchException(context.arg);
131
- } else "return" === context.method && context.abrupt("return", context.arg);
132
- state = "executing";
133
- var record = tryCatch(innerFn, self, context);
134
- if ("normal" === record.type) {
135
- if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
136
- return {
137
- value: record.arg,
138
- done: context.done
139
- };
140
- }
141
- "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
142
- }
143
- };
144
- }
145
- function maybeInvokeDelegate(delegate, context) {
146
- var method = delegate.iterator[context.method];
147
- if (undefined === method) {
148
- if (context.delegate = null, "throw" === context.method) {
149
- if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
150
- context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
151
- }
152
- return ContinueSentinel;
153
- }
154
- var record = tryCatch(method, delegate.iterator, context.arg);
155
- if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
156
- var info = record.arg;
157
- return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
158
- }
159
- function pushTryEntry(locs) {
160
- var entry = {
161
- tryLoc: locs[0]
162
- };
163
- 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
164
- }
165
- function resetTryEntry(entry) {
166
- var record = entry.completion || {};
167
- record.type = "normal", delete record.arg, entry.completion = record;
168
- }
169
- function Context(tryLocsList) {
170
- this.tryEntries = [{
171
- tryLoc: "root"
172
- }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
173
- }
174
- function values(iterable) {
175
- if (iterable) {
176
- var iteratorMethod = iterable[iteratorSymbol];
177
- if (iteratorMethod) return iteratorMethod.call(iterable);
178
- if ("function" == typeof iterable.next) return iterable;
179
- if (!isNaN(iterable.length)) {
180
- var i = -1,
181
- next = function next() {
182
- for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
183
- return next.value = undefined, next.done = !0, next;
184
- };
185
- return next.next = next;
186
- }
187
- }
188
- return {
189
- next: doneResult
190
- };
191
- }
192
- function doneResult() {
193
- return {
194
- value: undefined,
195
- done: !0
196
- };
197
- }
198
- return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
199
- value: GeneratorFunctionPrototype,
200
- configurable: !0
201
- }), defineProperty(GeneratorFunctionPrototype, "constructor", {
202
- value: GeneratorFunction,
203
- configurable: !0
204
- }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
205
- var ctor = "function" == typeof genFun && genFun.constructor;
206
- return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
207
- }, exports.mark = function (genFun) {
208
- return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
209
- }, exports.awrap = function (arg) {
210
- return {
211
- __await: arg
212
- };
213
- }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
214
- return this;
215
- }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
216
- void 0 === PromiseImpl && (PromiseImpl = Promise);
217
- var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
218
- return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
219
- return result.done ? result.value : iter.next();
220
- });
221
- }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
222
- return this;
223
- }), define(Gp, "toString", function () {
224
- return "[object Generator]";
225
- }), exports.keys = function (val) {
226
- var object = Object(val),
227
- keys = [];
228
- for (var key in object) keys.push(key);
229
- return keys.reverse(), function next() {
230
- for (; keys.length;) {
231
- var key = keys.pop();
232
- if (key in object) return next.value = key, next.done = !1, next;
233
- }
234
- return next.done = !0, next;
235
- };
236
- }, exports.values = values, Context.prototype = {
237
- constructor: Context,
238
- reset: function (skipTempReset) {
239
- if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
240
- },
241
- stop: function () {
242
- this.done = !0;
243
- var rootRecord = this.tryEntries[0].completion;
244
- if ("throw" === rootRecord.type) throw rootRecord.arg;
245
- return this.rval;
246
- },
247
- dispatchException: function (exception) {
248
- if (this.done) throw exception;
249
- var context = this;
250
- function handle(loc, caught) {
251
- return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
252
- }
253
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
254
- var entry = this.tryEntries[i],
255
- record = entry.completion;
256
- if ("root" === entry.tryLoc) return handle("end");
257
- if (entry.tryLoc <= this.prev) {
258
- var hasCatch = hasOwn.call(entry, "catchLoc"),
259
- hasFinally = hasOwn.call(entry, "finallyLoc");
260
- if (hasCatch && hasFinally) {
261
- if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
262
- if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
263
- } else if (hasCatch) {
264
- if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
265
- } else {
266
- if (!hasFinally) throw new Error("try statement without catch or finally");
267
- if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
268
- }
269
- }
270
- }
271
- },
272
- abrupt: function (type, arg) {
273
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
274
- var entry = this.tryEntries[i];
275
- if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
276
- var finallyEntry = entry;
277
- break;
278
- }
279
- }
280
- finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
281
- var record = finallyEntry ? finallyEntry.completion : {};
282
- return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
283
- },
284
- complete: function (record, afterLoc) {
285
- if ("throw" === record.type) throw record.arg;
286
- return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
287
- },
288
- finish: function (finallyLoc) {
289
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
290
- var entry = this.tryEntries[i];
291
- if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
292
- }
293
- },
294
- catch: function (tryLoc) {
295
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
296
- var entry = this.tryEntries[i];
297
- if (entry.tryLoc === tryLoc) {
298
- var record = entry.completion;
299
- if ("throw" === record.type) {
300
- var thrown = record.arg;
301
- resetTryEntry(entry);
302
- }
303
- return thrown;
304
- }
305
- }
306
- throw new Error("illegal catch attempt");
307
- },
308
- delegateYield: function (iterable, resultName, nextLoc) {
309
- return this.delegate = {
310
- iterator: values(iterable),
311
- resultName: resultName,
312
- nextLoc: nextLoc
313
- }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
314
- }
315
- }, exports;
316
- }
317
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
318
- try {
319
- var info = gen[key](arg);
320
- var value = info.value;
321
- } catch (error) {
322
- reject(error);
323
- return;
324
- }
325
- if (info.done) {
326
- resolve(value);
327
- } else {
328
- Promise.resolve(value).then(_next, _throw);
329
- }
330
- }
331
- function _asyncToGenerator(fn) {
332
- return function () {
333
- var self = this,
334
- args = arguments;
335
- return new Promise(function (resolve, reject) {
336
- var gen = fn.apply(self, args);
337
- function _next(value) {
338
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
339
- }
340
- function _throw(err) {
341
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
342
- }
343
- _next(undefined);
344
- });
345
- };
346
- }
347
- function _defineProperties(target, props) {
348
- for (var i = 0; i < props.length; i++) {
349
- var descriptor = props[i];
350
- descriptor.enumerable = descriptor.enumerable || false;
351
- descriptor.configurable = true;
352
- if ("value" in descriptor) descriptor.writable = true;
353
- Object.defineProperty(target, descriptor.key, descriptor);
354
- }
355
- }
356
- function _createClass(Constructor, protoProps, staticProps) {
357
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
358
- if (staticProps) _defineProperties(Constructor, staticProps);
359
- Object.defineProperty(Constructor, "prototype", {
360
- writable: false
361
- });
362
- return Constructor;
363
- }
364
- function _extends() {
365
- _extends = Object.assign ? Object.assign.bind() : function (target) {
366
- for (var i = 1; i < arguments.length; i++) {
367
- var source = arguments[i];
368
- for (var key in source) {
369
- if (Object.prototype.hasOwnProperty.call(source, key)) {
370
- target[key] = source[key];
371
- }
372
- }
373
- }
374
- return target;
375
- };
376
- return _extends.apply(this, arguments);
377
- }
378
-
379
- var Deferred = /*#__PURE__*/function () {
380
- function Deferred() {
381
- var _this = this;
382
- this.promise = new Promise(function (resolve, reject) {
383
- _this.reject = reject;
384
- _this.resolve = resolve;
385
- });
386
- }
387
- var _proto = Deferred.prototype;
388
- _proto.getPromise = function getPromise() {
389
- return this.promise;
390
- };
391
- return Deferred;
392
- }();
393
-
394
- // TODO: Improve -> `listeners` are unbounded -- don't use this in practice!
395
- function createEventEmitter() {
396
- var listeners = {};
397
- return {
398
- on: function on(key, fn) {
399
- listeners[key] = (listeners[key] || []).concat(fn);
400
- },
401
- off: function off(key, fn) {
402
- listeners[key] = (listeners[key] || []).filter(function (f) {
403
- return f !== fn;
404
- });
405
- },
406
- emit: function emit(key, data) {
407
- (listeners[key] || []).forEach(function (fn) {
408
- try {
409
- fn(data);
410
- } catch (_unused) {}
411
- });
412
- }
413
- };
414
- }
415
-
416
- var BaseAuthClient = /*#__PURE__*/function () {
417
- function BaseAuthClient() {
418
- var _this = this;
419
- this._state = {
420
- isAuthenticated: false,
421
- isInitialized: false,
422
- tokens: {}
423
- };
424
- // refresh queue - used to avoid concurrency issue during Token refresh
425
- this.refreshQ = [];
426
- this.eventEmitter = createEventEmitter();
427
- this.subscribers = new Set();
428
- // Should be declared like this to avoid binding issues when used by useSyncExternalStore
429
- this.subscribe = function (subscription) {
430
- _this.subscribers.add(subscription);
431
- return function () {
432
- return _this.subscribers["delete"](subscription);
433
- };
434
- };
435
- // Should be declared like this to avoid binding issues when used by useSyncExternalStore
436
- this.getSnapshot = function () {
437
- return _this._state;
438
- };
439
- }
440
- //
441
- // Getters
442
- //
443
- var _proto = BaseAuthClient.prototype;
444
- //
445
- // Public methods
446
- //
447
- _proto.init =
448
- /*#__PURE__*/
449
- function () {
450
- var _init = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
451
- var _this$onPostInit;
452
- return _regeneratorRuntime().wrap(function _callee$(_context) {
453
- while (1) {
454
- switch (_context.prev = _context.next) {
455
- case 0:
456
- _context.prev = 0;
457
- _context.next = 3;
458
- return this.onInit();
459
- case 3:
460
- this.setState({
461
- isInitialized: true
462
- });
463
- this.emit('initSuccess', undefined);
464
- _context.next = 11;
465
- break;
466
- case 7:
467
- _context.prev = 7;
468
- _context.t0 = _context["catch"](0);
469
- this.setState({
470
- isInitialized: false
471
- });
472
- this.emit('initFailed', _context.t0);
473
- case 11:
474
- _context.next = 13;
475
- return (_this$onPostInit = this.onPostInit) == null ? void 0 : _this$onPostInit.call(this);
476
- case 13:
477
- return _context.abrupt("return", this.isInitialized);
478
- case 14:
479
- case "end":
480
- return _context.stop();
481
- }
482
- }
483
- }, _callee, this, [[0, 7]]);
484
- }));
485
- function init() {
486
- return _init.apply(this, arguments);
487
- }
488
- return init;
489
- }();
490
- _proto.login = /*#__PURE__*/function () {
491
- var _login = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(credentials) {
492
- var _this$onPreLogin, _this$onPostLogin;
493
- var isSuccess, tokens;
494
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
495
- while (1) {
496
- switch (_context2.prev = _context2.next) {
497
- case 0:
498
- this.emit('loginStarted', undefined);
499
- _context2.next = 3;
500
- return (_this$onPreLogin = this.onPreLogin) == null ? void 0 : _this$onPreLogin.call(this);
501
- case 3:
502
- isSuccess = false;
503
- _context2.prev = 4;
504
- _context2.next = 7;
505
- return this.onLogin(credentials);
506
- case 7:
507
- tokens = _context2.sent;
508
- this.setState({
509
- isAuthenticated: true,
510
- tokens: tokens
511
- });
512
- this.emit('loginSuccess', undefined);
513
- isSuccess = true;
514
- _context2.next = 18;
515
- break;
516
- case 13:
517
- _context2.prev = 13;
518
- _context2.t0 = _context2["catch"](4);
519
- this.setState({
520
- isAuthenticated: false,
521
- tokens: {}
522
- });
523
- this.emit('loginFailed', _context2.t0);
524
- isSuccess = false;
525
- case 18:
526
- _context2.next = 20;
527
- return (_this$onPostLogin = this.onPostLogin) == null ? void 0 : _this$onPostLogin.call(this, isSuccess);
528
- case 20:
529
- return _context2.abrupt("return", this.isAuthenticated);
530
- case 21:
531
- case "end":
532
- return _context2.stop();
533
- }
534
- }
535
- }, _callee2, this, [[4, 13]]);
536
- }));
537
- function login(_x) {
538
- return _login.apply(this, arguments);
539
- }
540
- return login;
541
- }();
542
- _proto.refresh = /*#__PURE__*/function () {
543
- var _refresh = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(minValidity) {
544
- var deferred;
545
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
546
- while (1) {
547
- switch (_context3.prev = _context3.next) {
548
- case 0:
549
- deferred = new Deferred();
550
- this.runRefresh(deferred, minValidity);
551
- return _context3.abrupt("return", deferred.getPromise());
552
- case 3:
553
- case "end":
554
- return _context3.stop();
555
- }
556
- }
557
- }, _callee3, this);
558
- }));
559
- function refresh(_x2) {
560
- return _refresh.apply(this, arguments);
561
- }
562
- return refresh;
563
- }();
564
- _proto.logout = /*#__PURE__*/function () {
565
- var _logout = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
566
- var _this$onPreLogout, _this$onPostLogout;
567
- var isSuccess;
568
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
569
- while (1) {
570
- switch (_context4.prev = _context4.next) {
571
- case 0:
572
- this.emit('logoutStarted', undefined);
573
- _context4.next = 3;
574
- return (_this$onPreLogout = this.onPreLogout) == null ? void 0 : _this$onPreLogout.call(this);
575
- case 3:
576
- isSuccess = false;
577
- _context4.prev = 4;
578
- _context4.next = 7;
579
- return this.onLogout();
580
- case 7:
581
- this.setState({
582
- isAuthenticated: false,
583
- tokens: {}
584
- });
585
- this.emit('logoutSuccess', undefined);
586
- isSuccess = true;
587
- _context4.next = 16;
588
- break;
589
- case 12:
590
- _context4.prev = 12;
591
- _context4.t0 = _context4["catch"](4);
592
- this.emit('logoutFailed', _context4.t0);
593
- isSuccess = false;
594
- case 16:
595
- _context4.next = 18;
596
- return (_this$onPostLogout = this.onPostLogout) == null ? void 0 : _this$onPostLogout.call(this, isSuccess);
597
- case 18:
598
- case "end":
599
- return _context4.stop();
600
- }
601
- }
602
- }, _callee4, this, [[4, 12]]);
603
- }));
604
- function logout() {
605
- return _logout.apply(this, arguments);
606
- }
607
- return logout;
608
- }();
609
- _proto.on = function on(eventName, listener) {
610
- this.eventEmitter.on(eventName, listener);
611
- };
612
- _proto.off = function off(eventName, listener) {
613
- this.eventEmitter.off(eventName, listener);
614
- }
615
- //
616
- // Protected methods
617
- //
618
- ;
619
- _proto.setState = function setState(stateUpdate) {
620
- this._state = _extends({}, this._state, stateUpdate);
621
- this.notifySubscribers();
622
- }
623
- //
624
- // Private methods
625
- //
626
- ;
627
- _proto.runRefresh =
628
- /*#__PURE__*/
629
- function () {
630
- var _runRefresh = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(deferred, minValidity) {
631
- var _this$onPreRefresh, _this$onPostRefresh;
632
- var isAuthenticated, tokens, p;
633
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
634
- while (1) {
635
- switch (_context5.prev = _context5.next) {
636
- case 0:
637
- // Add deferred Promise to refresh queue
638
- this.refreshQ.push(deferred);
639
- // If refresh queue already has promises enqueued do not attempt a new refresh - one is already in progress
640
- if (!(this.refreshQ.length !== 1)) {
641
- _context5.next = 3;
642
- break;
643
- }
644
- return _context5.abrupt("return");
645
- case 3:
646
- this.emit('refreshStarted', undefined);
647
- _context5.next = 6;
648
- return (_this$onPreRefresh = this.onPreRefresh) == null ? void 0 : _this$onPreRefresh.call(this);
649
- case 6:
650
- isAuthenticated = false;
651
- tokens = {};
652
- _context5.prev = 8;
653
- _context5.next = 11;
654
- return this.onRefresh(minValidity);
655
- case 11:
656
- tokens = _context5.sent;
657
- isAuthenticated = true;
658
- this.emit('refreshSuccess', undefined);
659
- _context5.next = 20;
660
- break;
661
- case 16:
662
- _context5.prev = 16;
663
- _context5.t0 = _context5["catch"](8);
664
- isAuthenticated = false;
665
- this.emit('refreshFailed', _context5.t0);
666
- case 20:
667
- this.setState({
668
- isAuthenticated: isAuthenticated,
669
- tokens: tokens
670
- });
671
- _context5.next = 23;
672
- return (_this$onPostRefresh = this.onPostRefresh) == null ? void 0 : _this$onPostRefresh.call(this, isAuthenticated);
673
- case 23:
674
- for (p = this.refreshQ.pop(); p != null; p = this.refreshQ.pop()) {
675
- p.resolve(isAuthenticated);
676
- }
677
- case 24:
678
- case "end":
679
- return _context5.stop();
680
- }
681
- }
682
- }, _callee5, this, [[8, 16]]);
683
- }));
684
- function runRefresh(_x3, _x4) {
685
- return _runRefresh.apply(this, arguments);
686
- }
687
- return runRefresh;
688
- }();
689
- _proto.emit = function emit(eventName, error) {
690
- this.eventEmitter.emit(eventName, error);
691
- };
692
- _proto.notifySubscribers = function notifySubscribers() {
693
- this.subscribers.forEach(function (s) {
694
- try {
695
- s();
696
- } catch (_unused) {}
697
- });
698
- };
699
- _createClass(BaseAuthClient, [{
700
- key: "isInitialized",
701
- get: function get() {
702
- return this._state.isInitialized;
703
- }
704
- }, {
705
- key: "isAuthenticated",
706
- get: function get() {
707
- return this._state.isAuthenticated;
708
- }
709
- }, {
710
- key: "tokens",
711
- get: function get() {
712
- return this._state.tokens;
713
- }
714
- }]);
715
- return BaseAuthClient;
716
- }();
717
-
718
- function createAuth(authClient) {
719
- // Create a React context containing a BaseAuthClient instance.
720
- var authContext = React.createContext(null);
721
- // Create the React Context Provider for the BaseAuthClient instance.
722
- var AuthProvider = function AuthProvider(_ref) {
723
- var children = _ref.children,
724
- ErrorComponent = _ref.ErrorComponent,
725
- LoadingComponent = _ref.LoadingComponent;
726
- var _useState = React.useState(false),
727
- isInitFailed = _useState[0],
728
- setInitFailed = _useState[1];
729
- var _useSyncExternalStore = shim.useSyncExternalStore(authClient.subscribe, authClient.getSnapshot),
730
- isAuthenticated = _useSyncExternalStore.isAuthenticated,
731
- isInitialized = _useSyncExternalStore.isInitialized;
732
- React.useEffect(function () {
733
- function initAuthClient() {
734
- return _initAuthClient.apply(this, arguments);
735
- } // Init AuthClient
736
- function _initAuthClient() {
737
- _initAuthClient = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
738
- var initSuccess;
739
- return _regeneratorRuntime().wrap(function _callee$(_context) {
740
- while (1) {
741
- switch (_context.prev = _context.next) {
742
- case 0:
743
- _context.next = 2;
744
- return authClient.init();
745
- case 2:
746
- initSuccess = _context.sent;
747
- setInitFailed(!initSuccess);
748
- case 4:
749
- case "end":
750
- return _context.stop();
751
- }
752
- }
753
- }, _callee);
754
- }));
755
- return _initAuthClient.apply(this, arguments);
756
- }
757
- initAuthClient();
758
- }, []);
759
- if (!!ErrorComponent && isInitFailed) {
760
- return ErrorComponent;
761
- }
762
- if (!!LoadingComponent && !isInitialized) {
763
- return LoadingComponent;
764
- }
765
- return React__default.createElement(authContext.Provider, {
766
- value: {
767
- authClient: authClient,
768
- isAuthenticated: isAuthenticated,
769
- isInitialized: isInitialized
770
- }
771
- }, children);
772
- };
773
- // Retrieve the AuthClient from the current context
774
- var useAuthClient = function useAuthClient() {
775
- var ctx = React.useContext(authContext);
776
- if (!ctx) {
777
- throw new Error('useAuthClient hook should be used inside AuthProvider');
778
- }
779
- return ctx.authClient;
780
- };
781
- return {
782
- AuthProvider: AuthProvider,
783
- useAuthClient: useAuthClient
784
- };
785
- }
786
-
787
- exports.BaseAuthClient = BaseAuthClient;
788
- exports.createAuth = createAuth;
789
- //# sourceMappingURL=react-auth.cjs.development.js.map