@clicktap/state 0.1.0 → 0.1.2

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/README.md CHANGED
@@ -1,11 +1,9 @@
1
- # state
1
+ # @clicktap/state
2
2
 
3
- This library was generated with [Nx](https://nx.dev).
3
+ State management library for Clicktap reference frontend.
4
4
 
5
- ## Building
5
+ ## Install
6
6
 
7
- Run `nx build state` to build the library.
7
+ The state management library requires at least NextJS 13 and React 18. Additionally, it has a few peer dependencies on xstate that must be installed.
8
8
 
9
- ## Running unit tests
10
-
11
- Run `nx test state` to execute the unit tests via [Jest](https://jestjs.io).
9
+ Run `pnpm install @clicktap/state xstate @xstate/immer @xstate/inspect @xstate/react` to install the library.
package/package.json CHANGED
@@ -1,6 +1,16 @@
1
1
  {
2
2
  "name": "@clicktap/state",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
+ "private": false,
5
+ "author": "Clicktap",
6
+ "description": "A state management library for Clicktap reference frontend.",
7
+ "keywords": [
8
+ "clicktap"
9
+ ],
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
4
14
  "type": "commonjs",
5
15
  "dependencies": {
6
16
  "cookie": "^0.5.0"
@@ -10,11 +20,14 @@
10
20
  "@types/react": "18.0.28"
11
21
  },
12
22
  "peerDependencies": {
23
+ "@xstate/immer": "^0.3.3",
24
+ "@xstate/inspect": "^0.8.0",
25
+ "@xstate/react": "^3.2.2",
13
26
  "next": "^13.4.6",
14
27
  "react": "^18.2.0",
15
28
  "xstate": "^4.38.1",
16
- "@xstate/immer": "^0.3.3",
17
- "@xstate/inspect": "^0.8.0",
18
- "@xstate/react": "^3.2.2"
19
- }
29
+ "tslib": "2.4.0"
30
+ },
31
+ "main": "./src/index.js",
32
+ "types": "./src/index.d.ts"
20
33
  }
@@ -0,0 +1,49 @@
1
+ import type { InterpreterFrom } from 'xstate';
2
+ import type { ReactNode } from 'react';
3
+ import type { NextPageContext } from 'next';
4
+ import { authMachine } from './auth';
5
+ export declare const AuthContext: import("react").Context<import("xstate").Interpreter<import("./auth").AuthMachineContext, any, import("./auth").AuthMachineEvents, {
6
+ value: any;
7
+ context: import("./auth").AuthMachineContext;
8
+ }, import("xstate").ResolveTypegenMeta<import("xstate").TypegenDisabled, import("./auth").AuthMachineEvents, import("xstate").BaseActionObject, import("xstate").ServiceMap>>>;
9
+ export declare const useAuth: () => import("xstate").Interpreter<import("./auth").AuthMachineContext, any, import("./auth").AuthMachineEvents, {
10
+ value: any;
11
+ context: import("./auth").AuthMachineContext;
12
+ }, import("xstate").ResolveTypegenMeta<import("xstate").TypegenDisabled, import("./auth").AuthMachineEvents, import("xstate").BaseActionObject, import("xstate").ServiceMap>>;
13
+ export declare const useUser: () => {
14
+ email: string;
15
+ username: string;
16
+ firstName: string;
17
+ lastName: string;
18
+ birthdate?: Date | undefined;
19
+ gender?: string | undefined;
20
+ createdAt: Date;
21
+ updatedAt: Date;
22
+ role?: string | undefined;
23
+ locked: boolean;
24
+ affiliateId: string;
25
+ stripeId: string;
26
+ } | null;
27
+ type AuthOptions = {
28
+ devTools: boolean;
29
+ endpoints: {
30
+ login: string;
31
+ logout: string;
32
+ refresh: string;
33
+ ssrRefresh: string;
34
+ };
35
+ };
36
+ /**
37
+ * this will run on the server side as part of app.getInitialProps
38
+ * @todo is it possible to share state from client to server? headers? cookies?
39
+ */
40
+ export declare const getAuth: (context: NextPageContext, options: AuthOptions) => Promise<import("xstate").Interpreter<import("./auth").AuthMachineContext, any, import("./auth").AuthMachineEvents, {
41
+ value: any;
42
+ context: import("./auth").AuthMachineContext;
43
+ }, import("xstate").ResolveTypegenMeta<import("xstate").TypegenDisabled, import("./auth").AuthMachineEvents, import("xstate").BaseActionObject, import("xstate").ServiceMap>>>;
44
+ type Props = {
45
+ children: ReactNode;
46
+ service: InterpreterFrom<typeof authMachine>;
47
+ };
48
+ export declare function AuthProvider({ children, service, }: Props): JSX.Element;
49
+ export {};
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthProvider = exports.getAuth = exports.useUser = exports.useAuth = exports.AuthContext = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const react_1 = require("react");
6
+ const xstate_1 = require("xstate");
7
+ const cookie_1 = tslib_1.__importDefault(require("cookie"));
8
+ const auth_1 = require("./auth");
9
+ // removing dependencies on next, this should work regardless of platform
10
+ // import type { NextPageContext } from 'next';
11
+ // import { useRouter } from 'next/router';
12
+ exports.AuthContext = (0, react_1.createContext)({});
13
+ const useAuth = () => {
14
+ // console.log('useAuth');
15
+ // console.log(useContext(AuthContext).getSnapshot().context);
16
+ return (0, react_1.useContext)(exports.AuthContext);
17
+ };
18
+ exports.useAuth = useAuth;
19
+ const useUser = () => {
20
+ return (0, react_1.useContext)(exports.AuthContext).getSnapshot().context.user;
21
+ };
22
+ exports.useUser = useUser;
23
+ /**
24
+ * this will run on the server side as part of app.getInitialProps
25
+ * @todo is it possible to share state from client to server? headers? cookies?
26
+ */
27
+ const getAuth = (context, options
28
+ // eslint-disable-next-line @typescript-eslint/require-await
29
+ ) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
30
+ var _a;
31
+ if (typeof window !== 'undefined') {
32
+ // eslint-disable-next-line no-console
33
+ console.warn('App.getInitialProps::getAuth should not be run on the frontend. You are probably missing getServerSideProps in your page.');
34
+ return (0, xstate_1.interpret)(auth_1.authMachine, { devTools: options.devTools }).start();
35
+ }
36
+ const cookies = cookie_1.default.parse(((_a = context === null || context === void 0 ? void 0 : context.req) === null || _a === void 0 ? void 0 : _a.headers) && context.req.headers.cookie
37
+ ? context.req.headers.cookie
38
+ : '');
39
+ if (typeof cookies['refresh_token'] !== 'undefined') {
40
+ const authContext = Object.assign(Object.assign({}, auth_1.authMachine.initialState.context), { refreshToken: cookies['refresh_token'], endpoints: Object.assign({}, options.endpoints) });
41
+ return (0, xstate_1.interpret)(auth_1.authMachine.withContext(authContext), {
42
+ devTools: options.devTools,
43
+ }).start();
44
+ }
45
+ return (0, xstate_1.interpret)(auth_1.authMachine, { devTools: options.devTools }).start();
46
+ });
47
+ exports.getAuth = getAuth;
48
+ function AuthProvider({ children, service, }) {
49
+ // console.log('AuthProvider::state');
50
+ // console.log(state.context);
51
+ // let authService = interpret(authMachine, { devTools: options.devTools }).start(state);
52
+ // console.log('AuthProvider::authService');
53
+ // console.log(authService.getSnapshot().context);
54
+ return (<exports.AuthContext.Provider value={service}>{children}</exports.AuthContext.Provider>);
55
+ }
56
+ exports.AuthProvider = AuthProvider;
57
+ //# sourceMappingURL=AuthProvider.jsx.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AuthProvider.jsx","sourceRoot":"","sources":["../../../../../libs/state/src/auth/AuthProvider.tsx"],"names":[],"mappings":";;;;AAAA,iCAAkD;AAClD,mCAAmC;AAEnC,4DAA4B;AAG5B,iCAAqC;AAErC,yEAAyE;AACzE,+CAA+C;AAC/C,2CAA2C;AAE9B,QAAA,WAAW,GAAG,IAAA,qBAAa,EACtC,EAAyC,CAC1C,CAAC;AAEK,MAAM,OAAO,GAAG,GAAG,EAAE;IAC1B,0BAA0B;IAC1B,8DAA8D;IAC9D,OAAO,IAAA,kBAAU,EAAC,mBAAW,CAAC,CAAC;AACjC,CAAC,CAAC;AAJW,QAAA,OAAO,WAIlB;AAEK,MAAM,OAAO,GAAG,GAAG,EAAE;IAC1B,OAAO,IAAA,kBAAU,EAAC,mBAAW,CAAC,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC;AAC5D,CAAC,CAAC;AAFW,QAAA,OAAO,WAElB;AAYF;;;GAGG;AACI,MAAM,OAAO,GAAG,CACrB,OAAwB,EACxB,OAAoB;AACpB,4DAA4D;EAC5D,EAAE;;IACF,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QACjC,sCAAsC;QACtC,OAAO,CAAC,IAAI,CACV,2HAA2H,CAC5H,CAAC;QACF,OAAO,IAAA,kBAAS,EA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vokeEvent } from 'xstate';
2
+ export interface AuthMachineContext {
3
+ user: {
4
+ email: string;
5
+ username: string;
6
+ firstName: string;
7
+ lastName: string;
8
+ birthdate?: Date;
9
+ gender?: string /** @todo use enum? */;
10
+ createdAt: Date;
11
+ updatedAt: Date;
12
+ role?: string /** @todo use enum? */;
13
+ locked: boolean;
14
+ affiliateId: string;
15
+ stripeId: string;
16
+ } | null;
17
+ accessToken: string;
18
+ refreshToken: string;
19
+ ignoreRefreshToken: boolean;
20
+ endpoints: {
21
+ login: string;
22
+ logout: string;
23
+ refresh: string;
24
+ ssrRefresh: string;
25
+ };
26
+ }
27
+ export interface RefreshTokenEvent {
28
+ type: 'REFRESH_TOKEN';
29
+ accessToken: AuthMachineContext['accessToken'];
30
+ }
31
+ export interface LoginEvent {
32
+ type: 'LOGIN';
33
+ username: string;
34
+ password: string;
35
+ }
36
+ export interface LogoutEvent {
37
+ type: 'LOGOUT';
38
+ }
39
+ export interface AuthenticateSuccessEvent {
40
+ type: 'AUTHENTICATE_SUCCESS';
41
+ user: AuthMachineContext['user'];
42
+ accessToken: AuthMachineContext['accessToken'];
43
+ }
44
+ export interface RefreshTokenSuccessEvent {
45
+ type: 'REFRESH_TOKEN_SUCCESS';
46
+ accessToken: AuthMachineContext['accessToken'];
47
+ }
48
+ export type AuthMachineEvents = RefreshTokenEvent | LoginEvent | LogoutEvent | DoneInvokeEvent<AuthenticateSuccessEvent> | DoneInvokeEvent<RefreshTokenSuccessEvent>;
49
+ export declare const authMachine: import("xstate").StateMachine<AuthMachineContext, any, AuthMachineEvents, {
50
+ value: any;
51
+ context: AuthMachineContext;
52
+ }, import("xstate").BaseActionObject, import("xstate").ServiceMap, import("xstate").ResolveTypegenMeta<import("xstate").TypegenDisabled, AuthMachineEvents, import("xstate").BaseActionObject, import("xstate").ServiceMap>>;
@@ -0,0 +1,291 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.authMachine = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const xstate_1 = require("xstate");
6
+ const immer_1 = require("@xstate/immer");
7
+ function request(url, options) {
8
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
9
+ const response = yield fetch(url, options);
10
+ if (response.status === 200) {
11
+ return response.json();
12
+ }
13
+ return Promise.resolve({
14
+ message: response.statusText,
15
+ success: false,
16
+ });
17
+ });
18
+ }
19
+ exports.authMachine =
20
+ /** @xstate-layout N4IgpgJg5mDOIC5QEMCuAXAFgOjVsAdugJYDGyJBUAxBAPYFjbEEBudA1k3jj4SeUpQELdoOIMA2gAYAujNmJQABzqxiJBkpAAPRAEZ9Adn3YAbABYATAGYr1gKwWLDoxYA0IAJ6JbATmwADkCXPyszK0CzPyijAF84zx5cDEx+MgoWGjAAJxy6HOxlABsKADMCgFsUrBq0ogyhETY6cSk5BW1VdU0CbT0EfWkncysHYelba0DXTx8EBzNTCxDXPzMbaTCjQISk1OxUAj4G8SpaBiZRTm4Do5OBTKpmsUz2+TkutQ0JPqRdRAAWkMAUiNkCxjMO02+gsNjmvkCVmw+hsRnRjiM0hMexAyXuqXSZ2yeQKRVK6AqOWq+OOhNOT2E1zaBAUnX+3R+Wn+A2R0RsmwhRjMUKsRgcSIRCCR2Fs6MCYSmDn0wVxyRyYDKGtgmCyF0YzBaXDq2A1WrguuezLerI6nw5316-UQRhi2BiQ2kk2VkylUSCfnB9iWwSxYrVBzN2stJPyhRK5SqJqjFqyL1aNrZ9pUjt+zoQFn0Zmw0gs6Ks0n0gZMMSlwOx2ELTj80jMTisYvCEdqxToUBgEAA8hhqAAZQcAcQAkgA5dk5np5nm+KElsyBcWWQzhMZSizSQLYVzbhyB8F+Pz6bs4Xv9yBTghjyeDgCqABV5yBOU7l9KjDYghmQJhgVPwHArKw6yrYswKWf8HE2cYJWvbBbwHB9qB0WB0AobgynQXIAAozC9L0AEpqGSND71tRQHUXblQAGKJkVdZwqwlMIokCKCjGwYUYThf8SLRCwEkSEACDoCA4G0HgvgYv4mKBIs+LBIUoUCQT4W8IFIgsRtFmMMskMvKwUIeRosgUrklIBQZKwA1soWccJXU2PwpVEktjBmdcIhiZwUIJfAGSEGyf2UhBAQM0N1gPJYoVbHYoJCHyTCiLYYnXcMJPVTVo2s+jbPzawAkMSZwmxBUJX0KUxUPOV3LYy8tjEvKDmoocMAipcopsAJTzRNY0VhWEpVcaQSy0sVxjGFs0RQrqH16xj7MMOFGxWRYBXBRYeN0hA3XsINnBCfcLyvcSgA */
21
+ (0, xstate_1.createMachine)({
22
+ context: {
23
+ // id: '',
24
+ user: null,
25
+ accessToken: '',
26
+ refreshToken: '',
27
+ /**
28
+ * If unauthenticating fails, we need a way to ignore the refresh token on subsequent access token refresh.
29
+ * This would be set to true done/error of unauthenticate service, and false on done of authenticate service
30
+ */
31
+ ignoreRefreshToken: false,
32
+ endpoints: {
33
+ login: '',
34
+ logout: '',
35
+ refresh: '',
36
+ ssrRefresh: '',
37
+ },
38
+ },
39
+ predictableActionArguments: true,
40
+ id: 'auth',
41
+ initial: 'refreshing',
42
+ states: {
43
+ authenticating: {
44
+ invoke: {
45
+ src: 'authenticate',
46
+ onDone: [
47
+ {
48
+ actions: 'setUserContext',
49
+ target: 'loggedIn',
50
+ },
51
+ ],
52
+ onError: [
53
+ {
54
+ target: 'loggedOut',
55
+ },
56
+ ],
57
+ },
58
+ },
59
+ unauthenticating: {
60
+ invoke: {
61
+ src: 'unauthenticate',
62
+ onDone: [
63
+ {
64
+ actions: 'unsetUserContext',
65
+ target: 'loggedOut',
66
+ },
67
+ ],
68
+ onError: [
69
+ {
70
+ actions: ['unsetUserContext', 'setIgnoreRefreshToken'],
71
+ target: 'loggedOut',
72
+ },
73
+ ],
74
+ },
75
+ },
76
+ refreshing: {
77
+ invoke: {
78
+ src: 'refreshAccessToken',
79
+ onDone: [
80
+ {
81
+ actions: ['unsetRefreshToken', 'setAccessToken'],
82
+ target: 'loggedIn',
83
+ },
84
+ ],
85
+ onError: [
86
+ {
87
+ actions: 'unsetRefreshToken',
88
+ target: 'unauthenticating',
89
+ },
90
+ ],
91
+ },
92
+ },
93
+ loggedOut: {
94
+ on: {
95
+ LOGIN: {
96
+ target: 'authenticating',
97
+ },
98
+ },
99
+ },
100
+ loggedIn: {
101
+ after: {
102
+ '60000': {
103
+ cond: () => typeof window !== 'undefined',
104
+ target: 'refreshing',
105
+ },
106
+ },
107
+ // entry: ['unsetUserContext'],
108
+ on: {
109
+ LOGOUT: {
110
+ target: 'unauthenticating',
111
+ },
112
+ },
113
+ },
114
+ },
115
+ }, {
116
+ actions: {
117
+ // setAccessToken: assign<UserContext, RefreshTokenEvent>((context, event) => {
118
+ // context.accessToken = event.accessToken;
119
+ // }),
120
+ setUserContext: (0, immer_1.assign)((context, event) => {
121
+ // event.type - done.invoke.auth.authenticating:invocation[0]
122
+ if (event.data.type !== 'AUTHENTICATE_SUCCESS')
123
+ return;
124
+ // context.user = event.data.user;
125
+ context.accessToken = event.data.accessToken;
126
+ context.ignoreRefreshToken = false;
127
+ }),
128
+ unsetUserContext: (0, immer_1.assign)((context) => {
129
+ Object.assign(context, exports.authMachine.initialState.context);
130
+ // context = authMachine.initialState.context;
131
+ }),
132
+ setAccessToken: (0, immer_1.assign)((context, event) => {
133
+ if (event.data.type !== 'REFRESH_TOKEN_SUCCESS')
134
+ return; // is this really necessary?
135
+ context.accessToken = event.data.accessToken;
136
+ context.ignoreRefreshToken = false;
137
+ }),
138
+ unsetRefreshToken: (0, immer_1.assign)((context, event) => {
139
+ if (event.data.type !== 'REFRESH_TOKEN_SUCCESS')
140
+ return; // is this really necessary?
141
+ context.refreshToken = '';
142
+ }),
143
+ setIgnoreRefreshToken: (0, immer_1.assign)((context) => {
144
+ context.ignoreRefreshToken = true;
145
+ }),
146
+ },
147
+ services: {
148
+ refreshAccessToken: (context) => () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
149
+ // eslint-disable-next-line no-console
150
+ // console.log(
151
+ // 'refresh access token (%s)',
152
+ // typeof window === 'undefined' ? 'server' : 'client'
153
+ // );
154
+ // eslint-disable-next-line no-console
155
+ // console.log('--------------------');
156
+ let response;
157
+ if (typeof window === 'undefined') {
158
+ // server
159
+ // eslint-disable-next-line no-console
160
+ // console.log('in server refreshAccessToken');
161
+ // eslint-disable-next-line no-console
162
+ // console.log(context.refreshToken);
163
+ if (context.refreshToken === '')
164
+ throw new Error('Unauthorized.');
165
+ try {
166
+ response = yield request('http://nginx:5210/auth/refresh', {
167
+ method: 'POST',
168
+ mode: 'cors',
169
+ credentials: 'include',
170
+ headers: {
171
+ Cookie: `refresh_token=${context.refreshToken}`,
172
+ 'Content-Type': 'application/json',
173
+ },
174
+ body: JSON.stringify({
175
+ grant_type: 'refresh_token',
176
+ // client_id: 'default',
177
+ // client_secret: 'Password123!',
178
+ // scope: 'default',
179
+ }).toString(),
180
+ });
181
+ const data = response;
182
+ if (typeof data.accessToken === 'undefined') {
183
+ throw new Error('Unauthorized.');
184
+ }
185
+ return {
186
+ type: 'REFRESH_TOKEN_SUCCESS',
187
+ accessToken: data.accessToken,
188
+ };
189
+ }
190
+ catch (err) {
191
+ // eslint-disable-next-line no-console
192
+ // console.log(err);
193
+ throw new Error('Could not complete refresh request (server)');
194
+ }
195
+ }
196
+ else {
197
+ // client
198
+ response = yield request('https://middleware-clicktap.local-rmgmedia.com/auth/refresh', {
199
+ method: 'POST',
200
+ mode: 'cors',
201
+ credentials: 'include',
202
+ headers: {
203
+ 'Content-Type': 'application/json',
204
+ },
205
+ body: JSON.stringify({
206
+ grant_type: 'refresh_token',
207
+ // client_id: 'default',
208
+ // client_secret: 'Password123!',
209
+ // scope: 'default',
210
+ }).toString(),
211
+ });
212
+ const data = response;
213
+ if (typeof data.accessToken === 'undefined') {
214
+ throw new Error('Unauthorized.');
215
+ }
216
+ return {
217
+ type: 'REFRESH_TOKEN_SUCCESS',
218
+ accessToken: data.accessToken,
219
+ };
220
+ }
221
+ }),
222
+ authenticate: (context, event) => () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
223
+ var _a, _b;
224
+ const e = event; // workaround to typescript not allowing casting in parameter
225
+ if (e.type !== 'LOGIN') {
226
+ throw new Error(`Authenticate can only be called for "LOGIN" event type. Event caller: ${String(e.type)}`);
227
+ }
228
+ const response = yield request('https://middleware-clicktap.local-rmgmedia.com/auth/login', {
229
+ method: 'POST',
230
+ mode: 'cors',
231
+ credentials: 'include',
232
+ headers: {
233
+ 'Content-Type': 'application/json',
234
+ },
235
+ body: JSON.stringify({
236
+ username: e.username,
237
+ password: e.password,
238
+ // grant_type: 'password',
239
+ // client_id: 'default',
240
+ // client_secret: 'Password123!',
241
+ // scope: 'default',
242
+ }).toString(),
243
+ });
244
+ /** @todo do we need to handle different status codes here...like what if the service is down? */
245
+ const data = response;
246
+ if (typeof data.accessToken === 'undefined') {
247
+ 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.');
248
+ }
249
+ return {
250
+ type: 'AUTHENTICATE_SUCCESS',
251
+ // user: data.user,
252
+ accessToken: data.accessToken,
253
+ };
254
+ // /** @todo how to call immer assign from inside invoke here to update context? */
255
+ // console.log(data);
256
+ // console.log(event);
257
+ }),
258
+ unauthenticate: (context) => () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
259
+ // const response = await fetch(
260
+ yield fetch('https://middleware-clicktap.local-rmgmedia.com/auth/logout', {
261
+ method: 'POST',
262
+ mode: 'cors',
263
+ credentials: 'include',
264
+ // headers: {
265
+ // 'Access-Control-Allow-Origin': 'https://middleware-clicktap.local-rmgmedia.com',
266
+ // 'Access-Control-Allow-Credentials': 'true',
267
+ // },
268
+ });
269
+ /** @todo do we need to handle different status codes here...like what if the service is down? */
270
+ // const data = await response.json();
271
+ return { type: 'UNAUTHENTICATE' };
272
+ // if (!data.success) {
273
+ // throw new Error(data.message ?? 'Sign in failed. Please try again.');
274
+ // }
275
+ // return {
276
+ // type: 'AUTHENTICATE_SUCCESS',
277
+ // user: data.user,
278
+ // accessToken: data.accessToken,
279
+ // };
280
+ }),
281
+ },
282
+ // doesn't make sense in the case where you have an access token that is about to expire
283
+ // and the loggedIn state won't fire another refresh for 15 min
284
+ //
285
+ // guards: {
286
+ // checkIfLoggedIn: (context, _event) => {
287
+ // if (context.user) return true;
288
+ // },
289
+ // },
290
+ });
291
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../../../libs/state/src/auth/auth.ts"],"names":[],"mappings":";;;;AAAA,mCAAuC;AACvC,yCAAuC;AA4EvC,SAAe,OAAO,CAAI,GAAW,EAAE,OAAe;;QACpD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAC3C,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE;YAC3B,OAAO,QAAQ,CAAC,IAAI,EAAgB,CAAC;SACtC;QAED,OAAO,OAAO,CAAC,OAAO,CAAC;YACrB,OAAO,EAAE,QAAQ,CAAC,UAAU;YAC5B,OAAO,EAAE,KAAK;SACf,CAAe,CAAC;IACnB,CAAC;CAAA;AAEY,QAAA,WAAW;AACtB,qlCAAqlC;AACrlC,IAAA,sBAAa,EACX;IACE,OAAO,EAAE;QACP,UAAU;QACV,IAAI,EAAE,IAAI;QACV,WAAW,EAAE,EAAE;QACf,YAAY,EAAE,EAAE;QAChB;;;WAGG;QACH,kBAAkB,EAAE,KAAK;QACzB,SAAS,EAAE;YACT,KAAK,EAAE,EAAE;YACT,MAAM,EAAE,EAAE;YACV,OAAO,EAAE,EAAE;YACX,UAAU,EAAE,EAAE;SACf;KACF;IACD,0BAA0B,EAAE,IAAI;IAChC,EAAE,EAAE,MAAM;IACV,OAAO,EAAE,YAAY;IACrB,MAAM,EAAE;QACN,cAAc,EAAE;YACd,MAAM,EAAE;gBACN,GAAG,EAAE,cAAc;gBACnB,MAAM,EAAE;oBACN;wBACE,OAAO,EAAE,gBAAgB;wBACzB,MAAM,EAAE,UA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I,EAAE,sBAAsB;gBAC5B,mBAAmB;gBACnB,WAAW,EAAE,IAAI,CAAC,WAAW;aACF,CAAC;YAC9B,mFAAmF;YAEnF,qBAAqB;YACrB,sBAAsB;QACxB,CAAC,CAAA;QACD,cAAc,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,GAAS,EAAE;YACtC,gCAAgC;YAChC,MAAM,KAAK,CACT,4DAA4D,EAC5D;gBACE,MAAM,EAAE,MAAM;gBACd,IAAI,EAAE,MAAM;gBACZ,WAAW,EAAE,SAAS;gBACtB,aAAa;gBACb,qFAAqF;gBACrF,gDAAgD;gBAChD,KAAK;aACN,CACF,CAAC;YACF,iGAAiG;YACjG,sCAAsC;YAEtC,OAAO,EAAE,IAAI,EAAE,gBAAgB,EAAE,CAAC;YAElC,uBAAuB;YACvB,0EAA0E;YAC1E,IAAI;YAEJ,WAAW;YACX,kCAAkC;YAClC,qBAAqB;YACrB,mCAAmC;YACnC,KAAK;QACP,CAAC,CAAA;KACF;IACD,wFAAwF;IACxF,+DAA+D;IAC/D,EAAE;IACF,YAAY;IACZ,4CAA4C;IAC5C,qCAAqC;IACrC,OAAO;IACP,KAAK;CACN,CACF,CAAC"}
package/src/index.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./auth/auth"), exports);
5
+ tslib_1.__exportStar(require("./auth/AuthProvider"), exports);
6
+ tslib_1.__exportStar(require("./toast/toast"), exports);
7
+ tslib_1.__exportStar(require("./toast/ToastProvider"), exports);
8
+ tslib_1.__exportStar(require("./toast/timer"), exports);
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../libs/state/src/index.ts"],"names":[],"mappings":";;;AAAA,sDAA4B;AAC5B,8DAAoC;AACpC,wDAA8B;AAC9B,gEAAsC;AACtC,wDAA8B"}
@@ -0,0 +1,17 @@
1
+ import type { InterpreterFrom } from 'xstate';
2
+ import type { ReactNode } from 'react';
3
+ import { toastMachine } from './toast';
4
+ export declare const ToastContext: import("react").Context<import("xstate").Interpreter<import("./toast").ToastMachineContext, any, import("./toast").ToastMachineEvents, {
5
+ value: any;
6
+ context: import("./toast").ToastMachineContext;
7
+ }, import("xstate").ResolveTypegenMeta<import("xstate").TypegenDisabled, import("./toast").ToastMachineEvents, import("xstate").BaseActionObject, import("xstate").ServiceMap>>>;
8
+ export declare const useToast: () => import("xstate").Interpreter<import("./toast").ToastMachineContext, any, import("./toast").ToastMachineEvents, {
9
+ value: any;
10
+ context: import("./toast").ToastMachineContext;
11
+ }, import("xstate").ResolveTypegenMeta<import("xstate").TypegenDisabled, import("./toast").ToastMachineEvents, import("xstate").BaseActionObject, import("xstate").ServiceMap>>;
12
+ type Props = {
13
+ children: ReactNode;
14
+ service: InterpreterFrom<typeof toastMachine>;
15
+ };
16
+ export declare function ToastProvider({ children, service, }: Props): JSX.Element;
17
+ export {};
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ToastProvider = exports.useToast = exports.ToastContext = void 0;
4
+ const react_1 = require("react");
5
+ exports.ToastContext = (0, react_1.createContext)({});
6
+ const useToast = () => {
7
+ return (0, react_1.useContext)(exports.ToastContext);
8
+ };
9
+ exports.useToast = useToast;
10
+ function ToastProvider({ children, service, }) {
11
+ // const toastService = interpret(toastMachine, {
12
+ // devTools: options.devTools,
13
+ // }).start(state);
14
+ // toastService.subscribe((s) => {
15
+ // setState(s);
16
+ // });
17
+ return (<exports.ToastContext.Provider value={service}>{children}</exports.ToastContext.Provider>);
18
+ }
19
+ exports.ToastProvider = ToastProvider;
20
+ //# sourceMappingURL=ToastProvider.jsx.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ToastProvider.jsx","sourceRoot":"","sources":["../../../../../libs/state/src/toast/ToastProvider.tsx"],"names":[],"mappings":";;;AAAA,iCAAkD;AAKrC,QAAA,YAAY,GAAG,IAAA,qBAAa,EACvC,EAA0C,CAC3C,CAAC;AAEK,MAAM,QAAQ,GAAG,GAAG,EAAE;IAC3B,OAAO,IAAA,kBAAU,EAAC,oBAAY,CAAC,CAAC;AAClC,CAAC,CAAC;AAFW,QAAA,QAAQ,YAEnB;AAcF,SAAgB,aAAa,CAAC,EAC5B,QAAQ,EACR,OAAO,GAIJ;IACH,iDAAiD;IACjD,gCAAgC;IAChC,mBAAmB;IAEnB,kCAAkC;IAClC,iBAAiB;IACjB,MAAM;IAEN,OAAO,CACL,CAAC,oBAAY,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,oBAAY,CAAC,QAAQ,CAAC,CAC1E,CAAC;AACJ,CAAC;AAlBD,sCAkBC"}
@@ -0,0 +1,26 @@
1
+ /// <reference types="node" />
2
+ export interface TimerContext {
3
+ elapsed: number;
4
+ duration: number;
5
+ interval: number;
6
+ intervalId: NodeJS.Timer | null;
7
+ }
8
+ export type TimerEvents = {
9
+ type: 'START_TIMER';
10
+ } | {
11
+ type: 'RESUME_TIMER';
12
+ } | {
13
+ type: 'PAUSE_TIMER';
14
+ } | {
15
+ type: 'TICK';
16
+ } | {
17
+ type: 'DURATION.UPDATE';
18
+ value: number;
19
+ } | {
20
+ type: 'RESET_TIMER';
21
+ };
22
+ export declare const timerMachine: import("xstate").StateMachine<TimerContext, any, TimerEvents, {
23
+ value: any;
24
+ context: TimerContext;
25
+ }, import("xstate").BaseActionObject, import("xstate").ServiceMap, import("xstate").ResolveTypegenMeta<import("xstate").TypegenDisabled, TimerEvents, import("xstate").BaseActionObject, import("xstate").ServiceMap>>;
26
+ export default timerMachine;