@clicktap/state 0.2.0 → 0.9.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.js DELETED
@@ -1,724 +0,0 @@
1
- import _regeneratorRuntime from '@babel/runtime/regenerator';
2
- import { createMachine, interpret, sendTo } from 'xstate';
3
- import { assign } from '@xstate/immer';
4
- import axios from 'axios';
5
- import { jsx } from 'react/jsx-runtime';
6
- import { createContext, useContext, cloneElement } from 'react';
7
- import cookie from 'cookie';
8
- import crypto from 'crypto';
9
-
10
- /******************************************************************************
11
- Copyright (c) Microsoft Corporation.
12
-
13
- Permission to use, copy, modify, and/or distribute this software for any
14
- purpose with or without fee is hereby granted.
15
-
16
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
17
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
18
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
19
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
20
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
21
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
22
- PERFORMANCE OF THIS SOFTWARE.
23
- ***************************************************************************** */
24
-
25
- function __awaiter(thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- }
34
-
35
- function request(url, options) {
36
- return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
37
- var response;
38
- return _regeneratorRuntime.wrap(function _callee$(_context) {
39
- while (1) {
40
- switch (_context.prev = _context.next) {
41
- case 0:
42
- _context.next = 2;
43
- return fetch(url, options);
44
-
45
- case 2:
46
- response = _context.sent;
47
-
48
- if (!(response.status === 200)) {
49
- _context.next = 5;
50
- break;
51
- }
52
-
53
- return _context.abrupt("return", response.json());
54
-
55
- case 5:
56
- return _context.abrupt("return", Promise.resolve({
57
- message: response.statusText,
58
- success: false
59
- }));
60
-
61
- case 6:
62
- case "end":
63
- return _context.stop();
64
- }
65
- }
66
- }, _callee);
67
- }));
68
- }
69
-
70
- var authMachine =
71
- /** @xstate-layout N4IgpgJg5mDOIC5QEMCuAXAFgOjVsAdugJYDGyJBUAxBAPYFjbEEBudA1k3jj4SeUpQELdoOIMA2gAYAujNmJQABzqxiJBkpAAPRAEZ9Adn3YAbABYATAGYr1gKwWLDoxYA0IAJ6JbATmwADkCXPyszK0CzPyijAF84zx5cDEx+MgoWGjAAJxy6HOxlABsKADMCgFsUrBq0ogyhETY6cSk5BW1VdU0CbT0EfWkncysHYelba0DXTx8EBzNTCxDXPzMbaTCjQISk1OxUAj4G8SpaBiZRTm4Do5OBTKpmsUz2+TkutQ0JPqRdRAAWkMAUiNkCxjMO02+gsNjmvkCVmw+hsRnRjiM0hMexAyXuqXSZ2yeQKRVK6AqOWq+OOhNOT2E1zaBAUnX+3R+Wn+A2R0RsmwhRjMUKsRgcSIRCCR2Fs6MCYSmDn0wVxyRyYDKGtgmCyF0YzBaXDq2A1WrguuezLerI6nw5316-UQRhi2BiQ2kk2VkylUSCfnB9iWwSxYrVBzN2stJPyhRK5SqJqjFqyL1aNrZ9pUjt+zoQFn0Zmw0gs6Ks0n0gZMMSlwOx2ELTj80jMTisYvCEdqxToUBgEAA8hhqAAZQcAcQAkgA5dk5np5nm+KElsyBcWWQzhMZSizSQLYVzbhyB8F+Pz6bs4Xv9yBTghjyeDgCqABV5yBOU7l9KjDYghmQJhgVPwHArKw6yrYswKWf8HE2cYJWvbBbwHB9qB0WB0AobgynQXIAAozC9L0AEpqGSND71tRQHUXblQAGKJkVdZwqwlMIokCKCjGwYUYThf8SLRCwEkSEACDoCA4G0HgvgYv4mKBIs+LBIUoUCQT4W8IFIgsRtFmMMskMvKwUIeRosgUrklIBQZKwA1soWccJXU2PwpVEktjBmdcIhiZwUIJfAGSEGyf2UhBAQM0N1gPJYoVbHYoJCHyTCiLYYnXcMJPVTVo2s+jbPzawAkMSZwmxBUJX0KUxUPOV3LYy8tjEvKDmoocMAipcopsAJTzRNY0VhWEpVcaQSy0sVxjGFs0RQrqH16xj7MMOFGxWRYBXBRYeN0hA3XsINnBCfcLyvcSgA */
72
- createMachine({
73
- context: {
74
- // id: '',
75
- user: null,
76
- accessToken: '',
77
- refreshToken: '',
78
-
79
- /**
80
- * If unauthenticating fails, we need a way to ignore the refresh token on subsequent access token refresh.
81
- * This would be set to true done/error of unauthenticate service, and false on done of authenticate service
82
- */
83
- ignoreRefreshToken: false,
84
- endpoints: {
85
- login: '',
86
- logout: '',
87
- refresh: '',
88
- ssrRefresh: ''
89
- }
90
- },
91
- predictableActionArguments: true,
92
- id: 'auth',
93
- initial: 'refreshing',
94
- states: {
95
- authenticating: {
96
- invoke: {
97
- src: 'authenticate',
98
- onDone: [{
99
- actions: 'setUserContext',
100
- target: 'loggedIn'
101
- }],
102
- onError: [{
103
- target: 'loggedOut'
104
- }]
105
- }
106
- },
107
- unauthenticating: {
108
- invoke: {
109
- src: 'unauthenticate',
110
- onDone: [{
111
- actions: 'unsetUserContext',
112
- target: 'loggedOut'
113
- }],
114
- onError: [{
115
- actions: ['unsetUserContext', 'setIgnoreRefreshToken'],
116
- target: 'loggedOut'
117
- }]
118
- }
119
- },
120
- refreshing: {
121
- invoke: {
122
- src: 'refreshAccessToken',
123
- onDone: [{
124
- actions: ['unsetRefreshToken', 'setAccessToken'],
125
- target: 'loggedIn'
126
- }],
127
- onError: [{
128
- actions: 'unsetRefreshToken',
129
- target: 'unauthenticating'
130
- }]
131
- }
132
- },
133
- loggedOut: {
134
- on: {
135
- LOGIN: {
136
- target: 'authenticating'
137
- }
138
- }
139
- },
140
- loggedIn: {
141
- after: {
142
- '60000': {
143
- cond: function cond() {
144
- return typeof window !== 'undefined';
145
- },
146
- target: 'refreshing'
147
- }
148
- },
149
- // entry: ['unsetUserContext'],
150
- on: {
151
- LOGOUT: {
152
- target: 'unauthenticating'
153
- }
154
- }
155
- }
156
- }
157
- }, {
158
- actions: {
159
- // setAccessToken: assign<UserContext, RefreshTokenEvent>((context, event) => {
160
- // context.accessToken = event.accessToken;
161
- // }),
162
- setUserContext: assign(function (context, event) {
163
- // event.type - done.invoke.auth.authenticating:invocation[0]
164
- if (event.data.type !== 'AUTHENTICATE_SUCCESS') return; // context.user = event.data.user;
165
-
166
- context.accessToken = event.data.accessToken;
167
- context.ignoreRefreshToken = false;
168
- }),
169
- unsetUserContext: assign(function (context) {
170
- var endpoints = context.endpoints;
171
- Object.assign(context, authMachine.initialState.context);
172
- context.endpoints = endpoints; // maintain endpoints passed through DI when machine created
173
- // context = authMachine.initialState.context;
174
- }),
175
- setAccessToken: assign(function (context, event) {
176
- if (event.data.type !== 'REFRESH_TOKEN_SUCCESS') return; // is this really necessary?
177
-
178
- context.accessToken = event.data.accessToken;
179
- context.ignoreRefreshToken = false;
180
- }),
181
- unsetRefreshToken: assign(function (context, event) {
182
- if (event.data.type !== 'REFRESH_TOKEN_SUCCESS') return; // is this really necessary?
183
-
184
- context.refreshToken = '';
185
- }),
186
- setIgnoreRefreshToken: assign(function (context) {
187
- context.ignoreRefreshToken = true;
188
- })
189
- },
190
- services: {
191
- refreshAccessToken: function refreshAccessToken(context) {
192
- return function () {
193
- return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
194
- var response, res, data, _data;
195
-
196
- return _regeneratorRuntime.wrap(function _callee2$(_context2) {
197
- while (1) {
198
- switch (_context2.prev = _context2.next) {
199
- case 0:
200
- if (!(typeof window === 'undefined')) {
201
- _context2.next = 18;
202
- break;
203
- }
204
-
205
- if (!(context.refreshToken === '')) {
206
- _context2.next = 3;
207
- break;
208
- }
209
-
210
- throw new Error('Unauthorized.');
211
-
212
- case 3:
213
- _context2.prev = 3;
214
- _context2.next = 6;
215
- return axios.post(context.endpoints.ssrRefresh, {
216
- grant_type: 'refresh_token'
217
- }, {
218
- headers: {
219
- Cookie: "refresh_token=".concat(context.refreshToken),
220
- 'Content-Type': 'application/json'
221
- },
222
- withCredentials: true
223
- });
224
-
225
- case 6:
226
- res = _context2.sent;
227
- data = res.data;
228
-
229
- if (!(typeof data.accessToken === 'undefined')) {
230
- _context2.next = 10;
231
- break;
232
- }
233
-
234
- throw new Error('Unauthorized.');
235
-
236
- case 10:
237
- return _context2.abrupt("return", {
238
- type: 'REFRESH_TOKEN_SUCCESS',
239
- accessToken: data.accessToken
240
- });
241
-
242
- case 13:
243
- _context2.prev = 13;
244
- _context2.t0 = _context2["catch"](3);
245
- throw new Error('Could not complete refresh request (server)');
246
-
247
- case 16:
248
- _context2.next = 25;
249
- break;
250
-
251
- case 18:
252
- _context2.next = 20;
253
- return request(context.endpoints.refresh, {
254
- method: 'POST',
255
- mode: 'cors',
256
- credentials: 'include',
257
- headers: {
258
- 'Content-Type': 'application/json'
259
- },
260
- body: JSON.stringify({
261
- grant_type: 'refresh_token' // client_id: 'default',
262
- // client_secret: 'Password123!',
263
- // scope: 'default',
264
-
265
- }).toString()
266
- });
267
-
268
- case 20:
269
- response = _context2.sent;
270
- _data = response;
271
-
272
- if (!(typeof _data.accessToken === 'undefined')) {
273
- _context2.next = 24;
274
- break;
275
- }
276
-
277
- throw new Error('Unauthorized.');
278
-
279
- case 24:
280
- return _context2.abrupt("return", {
281
- type: 'REFRESH_TOKEN_SUCCESS',
282
- accessToken: _data.accessToken
283
- });
284
-
285
- case 25:
286
- case "end":
287
- return _context2.stop();
288
- }
289
- }
290
- }, _callee2, null, [[3, 13]]);
291
- }));
292
- };
293
- },
294
- authenticate: function authenticate(context, event) {
295
- return function () {
296
- return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
297
- var _a, _b, e, response, data;
298
-
299
- return _regeneratorRuntime.wrap(function _callee3$(_context3) {
300
- while (1) {
301
- switch (_context3.prev = _context3.next) {
302
- case 0:
303
- e = event; // workaround to typescript not allowing casting in parameter
304
-
305
- if (!(e.type !== 'LOGIN')) {
306
- _context3.next = 3;
307
- break;
308
- }
309
-
310
- throw new Error("Authenticate can only be called for \"LOGIN\" event type. Event caller: ".concat(String(e.type)));
311
-
312
- case 3:
313
- _context3.next = 5;
314
- return request(context.endpoints.login, {
315
- method: 'POST',
316
- mode: 'cors',
317
- credentials: 'include',
318
- headers: {
319
- 'Content-Type': 'application/json'
320
- },
321
- body: JSON.stringify({
322
- username: e.username,
323
- password: e.password // grant_type: 'password',
324
- // client_id: 'default',
325
- // client_secret: 'Password123!',
326
- // scope: 'default',
327
-
328
- }).toString()
329
- });
330
-
331
- case 5:
332
- response = _context3.sent;
333
-
334
- /** @todo do we need to handle different status codes here...like what if the service is down? */
335
- data = response;
336
-
337
- if (!(typeof data.accessToken === 'undefined')) {
338
- _context3.next = 9;
339
- break;
340
- }
341
-
342
- 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.');
343
-
344
- case 9:
345
- return _context3.abrupt("return", {
346
- type: 'AUTHENTICATE_SUCCESS',
347
- // user: data.user,
348
- accessToken: data.accessToken
349
- });
350
-
351
- case 10:
352
- case "end":
353
- return _context3.stop();
354
- }
355
- }
356
- }, _callee3);
357
- }));
358
- };
359
- },
360
- unauthenticate: function unauthenticate(context) {
361
- return function () {
362
- return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
363
- return _regeneratorRuntime.wrap(function _callee4$(_context4) {
364
- while (1) {
365
- switch (_context4.prev = _context4.next) {
366
- case 0:
367
- _context4.next = 2;
368
- return fetch(context.endpoints.logout, {
369
- method: 'POST',
370
- mode: 'cors',
371
- credentials: 'include' // headers: {
372
- // 'Access-Control-Allow-Origin': 'https://middleware-clicktap.local-rmgmedia.com',
373
- // 'Access-Control-Allow-Credentials': 'true',
374
- // },
375
-
376
- });
377
-
378
- case 2:
379
- return _context4.abrupt("return", {
380
- type: 'UNAUTHENTICATE'
381
- });
382
-
383
- case 3:
384
- case "end":
385
- return _context4.stop();
386
- }
387
- }
388
- }, _callee4);
389
- }));
390
- };
391
- }
392
- } // doesn't make sense in the case where you have an access token that is about to expire
393
- // and the loggedIn state won't fire another refresh for 15 min
394
- //
395
- // guards: {
396
- // checkIfLoggedIn: (context, _event) => {
397
- // if (context.user) return true;
398
- // },
399
- // },
400
-
401
- });
402
-
403
- // import type { NextPageContext } from 'next';
404
- // import { useRouter } from 'next/router';
405
-
406
- var AuthContext = /*#__PURE__*/createContext({});
407
- var useAuth = function useAuth() {
408
- // console.log('useAuth');
409
- // console.log(useContext(AuthContext).getSnapshot().context);
410
- return useContext(AuthContext);
411
- };
412
- var useUser = function useUser() {
413
- return useContext(AuthContext).getSnapshot().context.user;
414
- };
415
- /**
416
- * this will run on the server side as part of app.getInitialProps
417
- * @todo is it possible to share state from client to server? headers? cookies?
418
- */
419
-
420
- var getAuth = function getAuth(context, options // eslint-disable-next-line @typescript-eslint/require-await
421
- ) {
422
- return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
423
- var _a, authContext, cookies, authContextWithRefresh;
424
-
425
- return _regeneratorRuntime.wrap(function _callee$(_context) {
426
- while (1) {
427
- switch (_context.prev = _context.next) {
428
- case 0:
429
- authContext = Object.assign(Object.assign({}, authMachine.initialState.context), {
430
- endpoints: Object.assign({}, options.endpoints)
431
- });
432
-
433
- if (!(typeof window !== 'undefined')) {
434
- _context.next = 4;
435
- break;
436
- }
437
-
438
- // eslint-disable-next-line no-console
439
- console.warn('App.getInitialProps::getAuth should not be run on the frontend. You are probably missing getServerSideProps in your page.');
440
- return _context.abrupt("return", interpret(authMachine.withContext(authContext), {
441
- devTools: options.devTools
442
- }).start());
443
-
444
- case 4:
445
- cookies = cookie.parse(((_a = context === null || context === void 0 ? void 0 : context.req) === null || _a === void 0 ? void 0 : _a.headers) && context.req.headers.cookie ? context.req.headers.cookie : '');
446
- authContextWithRefresh = Object.assign(authContext, {
447
- refreshToken: cookies['refresh_token']
448
- });
449
-
450
- if (!(typeof cookies['refresh_token'] !== 'undefined')) {
451
- _context.next = 8;
452
- break;
453
- }
454
-
455
- return _context.abrupt("return", interpret(authMachine.withContext(authContextWithRefresh), {
456
- devTools: options.devTools
457
- }).start());
458
-
459
- case 8:
460
- return _context.abrupt("return", interpret(authMachine.withContext(authContext), {
461
- devTools: options.devTools
462
- }).start());
463
-
464
- case 9:
465
- case "end":
466
- return _context.stop();
467
- }
468
- }
469
- }, _callee);
470
- }));
471
- };
472
- function AuthProvider(_ref) {
473
- var children = _ref.children,
474
- service = _ref.service;
475
- // console.log('AuthProvider::state');
476
- // console.log(state.context);
477
- // let authService = interpret(authMachine, { devTools: options.devTools }).start(state);
478
- // console.log('AuthProvider::authService');
479
- // console.log(authService.getSnapshot().context);
480
- return jsx(AuthContext.Provider, Object.assign({
481
- value: service
482
- }, {
483
- children: children
484
- }));
485
- }
486
-
487
- var timerMachine =
488
- /** @xstate-layout N4IgpgJg5mDOIC5QBcCWBbMAnAdABwEMBXWSAYgCUBRAZQFUBZKgfQBUBJJigbQAYBdRKDwB7WKjQiAdkJAAPRAFoAjADYATDmUBOXQA5tAZmV69AFgDsq1QBoQAT0SHehnAFYAvh7tpMuLERSUqhSUGQcAMIA0nyCSCCi4pIy8QoIJqo4qnoWbnaOCGZmmaq8Zbyqyi5uym6qXj4Y2DgBQSFhAAoAgnQ0LBxcsbKJEqjSsmlVbjimFmZ6agZmbsbq+U4u7g0gvs2twaFkQ-EjyRNObrxZOXkOiGbKFjjq5WbqFurFvNpmXt4gUhEEDgsl2WGGYlG41SSnUVS0um0BmMpks1nW6Tcmk8-zB+GIpAgEKSYxSoDSvAxn142zx+3axKhZPkiEpdwQhjmW1xTVwAGMROg8AAbMDISCMs4whBsgpuOp-DxAA */
489
- createMachine({
490
- id: 'timer',
491
- initial: 'running',
492
- context: {
493
- elapsed: 0,
494
- duration: 3000,
495
- interval: 100,
496
- intervalId: null
497
- },
498
- states: {
499
- paused: {
500
- on: {
501
- // START_TIMER: {
502
- // target: 'running',
503
- // cond: (context) => context.elapsed < context.duration,
504
- // },
505
- RESUME_TIMER: {
506
- target: 'running',
507
- cond: function cond(context) {
508
- return context.elapsed < context.duration;
509
- }
510
- }
511
- }
512
- },
513
- running: {
514
- invoke: {
515
- src: function src(context) {
516
- return function (send) {
517
- // eslint-disable-next-line no-console
518
- // console.log('context.interval: ', context.interval);
519
- var interval = setInterval(function () {
520
- send('TICK');
521
- }, context.interval);
522
- return function () {
523
- clearInterval(interval);
524
- };
525
- };
526
- }
527
- },
528
- always: [{
529
- target: 'completed',
530
- cond: function cond(context) {
531
- return context.elapsed >= context.duration;
532
- }
533
- }],
534
- on: {
535
- TICK: {
536
- actions: assign(function (context, event) {
537
- if (event.type !== 'TICK') return;
538
- context.elapsed += context.interval; // eslint-disable-next-line no-console
539
- // console.log(
540
- // 'elapsed: %d | interval: %d',
541
- // context.elapsed,
542
- // context.interval
543
- // );
544
- })
545
- },
546
- PAUSE_TIMER: {
547
- target: 'paused'
548
- }
549
- }
550
- },
551
- completed: {
552
- type: 'final'
553
- }
554
- }
555
- });
556
-
557
- var toastMachine =
558
- /** @xstate-layout N4IgpgJg5mDOIC5QBcD2BDWyB0BLCANmAMQCCAIuQPoCSAKgKICyA2gAwC6ioADqrLmS5UAO24gAHogCMAZgCs2AGzS2SgBxKA7AE4lO2ToAsAGhABPRAFoj6gL52zaTDnQBjIQDcSEUWDwinqgA1v5CALZgAE7sXEggfAJCouJSCEpsOspaOQay0kqyAExKZpYIReps2LY6mmxG+kUKWkYOThhY2O5eJBTU9Myx4omCwmLxabKF2NKN8kpFbPls8gpl1vLqykXyasaNhdJFWu0gzl09uN7EAErMAPIAagy0jKycI-xjKZOIi9sDPI9EZgYV1LItBsEIYlNg9NIdGxKki1jkzhdXB5riQAMoMOi0cgAGQYw3io2SE1AaTkWS0RQOSKWEK0c2hzWkNUWJy0Skah1sGM6WN6dwYuIAqkxXnQaDLbuTeN8qakZPIuXylhktAppgUitDilpsJpQeo9KsVOoCsKXN1sTcAAqkSX4qhyhVKhIq8ZqirSbaZeTyLRbVnqVqyaHSaQm45mtirKo6Eo6O2XCAQXAiKDEfGEmgksmfCm+340xC2bCh3XGrTLfR8+TQqxFJbYTIoow6HStBshjOuLM5vMFqikADCcpe3spfr+MKMmsZbDmFvU6jBRtW8I3IcMBT7Q+wUTA4VQnlH+YJRNJc-L1MkiHURiKps0DIWKhyIZjehqfc1h0I8GyUE8zwvK9cxvQkpxnEs4mVJIF0rBBU1kWZVw1WtgSMUwLHVIxsEqIxjVDIF5CFM4RFQCA4HETEvhQitnwQKxYxNOoDFjbQ2RtfRW1kfJO1THjA1sVRZBPfAiGYn4nzSKx9D3cS+MDI9-zhWot2A0C1BPK5vHk1VF1kIwuOZPICmKYEtMAuoDxAptlkMkdcxM1C2MMYjKhKXUlH5DUimkVsijImsxMMcLpjDUMIPPS9R081i0i3OE10afI42XcKW0ImFgRrYE5FBWx1F2cyHAcIA */
559
- createMachine({
560
- context: {
561
- items: [],
562
- order: 'desc',
563
- duration: 0,
564
- activeItem: null
565
- },
566
- predictableActionArguments: true,
567
- id: 'toast',
568
- initial: 'idle',
569
- states: {
570
- idle: {
571
- on: {
572
- ADD_ITEM: {
573
- target: 'adding'
574
- }
575
- }
576
- },
577
- active: {
578
- invoke: {
579
- id: 'timer',
580
- src: timerMachine,
581
- onDone: {
582
- target: 'removing',
583
- cond: 'itemHasTimeout'
584
- },
585
- data: Object.assign(timerMachine.context, {
586
- duration: function duration(context) {
587
- var _a; // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return
588
-
589
-
590
- return (_a = context.items[context.items.length - 1].duration) !== null && _a !== void 0 ? _a : context.duration;
591
- }
592
- })
593
- },
594
- on: {
595
- ADD_ITEM: {
596
- // actions: sendTo('timer', 'PAUSE_TIMER'),
597
- target: 'adding'
598
- },
599
- REMOVE_ITEM: {
600
- target: 'removing'
601
- },
602
- SET_IDLE: {
603
- target: 'idle'
604
- },
605
- RESUME_TIMER: {
606
- actions: sendTo('timer', 'RESUME_TIMER') // cond: (context) => context.duration > 0,
607
-
608
- },
609
- PAUSE_TIMER: {
610
- actions: sendTo('timer', 'PAUSE_TIMER') // cond: (context) => context.duration > 0,
611
-
612
- }
613
- } // after: {
614
- // ITEM_TIMEOUT: {
615
- // target: 'removing',
616
- // cond: 'itemHasTimeout',
617
- // },
618
- // },
619
-
620
- },
621
- adding: {
622
- entry: ['addItem'],
623
- on: {
624
- SET_IDLE: {
625
- target: 'idle'
626
- },
627
- SET_ACTIVE: {
628
- target: 'active'
629
- }
630
- }
631
- },
632
- removing: {
633
- entry: 'removeItem',
634
- on: {
635
- SET_IDLE: {
636
- target: 'idle'
637
- },
638
- SET_ACTIVE: {
639
- target: 'active'
640
- }
641
- }
642
- }
643
- }
644
- }, {
645
- actions: {
646
- addItem: assign(function (context, event) {
647
- var _a, _b;
648
-
649
- if (event.type !== 'ADD_ITEM') return;
650
- var id = "notification-".concat(crypto.randomBytes(16).toString('hex'));
651
- var duration = (_a = event.duration) !== null && _a !== void 0 ? _a : context.duration; // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
652
-
653
- var notification = /*#__PURE__*/cloneElement(event.item, Object.assign({
654
- duration: duration,
655
- id: id,
656
- key: (_b = event.item.key) !== null && _b !== void 0 ? _b : id
657
- }, event.item.props));
658
- var item = {
659
- duration: duration,
660
- id: id,
661
- element: notification
662
- };
663
-
664
- if (context.order === 'desc') {
665
- context.items.push(item);
666
- } else {
667
- context.items.unshift(item);
668
- }
669
-
670
- context.activeItem = id;
671
- }),
672
- removeItem: assign(function (context, event) {
673
- if (event.type !== 'REMOVE_ITEM' && event.type !== 'xstate.after(ITEM_TIMEOUT)#toast.active' && event.type !== 'done.invoke.timer') return;
674
-
675
- if (context.order === 'desc') {
676
- context.items.pop();
677
- context.activeItem = context.items.length > 0 ? context.items[context.items.length - 1].id : null;
678
- } else {
679
- context.items.shift();
680
- context.activeItem = context.items.length > 0 ? context.items[0].id : null;
681
- }
682
- }) // startTimer: sendTo('timer', { type: 'START' }),
683
-
684
- },
685
- delays: {
686
- ITEM_TIMEOUT: function ITEM_TIMEOUT(context) {
687
- var _a; // eslint-disable-next-line @typescript-eslint/no-unsafe-return
688
-
689
-
690
- return (// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
691
- (_a = context.items[context.items.length - 1].duration) !== null && _a !== void 0 ? _a : context.duration
692
- );
693
- }
694
- },
695
- guards: {
696
- itemHasTimeout: function itemHasTimeout(context) {
697
- return (// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
698
- context.items[context.items.length - 1].duration > 0 || context.duration > 0
699
- );
700
- }
701
- }
702
- });
703
-
704
- var ToastContext = /*#__PURE__*/createContext({});
705
- var useToast = function useToast() {
706
- return useContext(ToastContext);
707
- };
708
- function ToastProvider(_ref) {
709
- var children = _ref.children,
710
- service = _ref.service;
711
- // const toastService = interpret(toastMachine, {
712
- // devTools: options.devTools,
713
- // }).start(state);
714
- // toastService.subscribe((s) => {
715
- // setState(s);
716
- // });
717
- return jsx(ToastContext.Provider, Object.assign({
718
- value: service
719
- }, {
720
- children: children
721
- }));
722
- }
723
-
724
- export { AuthContext, AuthProvider, ToastContext, ToastProvider, authMachine, getAuth, timerMachine, toastMachine, useAuth, useToast, useUser };