@clicktap/state 0.1.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.esm.js ADDED
@@ -0,0 +1,990 @@
1
+ import _toConsumableArray from '@babel/runtime/helpers/esm/toConsumableArray';
2
+ import _regeneratorRuntime from '@babel/runtime/regenerator';
3
+ import { setup, assign, fromPromise, createActor, fromCallback, sendTo } from 'xstate';
4
+ import axios from 'axios';
5
+ import { jsx } from 'react/jsx-runtime';
6
+ import { createContext, useContext, useState, useEffect, cloneElement } from 'react';
7
+ import crypto from 'crypto';
8
+
9
+ /******************************************************************************
10
+ Copyright (c) Microsoft Corporation.
11
+
12
+ Permission to use, copy, modify, and/or distribute this software for any
13
+ purpose with or without fee is hereby granted.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
16
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
17
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
18
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
19
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
20
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21
+ PERFORMANCE OF THIS SOFTWARE.
22
+ ***************************************************************************** */
23
+
24
+ function __awaiter(thisArg, _arguments, P, generator) {
25
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
26
+ return new (P || (P = Promise))(function (resolve, reject) {
27
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
28
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
29
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
30
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
31
+ });
32
+ }
33
+
34
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
35
+ var e = new Error(message);
36
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
37
+ };
38
+
39
+ function request(url, options) {
40
+ return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
41
+ var response;
42
+ return _regeneratorRuntime.wrap(function _callee$(_context) {
43
+ while (1) {
44
+ switch (_context.prev = _context.next) {
45
+ case 0:
46
+ _context.next = 2;
47
+ return fetch(url, options);
48
+ case 2:
49
+ response = _context.sent;
50
+ if (!(response.status === 200)) {
51
+ _context.next = 5;
52
+ break;
53
+ }
54
+ return _context.abrupt("return", response.json());
55
+ case 5:
56
+ return _context.abrupt("return", Promise.resolve({
57
+ message: response.statusText,
58
+ success: false
59
+ }));
60
+ case 6:
61
+ case "end":
62
+ return _context.stop();
63
+ }
64
+ }
65
+ }, _callee);
66
+ }));
67
+ }
68
+ /**
69
+ * still need a factory pattern to pass context and state
70
+ * until xstate supports both
71
+ */
72
+ // export const authMachine = (
73
+ // initialContext: Partial<AuthMachineContext> = {},
74
+ // initialState = 'refreshing'
75
+ // ) => {
76
+ var authMachine = setup({
77
+ types: {
78
+ context: {},
79
+ events: {},
80
+ input: {}
81
+ },
82
+ actions: {
83
+ setUserContext: assign(function (_ref) {
84
+ var context = _ref.context,
85
+ event = _ref.event;
86
+ if (!event.type.includes('xstate.done.actor')) return context;
87
+ var e = event;
88
+ if (e.output.type !== 'AUTHENTICATE_SUCCESS') return context;
89
+ return {
90
+ accessToken: e.output.accessToken,
91
+ ignoreRefreshToken: false
92
+ };
93
+ }),
94
+ unsetUserContext: assign(function () {
95
+ return {
96
+ user: null,
97
+ accessToken: '',
98
+ refreshToken: '',
99
+ ignoreRefreshToken: false
100
+ };
101
+ }),
102
+ setAccessToken: assign(function (_ref2) {
103
+ var context = _ref2.context,
104
+ event = _ref2.event;
105
+ if (!event.type.includes('xstate.done.actor')) return context;
106
+ var e = event;
107
+ if (e.output.type !== 'REFRESH_TOKEN_SUCCESS') return context;
108
+ return {
109
+ accessToken: e.output.accessToken,
110
+ ignoreRefreshToken: false
111
+ };
112
+ }),
113
+ unsetRefreshToken: assign(function () {
114
+ // there shouldn't be a problem with not checking event here
115
+ // since we can only hit this action from the refresh actor
116
+ // onDone or onError
117
+ return {
118
+ refreshToken: ''
119
+ };
120
+ }),
121
+ setIgnoreRefreshToken: assign(function () {
122
+ return {
123
+ ignoreRefreshToken: true
124
+ };
125
+ }),
126
+ addError: assign(function (_ref3) {
127
+ var context = _ref3.context,
128
+ event = _ref3.event;
129
+ if (!event.type.includes('xstate.error.actor')) return context;
130
+ var e = event;
131
+ return {
132
+ errors: [].concat(_toConsumableArray(context.errors), [String(e.error).replace('Error: ', '')])
133
+ };
134
+ }),
135
+ clearErrors: assign(function () {
136
+ return {
137
+ errors: []
138
+ };
139
+ })
140
+ // onLogin: ({ event, self }) => {
141
+ // console.log('onLogin', event, self);
142
+ // return raise({ type: 'AFTER_LOGGED_IN' });
143
+ // if (!event.type.includes('xstate.done.actor')) return;
144
+ // const e = event as DoneActorEvent<AuthenticateSuccessEvent>;
145
+ // if (
146
+ // e.output.type !== 'AUTHENTICATE_SUCCESS' ||
147
+ // self.getSnapshot().value !== 'loggedIn'
148
+ // )
149
+ // return;
150
+ // // eslint-disable-next-line consistent-return
151
+ // return raise({ type: 'AFTER_LOGGED_IN' });
152
+ // // if (!params) return context;
153
+ // // if (!('callback' in params) || typeof params.callback !== 'function')
154
+ // // return context;
155
+ // // params.callback();
156
+ // // return context;
157
+ // },
158
+ },
159
+
160
+ actors: {
161
+ refreshAccessToken: fromPromise(function (_ref4) {
162
+ var input = _ref4.input;
163
+ return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
164
+ var response, res, data, _data;
165
+ return _regeneratorRuntime.wrap(function _callee2$(_context2) {
166
+ while (1) {
167
+ switch (_context2.prev = _context2.next) {
168
+ case 0:
169
+ if (!(typeof window === 'undefined')) {
170
+ _context2.next = 18;
171
+ break;
172
+ }
173
+ if (!(input.context.refreshToken === '')) {
174
+ _context2.next = 3;
175
+ break;
176
+ }
177
+ throw new Error('Unauthorized.');
178
+ case 3:
179
+ _context2.prev = 3;
180
+ _context2.next = 6;
181
+ return axios.post(input.context.endpoints.ssrRefresh, {
182
+ grant_type: 'refresh_token'
183
+ }, {
184
+ headers: {
185
+ Cookie: "refresh_token=".concat(input.context.refreshToken),
186
+ 'Content-Type': 'application/json'
187
+ },
188
+ withCredentials: true
189
+ });
190
+ case 6:
191
+ res = _context2.sent;
192
+ data = res.data;
193
+ if (!(typeof data.accessToken === 'undefined')) {
194
+ _context2.next = 10;
195
+ break;
196
+ }
197
+ throw new Error('Unauthorized.');
198
+ case 10:
199
+ return _context2.abrupt("return", {
200
+ type: 'REFRESH_TOKEN_SUCCESS',
201
+ accessToken: data.accessToken
202
+ });
203
+ case 13:
204
+ _context2.prev = 13;
205
+ _context2.t0 = _context2["catch"](3);
206
+ throw new Error('Could not complete refresh request (server)');
207
+ case 16:
208
+ _context2.next = 25;
209
+ break;
210
+ case 18:
211
+ _context2.next = 20;
212
+ return request(input.context.endpoints.refresh, {
213
+ method: 'POST',
214
+ mode: 'cors',
215
+ credentials: 'include',
216
+ headers: {
217
+ 'Content-Type': 'application/json'
218
+ },
219
+ body: JSON.stringify({
220
+ grant_type: 'refresh_token'
221
+ // client_id: 'default',
222
+ // client_secret: 'Password123!',
223
+ // scope: 'default',
224
+ }).toString()
225
+ });
226
+ case 20:
227
+ response = _context2.sent;
228
+ _data = response;
229
+ if (!(typeof _data.accessToken === 'undefined')) {
230
+ _context2.next = 24;
231
+ break;
232
+ }
233
+ throw new Error('Unauthorized.');
234
+ case 24:
235
+ return _context2.abrupt("return", {
236
+ type: 'REFRESH_TOKEN_SUCCESS',
237
+ accessToken: _data.accessToken
238
+ });
239
+ case 25:
240
+ case "end":
241
+ return _context2.stop();
242
+ }
243
+ }
244
+ }, _callee2, null, [[3, 13]]);
245
+ }));
246
+ }),
247
+ authenticate: fromPromise(function (_ref5) {
248
+ var input = _ref5.input;
249
+ return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
250
+ var _a, _b, response, data;
251
+ return _regeneratorRuntime.wrap(function _callee3$(_context3) {
252
+ while (1) {
253
+ switch (_context3.prev = _context3.next) {
254
+ case 0:
255
+ _context3.next = 2;
256
+ return request(input.context.endpoints.login, {
257
+ method: 'POST',
258
+ mode: 'cors',
259
+ credentials: 'include',
260
+ headers: {
261
+ 'Content-Type': 'application/json'
262
+ },
263
+ body: JSON.stringify({
264
+ username: input.username,
265
+ password: input.password
266
+ }).toString()
267
+ });
268
+ case 2:
269
+ response = _context3.sent;
270
+ /** @todo do we need to handle different status codes here...like what if the service is down? */
271
+ data = response;
272
+ if (data.success) {
273
+ _context3.next = 6;
274
+ break;
275
+ }
276
+ throw new Error((_b = (_a = data.message) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : 'Sign in failed. Please try again.');
277
+ case 6:
278
+ return _context3.abrupt("return", {
279
+ type: 'AUTHENTICATE_SUCCESS',
280
+ // user: data.user,
281
+ accessToken: data.accessToken
282
+ });
283
+ case 7:
284
+ case "end":
285
+ return _context3.stop();
286
+ }
287
+ }
288
+ }, _callee3);
289
+ }));
290
+ }),
291
+ unauthenticate: fromPromise(function (_ref6) {
292
+ var input = _ref6.input;
293
+ return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
294
+ return _regeneratorRuntime.wrap(function _callee4$(_context4) {
295
+ while (1) {
296
+ switch (_context4.prev = _context4.next) {
297
+ case 0:
298
+ _context4.next = 2;
299
+ return fetch(input.context.endpoints.logout, {
300
+ method: 'POST',
301
+ mode: 'cors',
302
+ credentials: 'include'
303
+ // headers: {
304
+ // 'Access-Control-Allow-Origin': 'https://middleware-clicktap.local-rmgmedia.com',
305
+ // 'Access-Control-Allow-Credentials': 'true',
306
+ // },
307
+ });
308
+ case 2:
309
+ return _context4.abrupt("return", {
310
+ type: 'UNAUTHENTICATE'
311
+ });
312
+ case 3:
313
+ case "end":
314
+ return _context4.stop();
315
+ }
316
+ }
317
+ }, _callee4);
318
+ }));
319
+ })
320
+ }
321
+ }).createMachine({
322
+ id: 'auth',
323
+ context: function context(_ref7) {
324
+ var input = _ref7.input;
325
+ var _a, _b, _c, _d;
326
+ return {
327
+ user: null,
328
+ accessToken: '',
329
+ refreshToken: (_b = (_a = input === null || input === void 0 ? void 0 : input.initialContext) === null || _a === void 0 ? void 0 : _a.refreshToken) !== null && _b !== void 0 ? _b : '',
330
+ /**
331
+ * If unauthenticating fails, we need a way to ignore the refresh token on subsequent access token refresh.
332
+ * This would be set to true done/error of unauthenticate service, and false on done of authenticate service
333
+ */
334
+ ignoreRefreshToken: false,
335
+ endpoints: (_d = (_c = input === null || input === void 0 ? void 0 : input.initialContext) === null || _c === void 0 ? void 0 : _c.endpoints) !== null && _d !== void 0 ? _d : {
336
+ login: '',
337
+ logout: '',
338
+ refresh: '',
339
+ ssrRefresh: ''
340
+ },
341
+ errors: []
342
+ };
343
+ },
344
+ initial: 'refreshing',
345
+ states: {
346
+ authenticating: {
347
+ invoke: {
348
+ src: 'authenticate',
349
+ input: function input(_ref8) {
350
+ var context = _ref8.context,
351
+ event = _ref8.event;
352
+ if (event.type !== 'LOGIN') {
353
+ /** @todo how to use error handling here? */
354
+ return {
355
+ context: context,
356
+ username: '',
357
+ password: ''
358
+ };
359
+ }
360
+ return {
361
+ context: context,
362
+ username: event.username,
363
+ password: event.password
364
+ };
365
+ },
366
+ onDone: [{
367
+ actions: 'setUserContext',
368
+ target: 'loggedIn'
369
+ }],
370
+ onError: [{
371
+ actions: 'addError',
372
+ target: 'loggedOut'
373
+ }]
374
+ }
375
+ },
376
+ unauthenticating: {
377
+ invoke: {
378
+ src: 'unauthenticate',
379
+ input: function input(_ref9) {
380
+ var context = _ref9.context;
381
+ return {
382
+ context: context
383
+ };
384
+ },
385
+ onDone: [{
386
+ actions: 'unsetUserContext',
387
+ target: 'loggedOut'
388
+ }],
389
+ onError: [{
390
+ actions: ['unsetUserContext', 'setIgnoreRefreshToken'],
391
+ target: 'loggedOut'
392
+ }]
393
+ }
394
+ },
395
+ refreshing: {
396
+ invoke: {
397
+ src: 'refreshAccessToken',
398
+ input: function input(_ref10) {
399
+ var context = _ref10.context;
400
+ return {
401
+ context: context
402
+ };
403
+ },
404
+ onDone: [{
405
+ actions: ['unsetRefreshToken', 'setAccessToken'],
406
+ target: 'loggedIn'
407
+ }],
408
+ onError: [{
409
+ actions: 'unsetRefreshToken',
410
+ target: 'unauthenticating'
411
+ }]
412
+ }
413
+ },
414
+ loggedOut: {
415
+ on: {
416
+ LOGIN: {
417
+ target: 'authenticating'
418
+ },
419
+ CLEAR_ERRORS: {
420
+ actions: 'clearErrors'
421
+ }
422
+ }
423
+ },
424
+ loggedIn: {
425
+ after: {
426
+ // 14min (840000ms), jwt access token expires in 15min
427
+ 840000: {
428
+ guard: function guard() {
429
+ return typeof window !== 'undefined';
430
+ },
431
+ target: 'refreshing'
432
+ }
433
+ },
434
+ on: {
435
+ LOGOUT: {
436
+ target: 'unauthenticating'
437
+ },
438
+ CLEAR_ERRORS: {
439
+ actions: 'clearErrors'
440
+ }
441
+ // AFTER_LOGGED_IN: {
442
+ // target: 'afterLoggedIn',
443
+ // },
444
+ }
445
+ }
446
+ // onLogin: {
447
+ // always: {
448
+ // target: 'loggedIn',
449
+ // },
450
+ // },
451
+ // afterLoggedOut: {
452
+ // always: {
453
+ // target: 'loggedOut',
454
+ // },
455
+ // },
456
+ }
457
+ });
458
+
459
+ var AuthContext = /*#__PURE__*/createContext({});
460
+ var useAuth = function useAuth() {
461
+ var actor = useContext(AuthContext);
462
+ var _useState = useState(actor.getSnapshot().value === 'loggedIn'),
463
+ isLoggedIn = _useState[0],
464
+ setILoggedIn = _useState[1];
465
+ useEffect(function () {
466
+ var subscription = actor.subscribe(function (observer) {
467
+ if (observer.value === 'loggedIn' || observer.value === 'loggedOut') {
468
+ setILoggedIn(observer.value === 'loggedIn');
469
+ }
470
+ });
471
+ return function () {
472
+ subscription.unsubscribe();
473
+ };
474
+ }, [actor]);
475
+ return {
476
+ authActor: actor,
477
+ isLoggedIn: isLoggedIn
478
+ };
479
+ };
480
+ var useUser = function useUser() {
481
+ return useContext(AuthContext).getSnapshot().context.user;
482
+ };
483
+ /**
484
+ * runs on server side as part of withAuth HOF
485
+ *
486
+ * @todo should probably update signature to pass Partial<AuthContext> and
487
+ * Options, endpoints should probably be moved into context
488
+ */
489
+ var getAuth = function getAuth() {
490
+ var refreshToken = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
491
+ var options
492
+ // eslint-disable-next-line @typescript-eslint/require-await
493
+ = arguments.length > 1 ? arguments[1] : undefined;
494
+ return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
495
+ return _regeneratorRuntime.wrap(function _callee$(_context) {
496
+ while (1) {
497
+ switch (_context.prev = _context.next) {
498
+ case 0:
499
+ if (!(typeof window !== 'undefined')) {
500
+ _context.next = 3;
501
+ break;
502
+ }
503
+ // eslint-disable-next-line no-console
504
+ console.warn('App.getInitialProps::getAuth should not be run on the frontend. You are probably missing getServerSideProps in your page.');
505
+ return _context.abrupt("return", createActor(authMachine, {
506
+ inspect: options.inspect
507
+ }).start());
508
+ case 3:
509
+ return _context.abrupt("return", createActor(authMachine, {
510
+ input: {
511
+ initialContext: {
512
+ endpoints: options.endpoints,
513
+ refreshToken: refreshToken
514
+ }
515
+ },
516
+ inspect: options.inspect
517
+ }).start());
518
+ case 4:
519
+ case "end":
520
+ return _context.stop();
521
+ }
522
+ }
523
+ }, _callee);
524
+ }));
525
+ };
526
+ function AuthProvider(_ref) {
527
+ var actor = _ref.actor,
528
+ children = _ref.children;
529
+ return jsx(AuthContext.Provider, {
530
+ value: actor,
531
+ children: children
532
+ });
533
+ }
534
+
535
+ var timerMachine = setup({
536
+ types: {
537
+ context: {},
538
+ events: {},
539
+ input: {}
540
+ }
541
+ }).createMachine({
542
+ id: 'timer',
543
+ initial: 'running',
544
+ context: function context(_ref) {
545
+ var input = _ref.input;
546
+ var _a;
547
+ return {
548
+ elapsed: 0,
549
+ duration: (_a = input.initialContext.duration) !== null && _a !== void 0 ? _a : 3000,
550
+ interval: 100,
551
+ intervalId: null
552
+ };
553
+ },
554
+ states: {
555
+ paused: {
556
+ on: {
557
+ // START_TIMER: {
558
+ // target: 'running',
559
+ // cond: (context) => context.elapsed < context.duration,
560
+ // },
561
+ RESUME_TIMER: {
562
+ target: 'running',
563
+ guard: function guard(_ref2) {
564
+ var context = _ref2.context;
565
+ return context.elapsed < context.duration;
566
+ }
567
+ }
568
+ }
569
+ },
570
+ running: {
571
+ // invoke: {
572
+ // src:
573
+ // ({ context }) =>
574
+ // (send) => {
575
+ // // eslint-disable-next-line no-console
576
+ // // console.log('context.interval: ', context.interval);
577
+ // const interval = setInterval(() => {
578
+ // send('TICK');
579
+ // }, context.interval);
580
+ // return () => {
581
+ // clearInterval(interval);
582
+ // };
583
+ // },
584
+ // },
585
+ invoke: {
586
+ input: function input(_ref3) {
587
+ var context = _ref3.context;
588
+ return {
589
+ interval: context.interval
590
+ };
591
+ },
592
+ src: fromCallback(function (_ref4) {
593
+ var sendBack = _ref4.sendBack,
594
+ input = _ref4.input;
595
+ var interval = setInterval(function () {
596
+ sendBack({
597
+ type: 'TICK'
598
+ });
599
+ }, input.interval);
600
+ return function () {
601
+ clearInterval(interval);
602
+ };
603
+ }
604
+ // eslint-disable-next-line @typescript-eslint/require-await
605
+ // async ({ input }) => {
606
+ // console.log('interval: ', input.interval);
607
+ // return { type: 'TICK' };
608
+ // // console.log('in running invoke');
609
+ // // const interval = setInterval(() => {
610
+ // // raise({ type: 'TICK' });
611
+ // // }, input.interval);
612
+ // // return () => {
613
+ // // clearInterval(interval);
614
+ // // };
615
+ // }
616
+ )
617
+ },
618
+
619
+ always: [{
620
+ target: 'completed',
621
+ guard: function guard(_ref5) {
622
+ var context = _ref5.context;
623
+ return context.elapsed >= context.duration;
624
+ }
625
+ }],
626
+ on: {
627
+ TICK: {
628
+ actions: assign(function (_ref6) {
629
+ var context = _ref6.context,
630
+ event = _ref6.event;
631
+ if (event.type !== 'TICK') return context;
632
+ return {
633
+ elapsed: context.elapsed + context.interval
634
+ };
635
+ })
636
+ },
637
+ PAUSE_TIMER: {
638
+ target: 'paused'
639
+ }
640
+ }
641
+ },
642
+ completed: {
643
+ type: 'final'
644
+ }
645
+ }
646
+ });
647
+
648
+ // circular reference, don't want library depending on UI component specific to one app
649
+ // import { Notification } from "@waytrade/components/app/Toast/Notification";
650
+ var toastMachine = setup({
651
+ types: {
652
+ context: {},
653
+ events: {},
654
+ input: {}
655
+ },
656
+ actions: {
657
+ addItem: assign(function (_ref) {
658
+ var context = _ref.context,
659
+ event = _ref.event;
660
+ var _a, _b;
661
+ if (event.type !== 'ADD_ITEM') return context;
662
+ var id = "notification-".concat(crypto.randomBytes(16).toString('hex'));
663
+ var duration = (_a = event.duration) !== null && _a !== void 0 ? _a : context.duration;
664
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
665
+ var notification = /*#__PURE__*/cloneElement(event.item, Object.assign({
666
+ duration: duration,
667
+ id: id,
668
+ key: (_b = event.item.key) !== null && _b !== void 0 ? _b : id
669
+ }, event.item.props));
670
+ var item = {
671
+ duration: duration,
672
+ id: id,
673
+ element: notification
674
+ };
675
+ var updatedItems = context.items;
676
+ if (context.order === 'desc') {
677
+ updatedItems.push(item);
678
+ } else {
679
+ updatedItems.unshift(item);
680
+ }
681
+ return {
682
+ items: updatedItems,
683
+ activeItem: id
684
+ };
685
+ }),
686
+ removeItem: assign(function (_ref2) {
687
+ var context = _ref2.context,
688
+ event = _ref2.event;
689
+ // console.log('toast removeItem event: ', event);
690
+ if (event.type !== 'REMOVE_ITEM' && event.type !== 'xstate.done.actor.timer'
691
+ // event.type !== 'REMOVE_ITEM' &&
692
+ // event.type !== 'xstate.after(ITEM_TIMEOUT)#toast.active' &&
693
+ // event.type !== 'done.invoke.timer'
694
+ ) return context;
695
+ var updatedItems = context.items;
696
+ if (context.order === 'desc') {
697
+ updatedItems.pop();
698
+ return {
699
+ items: updatedItems,
700
+ activeItem: updatedItems.length > 0 ? updatedItems[updatedItems.length - 1].id : null
701
+ };
702
+ }
703
+ updatedItems.shift();
704
+ return {
705
+ items: updatedItems,
706
+ activeItem: updatedItems.length > 0 ? updatedItems[0].id : null
707
+ };
708
+ })
709
+ },
710
+ delays: {
711
+ ITEM_TIMEOUT: function ITEM_TIMEOUT(_ref3) {
712
+ var context = _ref3.context;
713
+ var _a;
714
+ return (_a = context.items[context.items.length - 1].duration) !== null && _a !== void 0 ? _a : context.duration;
715
+ }
716
+ },
717
+ guards: {
718
+ itemHasTimeout: function itemHasTimeout(_ref4) {
719
+ var context = _ref4.context;
720
+ return context.items[context.items.length - 1].duration > 0 || context.duration > 0;
721
+ }
722
+ }
723
+ }).createMachine({
724
+ id: 'toast',
725
+ context: {
726
+ items: [],
727
+ order: 'desc',
728
+ duration: 0,
729
+ activeItem: null
730
+ },
731
+ initial: 'idle',
732
+ states: {
733
+ idle: {
734
+ on: {
735
+ ADD_ITEM: {
736
+ target: 'adding'
737
+ }
738
+ }
739
+ },
740
+ active: {
741
+ invoke: {
742
+ id: 'timer',
743
+ src: timerMachine,
744
+ input: function input(_ref5) {
745
+ var context = _ref5.context;
746
+ var _a;
747
+ return {
748
+ initialContext: {
749
+ duration: (_a = context.items[context.items.length - 1].duration) !== null && _a !== void 0 ? _a : context.duration
750
+ }
751
+ };
752
+ },
753
+ onDone: {
754
+ target: 'removing',
755
+ guard: 'itemHasTimeout'
756
+ }
757
+ // data: Object.assign(timerMachine.context, {
758
+ // duration: (context: ToastMachineContext) =>
759
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return
760
+ // context.items[context.items.length - 1].duration ??
761
+ // context.duration,
762
+ // }),
763
+ },
764
+
765
+ on: {
766
+ ADD_ITEM: {
767
+ // actions: sendTo('timer', 'PAUSE_TIMER'),
768
+ target: 'adding'
769
+ },
770
+ REMOVE_ITEM: {
771
+ target: 'removing'
772
+ },
773
+ SET_IDLE: {
774
+ target: 'idle'
775
+ },
776
+ RESUME_TIMER: {
777
+ actions: sendTo('timer', {
778
+ type: 'RESUME_TIMER'
779
+ })
780
+ // cond: (context) => context.duration > 0,
781
+ },
782
+
783
+ PAUSE_TIMER: {
784
+ actions: sendTo('timer', {
785
+ type: 'PAUSE_TIMER'
786
+ })
787
+ // cond: (context) => context.duration > 0,
788
+ }
789
+ }
790
+ // after: {
791
+ // ITEM_TIMEOUT: {
792
+ // target: 'removing',
793
+ // cond: 'itemHasTimeout',
794
+ // },
795
+ // },
796
+ },
797
+
798
+ adding: {
799
+ entry: ['addItem'],
800
+ on: {
801
+ SET_IDLE: {
802
+ target: 'idle'
803
+ },
804
+ SET_ACTIVE: {
805
+ target: 'active'
806
+ }
807
+ }
808
+ },
809
+ removing: {
810
+ entry: 'removeItem',
811
+ on: {
812
+ SET_IDLE: {
813
+ target: 'idle'
814
+ },
815
+ SET_ACTIVE: {
816
+ target: 'active'
817
+ }
818
+ }
819
+ }
820
+ }
821
+ });
822
+ // export const toastMachine =
823
+ // /** @xstate-layout N4IgpgJg5mDOIC5QBcD2BDWyB0BLCANmAMQCCAIuQPoCSAKgKICyA2gAwC6ioADqrLmS5UAO24gAHogCMAZgCs2AGzS2SgBxKA7AE4lO2ToAsAGhABPRAFoj6gL52zaTDnQBjIQDcSEUWDwinqgA1v5CALZgAE7sXEggfAJCouJSCEpsOspaOQay0kqyAExKZpYIReps2LY6mmxG+kUKWkYOThhY2O5eJBTU9Myx4omCwmLxabKF2NKN8kpFbPls8gpl1vLqykXyasaNhdJFWu0gzl09uN7EAErMAPIAagy0jKycI-xjKZOIi9sDPI9EZgYV1LItBsEIYlNg9NIdGxKki1jkzhdXB5riQAMoMOi0cgAGQYw3io2SE1AaTkWS0RQOSKWEK0c2hzWkNUWJy0Skah1sGM6WN6dwYuIAqkxXnQaDLbuTeN8qakZPIuXylhktAppgUitDilpsJpQeo9KsVOoCsKXN1sTcAAqkSX4qhyhVKhIq8ZqirSbaZeTyLRbVnqVqyaHSaQm45mtirKo6Eo6O2XCAQXAiKDEfGEmgksmfCm+340xC2bCh3XGrTLfR8+TQqxFJbYTIoow6HStBshjOuLM5vMFqikADCcpe3spfr+MKMmsZbDmFvU6jBRtW8I3IcMBT7Q+wUTA4VQnlH+YJRNJc-L1MkiHURiKps0DIWKhyIZjehqfc1h0I8GyUE8zwvK9cxvQkpxnEs4mVJIF0rBBU1kWZVw1WtgSMUwLHVIxsEqIxjVDIF5CFM4RFQCA4HETEvhQitnwQKxYxNOoDFjbQ2RtfRW1kfJO1THjA1sVRZBPfAiGYn4nzSKx9D3cS+MDI9-zhWot2A0C1BPK5vHk1VF1kIwuOZPICmKYEtMAuoDxAptlkMkdcxM1C2MMYjKhKXUlH5DUimkVsijImsxMMcLpjDUMIPPS9R081i0i3OE10afI42XcKW0ImFgRrYE5FBWx1F2cyHAcIA */
824
+ // createMachine<ToastMachineContext, ToastMachineEvents>(
825
+ // {
826
+ // context: { items: [], order: 'desc', duration: 0, activeItem: null },
827
+ // predictableActionArguments: true,
828
+ // id: 'toast',
829
+ // initial: 'idle',
830
+ // states: {
831
+ // idle: {
832
+ // on: {
833
+ // ADD_ITEM: {
834
+ // target: 'adding',
835
+ // },
836
+ // },
837
+ // },
838
+ // active: {
839
+ // invoke: {
840
+ // id: 'timer',
841
+ // src: timerMachine,
842
+ // onDone: {
843
+ // target: 'removing',
844
+ // cond: 'itemHasTimeout',
845
+ // },
846
+ // data: Object.assign(timerMachine.context, {
847
+ // duration: (context: ToastMachineContext) =>
848
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return
849
+ // context.items[context.items.length - 1].duration ??
850
+ // context.duration,
851
+ // }),
852
+ // },
853
+ // on: {
854
+ // ADD_ITEM: {
855
+ // // actions: sendTo('timer', 'PAUSE_TIMER'),
856
+ // target: 'adding',
857
+ // },
858
+ // REMOVE_ITEM: {
859
+ // target: 'removing',
860
+ // },
861
+ // SET_IDLE: {
862
+ // target: 'idle',
863
+ // },
864
+ // RESUME_TIMER: {
865
+ // actions: sendTo('timer', 'RESUME_TIMER'),
866
+ // // cond: (context) => context.duration > 0,
867
+ // },
868
+ // PAUSE_TIMER: {
869
+ // actions: sendTo('timer', 'PAUSE_TIMER'),
870
+ // // cond: (context) => context.duration > 0,
871
+ // },
872
+ // },
873
+ // // after: {
874
+ // // ITEM_TIMEOUT: {
875
+ // // target: 'removing',
876
+ // // cond: 'itemHasTimeout',
877
+ // // },
878
+ // // },
879
+ // },
880
+ // adding: {
881
+ // entry: ['addItem'],
882
+ // on: {
883
+ // SET_IDLE: {
884
+ // target: 'idle',
885
+ // },
886
+ // SET_ACTIVE: {
887
+ // target: 'active',
888
+ // },
889
+ // },
890
+ // },
891
+ // removing: {
892
+ // entry: 'removeItem',
893
+ // on: {
894
+ // SET_IDLE: {
895
+ // target: 'idle',
896
+ // },
897
+ // SET_ACTIVE: {
898
+ // target: 'active',
899
+ // },
900
+ // },
901
+ // },
902
+ // },
903
+ // },
904
+ // {
905
+ // actions: {
906
+ // addItem: assign((context, event) => {
907
+ // if (event.type !== 'ADD_ITEM') return;
908
+ // const id = `notification-${crypto.randomBytes(16).toString('hex')}`;
909
+ // const duration = event.duration ?? context.duration;
910
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
911
+ // const notification = cloneElement(event.item, {
912
+ // duration,
913
+ // id,
914
+ // key: event.item.key ?? id,
915
+ // ...event.item.props,
916
+ // });
917
+ // const item = {
918
+ // duration,
919
+ // id,
920
+ // element: notification,
921
+ // };
922
+ // if (context.order === 'desc') {
923
+ // context.items.push(item);
924
+ // } else {
925
+ // context.items.unshift(item);
926
+ // }
927
+ // context.activeItem = id;
928
+ // }),
929
+ // removeItem: assign((context, event) => {
930
+ // if (
931
+ // event.type !== 'REMOVE_ITEM' &&
932
+ // event.type !== 'xstate.after(ITEM_TIMEOUT)#toast.active' &&
933
+ // event.type !== 'done.invoke.timer'
934
+ // )
935
+ // return;
936
+ // if (context.order === 'desc') {
937
+ // context.items.pop();
938
+ // context.activeItem =
939
+ // context.items.length > 0
940
+ // ? context.items[context.items.length - 1].id
941
+ // : null;
942
+ // } else {
943
+ // context.items.shift();
944
+ // context.activeItem =
945
+ // context.items.length > 0 ? context.items[0].id : null;
946
+ // }
947
+ // }),
948
+ // // startTimer: sendTo('timer', { type: 'START' }),
949
+ // },
950
+ // delays: {
951
+ // ITEM_TIMEOUT: (context) => {
952
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-return
953
+ // return (
954
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
955
+ // context.items[context.items.length - 1].duration ?? context.duration
956
+ // );
957
+ // },
958
+ // },
959
+ // guards: {
960
+ // itemHasTimeout: (context) => {
961
+ // return (
962
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
963
+ // context.items[context.items.length - 1].duration > 0 ||
964
+ // context.duration > 0
965
+ // );
966
+ // },
967
+ // },
968
+ // }
969
+ // );
970
+
971
+ var ToastContext = /*#__PURE__*/createContext({});
972
+ var useToast = function useToast() {
973
+ return useContext(ToastContext);
974
+ };
975
+ function ToastProvider(_ref) {
976
+ var children = _ref.children,
977
+ actor = _ref.actor;
978
+ // const toastService = interpret(toastMachine, {
979
+ // devTools: options.devTools,
980
+ // }).start(state);
981
+ // toastService.subscribe((s) => {
982
+ // setState(s);
983
+ // });
984
+ return jsx(ToastContext.Provider, {
985
+ value: actor,
986
+ children: children
987
+ });
988
+ }
989
+
990
+ export { AuthContext, AuthProvider, ToastContext, ToastProvider, authMachine, getAuth, timerMachine, toastMachine, useAuth, useToast, useUser };