@strivacity/sdk-next 1.0.1 → 2.0.0-beta

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/CHANGELOG.md CHANGED
@@ -1,3 +1,19 @@
1
+ ## 2.0.0-beta (2025-07-24)
2
+
3
+ ### 🚀 Features
4
+
5
+ - ionic example app added ([494805a](https://github.com/strivacity/sdk-js/commit/494805a))
6
+ - ⚠️ NativeFlow implemented ([75b353f](https://github.com/strivacity/sdk-js/commit/75b353f))
7
+ - @strivacity/sdk-next package implemented ([15d4019](https://github.com/strivacity/sdk-js/commit/15d4019))
8
+
9
+ ### ⚠️ Breaking Changes
10
+
11
+ - ⚠️ NativeFlow implemented ([75b353f](https://github.com/strivacity/sdk-js/commit/75b353f))
12
+
13
+ ### 🧱 Updated Dependencies
14
+
15
+ - Updated sdk-core to 2.0.0-beta
16
+
1
17
  ## 1.0.1 (2025-02-03)
2
18
 
3
19
 
package/README.md CHANGED
@@ -1,75 +1,432 @@
1
1
  # @strivacity/sdk-next
2
2
 
3
- > **The SDK supports React version 16 and above**
3
+ > **The SDK supports Next.js version 13 and above**
4
4
 
5
- ### Install
5
+ ## Example App
6
+
7
+ - [Example app](https://github.com/Strivacity/sdk-js/tree/main/apps/next)
8
+
9
+ ## Install
6
10
 
7
11
  ```bash
8
12
  npm install @strivacity/sdk-next
9
13
  ```
10
14
 
11
- ### Usage
15
+ ## Usage
16
+
17
+ ### Wrap your app with `StyAuthProvider`
18
+
19
+ Add the `StyAuthProvider` to your `layout.tsx` file.
12
20
 
13
- #### Wrap your app with Auth Provider:
21
+ ```tsx
22
+ 'use client';
14
23
 
15
- ```js
16
- import { AuthProvider, useStrivacity } from '@strivacity/sdk-next';
24
+ import { StyAuthProvider, type SDKOptions } from '@strivacity/sdk-next';
17
25
 
18
- const sdkOptions = {
19
- mode: 'redirect',
26
+ const options: SDKOptions = {
27
+ mode: 'redirect', // or 'popup' or 'native'
20
28
  issuer: 'https://<YOUR_DOMAIN>',
21
29
  scopes: ['openid', 'profile'],
22
30
  clientId: '<YOUR_CLIENT_ID>',
23
31
  redirectUri: '<YOUR_REDIRECT_URI>',
24
32
  };
25
- const AppRoot = () => {
33
+
34
+ export default function RootLayout({ children }: { children: React.ReactNode }) {
35
+ return (
36
+ <html lang="en">
37
+ <body>
38
+ <StyAuthProvider options={options}>{children}</StyAuthProvider>
39
+ </body>
40
+ </html>
41
+ );
42
+ }
43
+ ```
44
+
45
+ ### How to use the SDK in your components:
46
+
47
+ #### Redirect or popup mode
48
+
49
+ When using redirect or popup mode, the authentication flow involves two main components: a login page that initiates the authentication process, and a callback page that handles the response from the identity provider.
50
+
51
+ In **redirect mode**, users are redirected to the identity provider's login page in the same browser window. After successful authentication, they are redirected back to your application's callback URL.
52
+
53
+ In **popup mode**, the authentication happens in a popup window, allowing the main application to remain open while the user authenticates.
54
+
55
+ ##### Login page example
56
+
57
+ The login page is where users start the authentication process. This component automatically triggers the login flow when the page loads, redirecting users to the identity provider for authentication.
58
+
59
+ ```tsx
60
+ 'use client';
61
+
62
+ import { useEffect } from 'react';
63
+ import { useStrivacity } from '@strivacity/sdk-next';
64
+
65
+ export default function Login() {
66
+ const { login } = useStrivacity();
67
+
68
+ useEffect(() => {
69
+ login();
70
+ }, []);
71
+
72
+ return (
73
+ <section>
74
+ <h1>Redirecting...</h1>
75
+ </section>
76
+ );
77
+ }
78
+ ```
79
+
80
+ ##### Callback page example
81
+
82
+ The callback page handles the response from the identity provider after successful authentication. It processes the authentication result, extracts the tokens, and redirects users to their intended destination (typically a protected page like a profile or dashboard).
83
+
84
+ ```tsx
85
+ 'use client';
86
+
87
+ import { useEffect } from 'react';
88
+ import { useRouter } from 'next/navigation';
89
+ import { useStrivacity } from '@strivacity/sdk-next';
90
+
91
+ export default function Callback() {
92
+ const router = useRouter();
93
+ const { handleCallback } = useStrivacity();
94
+
95
+ useEffect(() => {
96
+ (async () => {
97
+ try {
98
+ await handleCallback();
99
+ router.push('/profile');
100
+ } catch (error) {
101
+ console.error('Error during callback handling:', error);
102
+ }
103
+ })();
104
+ }, []);
105
+
106
+ return (
107
+ <section>
108
+ <h1>Logging in...</h1>
109
+ </section>
110
+ );
111
+ }
112
+ ```
113
+
114
+ ##### Profile page example
115
+
116
+ The profile page displays user information and authentication details after successful login. It uses the `useStrivacity` hook to access the authentication state and display relevant data such as access tokens, ID token claims, and expiration status.
117
+
118
+ We check if the user is authenticated and display their profile information. If the user is not authenticated, we redirect them to the login page.
119
+
120
+ ```tsx
121
+ 'use client';
122
+
123
+ import Link from 'next/link';
124
+ import { useStrivacity } from '@strivacity/sdk-next';
125
+
126
+ export default function Profile() {
127
+ const { loading, isAuthenticated, accessToken, accessTokenExpired, accessTokenExpirationDate, idTokenClaims, refreshToken } = useStrivacity();
128
+
129
+ if (loading) {
130
+ return <h1>Loading...</h1>;
131
+ }
132
+
133
+ if (!isAuthenticated) {
134
+ return <Link href="/login" replace />;
135
+ }
136
+
26
137
  return (
27
- <AuthProvider options={sdkOptions}>
28
- <App />
29
- </AuthProvider>
138
+ <section>
139
+ <dl>
140
+ <dt>
141
+ <strong>accessToken</strong>
142
+ </dt>
143
+ <dd>
144
+ <pre>{JSON.stringify(accessToken)}</pre>
145
+ </dd>
146
+ <dt>
147
+ <strong>refreshToken</strong>
148
+ </dt>
149
+ <dd>
150
+ <pre>{JSON.stringify(refreshToken)}</pre>
151
+ </dd>
152
+ <dt>
153
+ <strong>accessTokenExpired</strong>
154
+ </dt>
155
+ <dd>
156
+ <pre>{JSON.stringify(accessTokenExpired)}</pre>
157
+ </dd>
158
+ <dt>
159
+ <strong>accessTokenExpirationDate</strong>
160
+ </dt>
161
+ <dd>
162
+ <pre>{accessTokenExpirationDate ? new Date(accessTokenExpirationDate * 1000).toLocaleString() : JSON.stringify(null)}</pre>
163
+ </dd>
164
+ <dt>
165
+ <strong>claims</strong>
166
+ </dt>
167
+ <dd>
168
+ <pre>{JSON.stringify(idTokenClaims, null, 2)}</pre>
169
+ </dd>
170
+ </dl>
171
+ </section>
30
172
  );
173
+ }
174
+ ```
175
+
176
+ ##### Logout page example
177
+
178
+ The logout page handles user logout by terminating their session. The `postLogoutRedirectUri` parameter is optional and specifies where users should be redirected after logout. If not provided, users will be redirected to the identity provider's logout page.
179
+
180
+ This URI must be configured in the Admin Console as an allowed post-logout redirect URI for your application.
181
+
182
+ ```tsx
183
+ 'use client';
184
+
185
+ import { useEffect } from 'react';
186
+ import { useRouter } from 'next/navigation';
187
+ import { useStrivacity } from '@strivacity/sdk-next';
188
+
189
+ export default function Logout() {
190
+ const router = useRouter();
191
+ const { isAuthenticated, logout } = useStrivacity();
192
+
193
+ useEffect(() => {
194
+ (async () => {
195
+ if (isAuthenticated) {
196
+ await logout({ postLogoutRedirectUri: location.origin });
197
+ } else {
198
+ router.push('/');
199
+ }
200
+ })();
201
+ }, []);
202
+
203
+ return (
204
+ <section>
205
+ <h1>Logging out...</h1>
206
+ </section>
207
+ );
208
+ }
209
+ ```
210
+
211
+ #### Native mode
212
+
213
+ If you are using `native` mode, you can use the `StyLoginRenderer` component to render the login UI.
214
+
215
+ To customize the UI components used in the authentication flows, define the `widgets` object in your component.
216
+
217
+ ###### Example widgets
218
+
219
+ The example widgets use SCSS for styling and Luxon for date handling. You'll need to install these dependencies:
220
+
221
+ ```bash
222
+ npm install sass luxon
223
+ npm install --save-dev @types/luxon
224
+ ```
225
+
226
+ ```tsx
227
+ import CheckboxWidget from './checkbox.widget';
228
+ import DateWidget from './date.widget';
229
+ import InputWidget from './input.widget';
230
+ import LayoutWidget from './layout.widget';
231
+ import MultiSelectWidget from './multiselect.widget';
232
+ import PasscodeWidget from './passcode.widget';
233
+ import LoadingWidget from './loading.widget';
234
+ import PasswordWidget from './password.widget';
235
+ import PhoneWidget from './phone.widget';
236
+ import SelectWidget from './select.widget';
237
+ import StaticWidget from './static.widget';
238
+ import SubmitWidget from './submit.widget';
239
+
240
+ export const widgets = {
241
+ checkbox: CheckboxWidget,
242
+ date: DateWidget,
243
+ input: InputWidget,
244
+ layout: LayoutWidget,
245
+ loading: LoadingWidget,
246
+ passcode: PasscodeWidget,
247
+ password: PasswordWidget,
248
+ phone: PhoneWidget,
249
+ select: SelectWidget,
250
+ multiSelect: MultiSelectWidget,
251
+ static: StaticWidget,
252
+ submit: SubmitWidget,
31
253
  };
32
254
  ```
33
255
 
34
- #### How to use the SDK in your components:
256
+ You can find example widgets here: [Example widgets](https://github.com/Strivacity/sdk-js/tree/main/apps/next/src/components/widgets)
257
+
258
+ ##### Login page example
259
+
260
+ The native mode login page provides a fully customizable authentication experience rendered directly within your application. Unlike redirect or popup modes, native mode keeps users on your site throughout the entire authentication process using the `StyLoginRenderer` component.
261
+
262
+ This example demonstrates how to handle session management, implement callback functions for various authentication events, and manage URL parameters for session continuity.
263
+
264
+ ```tsx
265
+ 'use client';
266
+
267
+ import { Suspense, useEffect, useState } from 'react';
268
+ import { useRouter } from 'next/navigation';
269
+ import { useStrivacity, StyLoginRenderer, FallbackError, type LoginFlowState } from '@strivacity/sdk-next';
270
+ import { widgets } from '@/components/widgets';
271
+
272
+ export default function Login() {
273
+ const router = useRouter();
274
+ const { options, login } = useStrivacity();
275
+ const [sessionId, setSessionId] = useState<string | null>(null);
276
+
277
+ /**
278
+ * Extract session_id from URL parameters and clean up the URL
279
+ * This is necessary for maintaining session state across external login providers
280
+ */
281
+ useEffect(() => {
282
+ if (window.location.search !== '') {
283
+ const url = new URL(window.location.href);
284
+ const sid = url.searchParams.get('session_id');
285
+ setSessionId(sid);
286
+ url.search = '';
287
+ window.history.replaceState({}, '', url.toString());
288
+ }
289
+ }, []);
290
+
291
+ /**
292
+ * Called when authentication is successful
293
+ * Redirects user to the profile page
294
+ */
295
+ const onLogin = () => {
296
+ router.push('/profile');
297
+ };
298
+
299
+ /**
300
+ * Called when native flow cannot handle the authentication
301
+ * Falls back to redirect mode by navigating to the provided URL
302
+ * @param error - FallbackError containing the fallback URL and message
303
+ */
304
+ const onFallback = (error: FallbackError) => {
305
+ if (error.url) {
306
+ console.log(`Fallback: ${error.url}`);
307
+ window.location.href = error.url.toString();
308
+ } else {
309
+ console.error(`FallbackError without URL: ${error.message}`);
310
+ alert(error);
311
+ }
312
+ };
313
+
314
+ /**
315
+ * Called when an error occurs during the authentication process
316
+ * @param error - Error message describing what went wrong
317
+ */
318
+ const onError = (error: string) => {
319
+ console.error(`Error: ${error}`);
320
+ alert(error);
321
+ };
35
322
 
36
- ```jsx
37
- import { useEffect, useCallback } from 'react'
323
+ /**
324
+ * Called when the authentication flow wants to display a global message
325
+ * @param message - Message to display to the user
326
+ */
327
+ const onGlobalMessage = (message: string) => {
328
+ alert(message);
329
+ };
330
+
331
+ /**
332
+ * Called when the authentication flow transitions between states
333
+ * Useful for tracking flow progress and inject custom logic such as logging or analytics
334
+ * @param params - Object containing previous and current flow states
335
+ */
336
+ const onBlockReady = ({ previousState, state }: { previousState: LoginFlowState; state: LoginFlowState }) => {
337
+ console.log('previousState', previousState);
338
+ console.log('state', state);
339
+ };
340
+
341
+ return (
342
+ <Suspense fallback={<span>Loading...</span>}>
343
+ <StyLoginRenderer
344
+ widgets={widgets}
345
+ sessionId={sessionId}
346
+ onFallback={onFallback}
347
+ onLogin={() => void onLogin()}
348
+ onError={onError}
349
+ onGlobalMessage={onGlobalMessage}
350
+ onBlockReady={onBlockReady}
351
+ />
352
+ </Suspense>
353
+ );
354
+ }
355
+ ```
356
+
357
+ ##### Callback page example
358
+
359
+ The native mode callback page handles authentication responses when external identity providers redirect back to your application. This page checks for session IDs in the URL parameters and either continues the native flow or falls back to standard callback handling.
360
+
361
+ This component is essential for handling social login providers (like Google, Facebook, etc.) that require redirect-based authentication even within native mode flows.
362
+
363
+ ```tsx
364
+ 'use client';
365
+
366
+ import { useEffect } from 'react';
367
+ import { useRouter } from 'next/navigation';
38
368
  import { useStrivacity } from '@strivacity/sdk-next';
39
369
 
40
- const { isAuthenticated, idTokenClaims, login, logout } = useStrivacity();
41
- const [name, setName] = useState('');
42
- const onLogin = useCallback(() => {
43
- login();
44
- },[]);
45
- const onLogout = useCallback(() => {
46
- logout();
47
- },[]);
48
-
49
- useEffect(() => {
50
- setName(`${idTokenClaims?.given_name} ${idTokenClaims?.family_name}`);
51
- }, [isAuthenticated, idTokenClaims]);
52
-
53
- return (
54
- {isAuthenticated ? (<>
55
- <div>Welcome, {{ name }}!</div>
56
- <button onClick={onLogout()}>Logout</button>
57
- </>) : <>
58
- <div>Not logged in</div>
59
- <button onClick={onLogin()}>Log in</button>
60
- </>}
61
- )
370
+ export default function Callback() {
371
+ const query = globalThis?.window ? Object.fromEntries(new URLSearchParams(globalThis.window.location.search)) : {};
372
+ const router = useRouter();
373
+ const { handleCallback } = useStrivacity();
374
+
375
+ useEffect(() => {
376
+ (async () => {
377
+ const url = new URL(location.href);
378
+ const sessionId = url.searchParams.get('session_id');
379
+
380
+ if (sessionId) {
381
+ router.push(`/login?session_id=${sessionId}`);
382
+ } else {
383
+ try {
384
+ await handleCallback();
385
+ router.push('/profile');
386
+ } catch (error) {
387
+ console.error('Error during callback handling:', error);
388
+ }
389
+ }
390
+ })();
391
+ }, []);
392
+
393
+ if (query.error) {
394
+ return (
395
+ <section>
396
+ <h1>Error in authentication</h1>
397
+ <div>
398
+ <h4>{query.error}</h4>
399
+ <p>{query.error_description}</p>
400
+ </div>
401
+ </section>
402
+ );
403
+ } else {
404
+ return (
405
+ <section>
406
+ <h1>Logging in...</h1>
407
+ </section>
408
+ );
409
+ }
410
+ }
62
411
  ```
63
412
 
413
+ ##### Profile page example
414
+
415
+ Same as the profile page example in redirect/popup mode.
416
+
417
+ ##### Logout page example
418
+
419
+ Same as the logout page example in redirect/popup mode.
420
+
64
421
  ### API Documentation
65
422
 
66
423
  #### `useStrivacity` hook
67
424
 
68
425
  ```typescript
69
- useStrivacity<T extends PopupContext | RedirectContext>(): T;
426
+ useStrivacity<T extends PopupContext | RedirectContext | NativeContext>(): T;
70
427
  ```
71
428
 
72
- You can choose between `PopupContext` or `RedirectContext` with the `mode` option when you configure the sdk options.
429
+ You can choose between `PopupContext`, `RedirectContext`, or `NativeContext` with the `mode` option when you configure the sdk options.
73
430
 
74
431
  **Properties**
75
432
 
@@ -92,7 +449,7 @@ Represents the available methods for Redirect-based interactions.
92
449
  - `options` (optional): Configuration options for registration.
93
450
  - **`refresh(): Promise<void>`**: Refreshes the user's session using a redirect flow.
94
451
  - **`revoke(): Promise<void>`**: Revokes the current session tokens using a redirect flow.
95
- - **`logout(options?: LogoutOptions): Promise<void>`**: Logs out the user by redirecting to the logout page.
452
+ - **`logout(options?: LogoutOptions): Promise<void>`**: Logs out the user by redirecting to the identity provider.
96
453
  - `options` (optional): Configuration options for logout.
97
454
  - **`handleCallback(url?: string): Promise<void>`**: Handles the callback after a redirect-based authentication or token exchange.
98
455
  - `url` (optional): The URL to handle for the callback.
@@ -113,6 +470,76 @@ Represents the available methods for Popup-based interactions.
113
470
  - **`handleCallback(url?: string): Promise<void>`**: Handles the callback after a popup-based authentication or token exchange.
114
471
  - `url` (optional): The URL to handle for the callback.
115
472
 
473
+ ---
474
+
475
+ Type: `NativeContext`
476
+ Represents the available methods for native-based interactions.
477
+
478
+ - **`login(options?: LoginOptions): Promise<NativeFlowHandler>`**: Initiates the login process using a native flow.
479
+ - `options` (optional): Configuration options for login.
480
+ - **`register(options?: RegisterOptions): Promise<NativeFlowHandler>`**: Registers a new user using a native flow.
481
+ - `options` (optional): Configuration options for registration.
482
+ - **`refresh(): Promise<void>`**: Refreshes the user's session.
483
+ - **`revoke(): Promise<void>`**: Revokes the current session tokens.
484
+ - **`logout(options?: LogoutOptions): Promise<void>`**: Logs out the user by redirecting to the logout page.
485
+ - `options` (optional): Configuration options for logout.
486
+ - **`handleCallback(url?: string): Promise<void>`**: Handles the callback after a redirect-based authentication. This will be called automatically by the native flow handler during fallback.
487
+ - `url` (optional): The URL to handle for the callback.
488
+
489
+ #### `StyLoginRenderer` component
490
+
491
+ The `StyLoginRenderer` component is used in native mode to render the authentication UI directly within your application. It provides a fully customizable login experience using your own UI components.
492
+
493
+ ```typescript
494
+ StyLoginRenderer: React.FC<{
495
+ params?: NativeParams;
496
+ widgets?: PartialRecord<WidgetType, React.ComponentType<any>>;
497
+ sessionId?: string | null;
498
+ onLogin?: (claims?: IdTokenClaims | null) => void;
499
+ onFallback?: (error: FallbackError) => void;
500
+ onError?: (error: any) => void;
501
+ onGlobalMessage?: (message: string) => void;
502
+ onBlockReady?: ({ previousState, state }: { previousState: LoginFlowState; state: LoginFlowState }) => void;
503
+ }>;
504
+ ```
505
+
506
+ **Properties**
507
+
508
+ - **`params?: NativeParams`** (optional): Additional parameters to pass to the native login flow. These parameters can include custom configuration options for the authentication process.
509
+
510
+ - **`widgets?: PartialRecord<WidgetType, React.ComponentType<any>>`** (optional): A collection of React components that define the UI widgets used in the authentication flow. Each widget type (input, button, layout, etc.) can be customized with your own components.
511
+
512
+ - **`sessionId?: string | null`** (optional): The session ID for continuing an existing authentication session. This is typically extracted from URL parameters when returning from external identity providers.
513
+
514
+ - **`onLogin?: (claims?: IdTokenClaims | null) => void`** (optional): Callback function called when authentication is successful. Receives the ID token claims as a parameter.
515
+
516
+ - **`onFallback?: (error: FallbackError) => void`** (optional): Callback function called when the native flow cannot handle the authentication and needs to fall back to redirect mode. The error parameter contains the fallback URL.
517
+
518
+ - **`onError?: (error: any) => void`** (optional): Callback function called when an error occurs during the authentication process. Use this to handle and display error messages to users.
519
+
520
+ - **`onGlobalMessage?: (message: string) => void`** (optional): Callback function called when the authentication flow wants to display a global message to the user (e.g., account lockout warnings, validation messages).
521
+
522
+ - **`onBlockReady?: ({ previousState, state }: { previousState: LoginFlowState; state: LoginFlowState }) => void`** (optional): Callback function called when the authentication flow transitions between states. Useful for tracking progress, implementing custom logging, or injecting analytics. Receives both the previous and current flow states.
523
+
524
+ **Widget Types**
525
+
526
+ The `widgets` prop accepts the following widget types:
527
+
528
+ - `checkbox`: For checkbox input fields
529
+ - `date`: For date input fields
530
+ - `input`: For text input fields
531
+ - `layout`: For layout containers and form structure
532
+ - `loading`: For loading indicators
533
+ - `multiSelect`: For multi-select dropdown fields
534
+ - `passcode`: For passcode input fields
535
+ - `password`: For password input fields
536
+ - `phone`: For phone number input fields
537
+ - `select`: For single-select dropdown fields
538
+ - `static`: For static text and display elements
539
+ - `submit`: For form submission buttons
540
+
541
+ Each widget component receives props specific to its type and function within the authentication flow.
542
+
116
543
  ### Links
117
544
 
118
545
  [Example app](https://github.com/Strivacity/sdk-js/tree/main/apps/next)
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("react/jsx-runtime"),n=require("react"),y=require("@strivacity/sdk-core"),m=require("./composables.cjs");let e;const A=({options:a,children:k=void 0})=>{const[i,T]=n.useState(!0),[o,b]=n.useState(!1),[r,v]=n.useState(null),[c,g]=n.useState(null),[u,f]=n.useState(null),[l,h]=n.useState(!0),[d,w]=n.useState(null),t=async()=>{b(await e.isAuthenticated),v(e.idTokenClaims||null),g(e.accessToken||null),f(e.refreshToken||null),h(e.accessTokenExpired),w(e.accessTokenExpirationDate||null),i&&T(!1)},E=n.useMemo(()=>(e||(e=y.initFlow(a),e.subscribeToEvent("init",t),e.subscribeToEvent("loggedIn",t),e.subscribeToEvent("sessionLoaded",t),e.subscribeToEvent("tokenRefreshed",t),e.subscribeToEvent("tokenRefreshFailed",t),e.subscribeToEvent("logoutInitiated",t),e.subscribeToEvent("tokenRevoked",t),e.subscribeToEvent("tokenRevokeFailed",t)),{sdk:e,loading:i,options:a,isAuthenticated:o,idTokenClaims:r,accessToken:c,refreshToken:u,accessTokenExpired:l,accessTokenExpirationDate:d,login:async s=>{if(e.options.mode==="native")return e.login(s);await e.login(s),await t()},register:async s=>{if(e.options.mode==="native")return e.register(s);await e.register(s),await t()},refresh:async()=>{await e.refresh(),await t()},revoke:async()=>{await e.revoke(),await t()},logout:async s=>{await e.logout(s),await t()},handleCallback:async s=>{await e.handleCallback(s),await t()}}),[e,i,a,r,c,u,l,d,o]);return S.jsx(m.STRIVACITY_SDK.Provider,{value:E,children:k})};exports.StyAuthProvider=A;
2
+ //# sourceMappingURL=AuthProvider.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AuthProvider.cjs","sources":["../src/AuthProvider.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { useMemo, useState } from 'react';\nimport { initFlow } from '@strivacity/sdk-core';\nimport type { SDKOptions, IdTokenClaims } from '@strivacity/sdk-core';\nimport type { PopupFlow } from '@strivacity/sdk-core/flows/PopupFlow';\nimport type { RedirectFlow } from '@strivacity/sdk-core/flows/RedirectFlow';\nimport type { NativeFlow } from '@strivacity/sdk-core/flows/NativeFlow';\nimport type { PopupContext, RedirectContext, NativeContext, Children } from './types';\nimport { STRIVACITY_SDK } from './composables';\n\nlet sdk: RedirectFlow | PopupFlow | NativeFlow;\n\nexport const StyAuthProvider: FC<{ options: SDKOptions; children?: Children }> = ({\n\toptions,\n\tchildren = undefined,\n}: {\n\toptions: SDKOptions;\n\tchildren?: Children;\n}) => {\n\tconst [loading, setLoading] = useState<boolean>(true);\n\tconst [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);\n\tconst [idTokenClaims, setIdTokenClaims] = useState<IdTokenClaims | null>(null);\n\tconst [accessToken, setAccessToken] = useState<string | null>(null);\n\tconst [refreshToken, setRefreshToken] = useState<string | null>(null);\n\tconst [accessTokenExpired, setAccessTokenExpired] = useState<boolean>(true);\n\tconst [accessTokenExpirationDate, setAccessTokenExpirationDate] = useState<number | null>(null);\n\n\tconst updateSession = async () => {\n\t\tsetIsAuthenticated(await sdk.isAuthenticated);\n\t\tsetIdTokenClaims(sdk.idTokenClaims || null);\n\t\tsetAccessToken(sdk.accessToken || null);\n\t\tsetRefreshToken(sdk.refreshToken || null);\n\t\tsetAccessTokenExpired(sdk.accessTokenExpired);\n\t\tsetAccessTokenExpirationDate(sdk.accessTokenExpirationDate || null);\n\n\t\tif (loading) {\n\t\t\tsetLoading(false);\n\t\t}\n\t};\n\n\t// @ts-expect-error: Ignore SDK type mismatch for initFlow\n\tconst value = useMemo<PopupContext | RedirectContext | NativeContext>(() => {\n\t\tif (!sdk) {\n\t\t\tsdk = initFlow(options);\n\n\t\t\tsdk.subscribeToEvent('init', updateSession);\n\t\t\tsdk.subscribeToEvent('loggedIn', updateSession);\n\t\t\tsdk.subscribeToEvent('sessionLoaded', updateSession);\n\t\t\tsdk.subscribeToEvent('tokenRefreshed', updateSession);\n\t\t\tsdk.subscribeToEvent('tokenRefreshFailed', updateSession);\n\t\t\tsdk.subscribeToEvent('logoutInitiated', updateSession);\n\t\t\tsdk.subscribeToEvent('tokenRevoked', updateSession);\n\t\t\tsdk.subscribeToEvent('tokenRevokeFailed', updateSession);\n\t\t}\n\n\t\treturn {\n\t\t\tsdk,\n\t\t\tloading,\n\t\t\toptions,\n\t\t\tisAuthenticated,\n\t\t\tidTokenClaims,\n\t\t\taccessToken,\n\t\t\trefreshToken,\n\t\t\taccessTokenExpired,\n\t\t\taccessTokenExpirationDate,\n\n\t\t\tlogin: async (options?: Parameters<PopupFlow['login'] | RedirectFlow['login'] | NativeFlow['login']>[0]) => {\n\t\t\t\tif (sdk.options.mode === 'native') {\n\t\t\t\t\treturn sdk.login(options);\n\t\t\t\t}\n\n\t\t\t\tawait sdk.login(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\tregister: async (options?: Parameters<PopupFlow['register'] | RedirectFlow['register'] | NativeFlow['register']>[0]) => {\n\t\t\t\tif (sdk.options.mode === 'native') {\n\t\t\t\t\treturn sdk.register(options);\n\t\t\t\t}\n\n\t\t\t\tawait sdk.register(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\trefresh: async () => {\n\t\t\t\tawait sdk.refresh();\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\trevoke: async () => {\n\t\t\t\tawait sdk.revoke();\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\tlogout: async (options?: Parameters<PopupFlow['logout'] | RedirectFlow['logout']>[0]) => {\n\t\t\t\tawait sdk.logout(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\thandleCallback: async (url?: Parameters<PopupFlow['handleCallback'] | RedirectFlow['handleCallback'] | NativeFlow['handleCallback']>[0]) => {\n\t\t\t\tawait sdk.handleCallback(url);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t};\n\t}, [sdk, loading, options, idTokenClaims, accessToken, refreshToken, accessTokenExpired, accessTokenExpirationDate, isAuthenticated]);\n\n\treturn <STRIVACITY_SDK.Provider value={value}>{children}</STRIVACITY_SDK.Provider>;\n};\n"],"names":["sdk","StyAuthProvider","options","children","loading","setLoading","useState","isAuthenticated","setIsAuthenticated","idTokenClaims","setIdTokenClaims","accessToken","setAccessToken","refreshToken","setRefreshToken","accessTokenExpired","setAccessTokenExpired","accessTokenExpirationDate","setAccessTokenExpirationDate","updateSession","value","useMemo","initFlow","url","jsx","STRIVACITY_SDK"],"mappings":"yMAUA,IAAIA,EAEG,MAAMC,EAAoE,CAAC,CACjF,QAAAC,EACA,SAAAC,EAAW,MACZ,IAGM,CACL,KAAM,CAACC,EAASC,CAAU,EAAIC,EAAAA,SAAkB,EAAI,EAC9C,CAACC,EAAiBC,CAAkB,EAAIF,EAAAA,SAAkB,EAAK,EAC/D,CAACG,EAAeC,CAAgB,EAAIJ,EAAAA,SAA+B,IAAI,EACvE,CAACK,EAAaC,CAAc,EAAIN,EAAAA,SAAwB,IAAI,EAC5D,CAACO,EAAcC,CAAe,EAAIR,EAAAA,SAAwB,IAAI,EAC9D,CAACS,EAAoBC,CAAqB,EAAIV,EAAAA,SAAkB,EAAI,EACpE,CAACW,EAA2BC,CAA4B,EAAIZ,EAAAA,SAAwB,IAAI,EAExFa,EAAgB,SAAY,CACjCX,EAAmB,MAAMR,EAAI,eAAe,EAC5CU,EAAiBV,EAAI,eAAiB,IAAI,EAC1CY,EAAeZ,EAAI,aAAe,IAAI,EACtCc,EAAgBd,EAAI,cAAgB,IAAI,EACxCgB,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EC,CAACnB,EAAKI,EAASF,EAASO,EAAeE,EAAaE,EAAcE,EAAoBE,EAA2BV,CAAe,CAAC,EAEpI,OAAOiB,EAAAA,IAACC,EAAAA,eAAe,SAAf,CAAwB,MAAAL,EAAe,SAAAjB,CAAA,CAAS,CACzD"}
@@ -0,0 +1,7 @@
1
+ import { FC } from 'react';
2
+ import { SDKOptions } from '@strivacity/sdk-core';
3
+ import { Children } from './types';
4
+ export declare const StyAuthProvider: FC<{
5
+ options: SDKOptions;
6
+ children?: Children;
7
+ }>;
@@ -0,0 +1,2 @@
1
+ import{jsx as h}from"react/jsx-runtime";import{useState as n,useMemo as p}from"react";import{initFlow as x}from"@strivacity/sdk-core";import{STRIVACITY_SDK as y}from"./composables.mjs";let e;const S=({options:o,children:k=void 0})=>{const[a,T]=n(!0),[i,b]=n(!1),[r,v]=n(null),[c,f]=n(null),[l,m]=n(null),[u,w]=n(!0),[d,E]=n(null),t=async()=>{b(await e.isAuthenticated),v(e.idTokenClaims||null),f(e.accessToken||null),m(e.refreshToken||null),w(e.accessTokenExpired),E(e.accessTokenExpirationDate||null),a&&T(!1)},g=p(()=>(e||(e=x(o),e.subscribeToEvent("init",t),e.subscribeToEvent("loggedIn",t),e.subscribeToEvent("sessionLoaded",t),e.subscribeToEvent("tokenRefreshed",t),e.subscribeToEvent("tokenRefreshFailed",t),e.subscribeToEvent("logoutInitiated",t),e.subscribeToEvent("tokenRevoked",t),e.subscribeToEvent("tokenRevokeFailed",t)),{sdk:e,loading:a,options:o,isAuthenticated:i,idTokenClaims:r,accessToken:c,refreshToken:l,accessTokenExpired:u,accessTokenExpirationDate:d,login:async s=>{if(e.options.mode==="native")return e.login(s);await e.login(s),await t()},register:async s=>{if(e.options.mode==="native")return e.register(s);await e.register(s),await t()},refresh:async()=>{await e.refresh(),await t()},revoke:async()=>{await e.revoke(),await t()},logout:async s=>{await e.logout(s),await t()},handleCallback:async s=>{await e.handleCallback(s),await t()}}),[e,a,o,r,c,l,u,d,i]);return h(y.Provider,{value:g,children:k})};export{S as StyAuthProvider};
2
+ //# sourceMappingURL=AuthProvider.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AuthProvider.mjs","sources":["../src/AuthProvider.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { useMemo, useState } from 'react';\nimport { initFlow } from '@strivacity/sdk-core';\nimport type { SDKOptions, IdTokenClaims } from '@strivacity/sdk-core';\nimport type { PopupFlow } from '@strivacity/sdk-core/flows/PopupFlow';\nimport type { RedirectFlow } from '@strivacity/sdk-core/flows/RedirectFlow';\nimport type { NativeFlow } from '@strivacity/sdk-core/flows/NativeFlow';\nimport type { PopupContext, RedirectContext, NativeContext, Children } from './types';\nimport { STRIVACITY_SDK } from './composables';\n\nlet sdk: RedirectFlow | PopupFlow | NativeFlow;\n\nexport const StyAuthProvider: FC<{ options: SDKOptions; children?: Children }> = ({\n\toptions,\n\tchildren = undefined,\n}: {\n\toptions: SDKOptions;\n\tchildren?: Children;\n}) => {\n\tconst [loading, setLoading] = useState<boolean>(true);\n\tconst [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);\n\tconst [idTokenClaims, setIdTokenClaims] = useState<IdTokenClaims | null>(null);\n\tconst [accessToken, setAccessToken] = useState<string | null>(null);\n\tconst [refreshToken, setRefreshToken] = useState<string | null>(null);\n\tconst [accessTokenExpired, setAccessTokenExpired] = useState<boolean>(true);\n\tconst [accessTokenExpirationDate, setAccessTokenExpirationDate] = useState<number | null>(null);\n\n\tconst updateSession = async () => {\n\t\tsetIsAuthenticated(await sdk.isAuthenticated);\n\t\tsetIdTokenClaims(sdk.idTokenClaims || null);\n\t\tsetAccessToken(sdk.accessToken || null);\n\t\tsetRefreshToken(sdk.refreshToken || null);\n\t\tsetAccessTokenExpired(sdk.accessTokenExpired);\n\t\tsetAccessTokenExpirationDate(sdk.accessTokenExpirationDate || null);\n\n\t\tif (loading) {\n\t\t\tsetLoading(false);\n\t\t}\n\t};\n\n\t// @ts-expect-error: Ignore SDK type mismatch for initFlow\n\tconst value = useMemo<PopupContext | RedirectContext | NativeContext>(() => {\n\t\tif (!sdk) {\n\t\t\tsdk = initFlow(options);\n\n\t\t\tsdk.subscribeToEvent('init', updateSession);\n\t\t\tsdk.subscribeToEvent('loggedIn', updateSession);\n\t\t\tsdk.subscribeToEvent('sessionLoaded', updateSession);\n\t\t\tsdk.subscribeToEvent('tokenRefreshed', updateSession);\n\t\t\tsdk.subscribeToEvent('tokenRefreshFailed', updateSession);\n\t\t\tsdk.subscribeToEvent('logoutInitiated', updateSession);\n\t\t\tsdk.subscribeToEvent('tokenRevoked', updateSession);\n\t\t\tsdk.subscribeToEvent('tokenRevokeFailed', updateSession);\n\t\t}\n\n\t\treturn {\n\t\t\tsdk,\n\t\t\tloading,\n\t\t\toptions,\n\t\t\tisAuthenticated,\n\t\t\tidTokenClaims,\n\t\t\taccessToken,\n\t\t\trefreshToken,\n\t\t\taccessTokenExpired,\n\t\t\taccessTokenExpirationDate,\n\n\t\t\tlogin: async (options?: Parameters<PopupFlow['login'] | RedirectFlow['login'] | NativeFlow['login']>[0]) => {\n\t\t\t\tif (sdk.options.mode === 'native') {\n\t\t\t\t\treturn sdk.login(options);\n\t\t\t\t}\n\n\t\t\t\tawait sdk.login(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\tregister: async (options?: Parameters<PopupFlow['register'] | RedirectFlow['register'] | NativeFlow['register']>[0]) => {\n\t\t\t\tif (sdk.options.mode === 'native') {\n\t\t\t\t\treturn sdk.register(options);\n\t\t\t\t}\n\n\t\t\t\tawait sdk.register(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\trefresh: async () => {\n\t\t\t\tawait sdk.refresh();\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\trevoke: async () => {\n\t\t\t\tawait sdk.revoke();\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\tlogout: async (options?: Parameters<PopupFlow['logout'] | RedirectFlow['logout']>[0]) => {\n\t\t\t\tawait sdk.logout(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\thandleCallback: async (url?: Parameters<PopupFlow['handleCallback'] | RedirectFlow['handleCallback'] | NativeFlow['handleCallback']>[0]) => {\n\t\t\t\tawait sdk.handleCallback(url);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t};\n\t}, [sdk, loading, options, idTokenClaims, accessToken, refreshToken, accessTokenExpired, accessTokenExpirationDate, isAuthenticated]);\n\n\treturn <STRIVACITY_SDK.Provider value={value}>{children}</STRIVACITY_SDK.Provider>;\n};\n"],"names":["sdk","StyAuthProvider","options","children","loading","setLoading","useState","isAuthenticated","setIsAuthenticated","idTokenClaims","setIdTokenClaims","accessToken","setAccessToken","refreshToken","setRefreshToken","accessTokenExpired","setAccessTokenExpired","accessTokenExpirationDate","setAccessTokenExpirationDate","updateSession","value","useMemo","initFlow","url","jsx","STRIVACITY_SDK"],"mappings":"yLAUA,IAAIA,EAEG,MAAMC,EAAoE,CAAC,CACjF,QAAAC,EACA,SAAAC,EAAW,MACZ,IAGM,CACL,KAAM,CAACC,EAASC,CAAU,EAAIC,EAAkB,EAAI,EAC9C,CAACC,EAAiBC,CAAkB,EAAIF,EAAkB,EAAK,EAC/D,CAACG,EAAeC,CAAgB,EAAIJ,EAA+B,IAAI,EACvE,CAACK,EAAaC,CAAc,EAAIN,EAAwB,IAAI,EAC5D,CAACO,EAAcC,CAAe,EAAIR,EAAwB,IAAI,EAC9D,CAACS,EAAoBC,CAAqB,EAAIV,EAAkB,EAAI,EACpE,CAACW,EAA2BC,CAA4B,EAAIZ,EAAwB,IAAI,EAExFa,EAAgB,SAAY,CACjCX,EAAmB,MAAMR,EAAI,eAAe,EAC5CU,EAAiBV,EAAI,eAAiB,IAAI,EAC1CY,EAAeZ,EAAI,aAAe,IAAI,EACtCc,EAAgBd,EAAI,cAAgB,IAAI,EACxCgB,EAAsBhB,EAAI,kBAAkB,EAC5CkB,EAA6BlB,EAAI,2BAA6B,IAAI,EAE9DI,G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OAAOiB,EAACC,EAAe,SAAf,CAAwB,MAAAL,EAAe,SAAAjB,CAAA,CAAS,CACzD"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("react/jsx-runtime"),u=require("react"),v=require("@strivacity/sdk-core"),D=require("@strivacity/sdk-core/utils/object"),J=require("./composables.cjs"),k=u.createContext(null),A=({items:U,widgets:C,state:y,triggerFallback:w})=>h.jsx(h.Fragment,{children:U.map((n,l)=>{var g;if(n.type==="widget"){const r=(g=y.forms)==null?void 0:g.find(b=>b.id===n.formId),f=r==null?void 0:r.widgets.find(b=>b.id===n.widgetId);if(!r||!f)return w(),null;const d=C[f.type];return d?h.jsx(d,{formId:r.id,config:f},`${r.id}.${f.id}`):(w(),null)}else if(n.type==="vertical"||n.type==="horizontal"){const r=C.layout;return r?h.jsx(r,{formId:n.items[0].formId,type:n.type,children:h.jsx(A,{items:n.items,widgets:C,state:y,triggerFallback:w})},l):(w(),null)}else return w(),null})}),K=U=>{var q,T,N,O,L;const{params:C,widgets:y,sessionId:w,onLogin:n,onFallback:l,onError:g,onGlobalMessage:r,onBlockReady:f}={params:{},widgets:{},sessionId:null,...U},{sdk:d}=J.useStrivacity(),b=u.useRef(null),[I,z]=u.useState(!1),[x,j]=u.useState({}),[P,S]=u.useState({}),[t,E]=u.useState({}),R=u.useCallback(c=>{const e=c||t.hostedUrl;if(!e)throw new Error("No hosted URL provided");l==null||l(new v.FallbackError(new URL(e)))},[t,l]),V=u.useCallback((c,e,s)=>{j(o=>({...o,[c]:{...o[c]||{},[e]:s===""?null:s}}))},[]),W=u.useCallback((c,e,s)=>{S(o=>({...o,[c]:{...o[c]||{},[e]:s}}))},[]),$=u.useCallback(async c=>{var e;try{z(!0);const s=await((e=b.current)==null?void 0:e.submitForm(c,D.unflattenObject(x[c])));if(await d.isAuthenticated)n==null||n(d.idTokenClaims);else{const o=structuredClone(t),i={hostedUrl:(s==null?void 0:s.hostedUrl)??t.hostedUrl,finalizeUrl:(s==null?void 0:s.finalizeUrl)??t.finalizeUrl,screen:(s==null?void 0:s.screen)??t.screen,forms:(s==null?void 0:s.forms)??t.forms,layout:(s==null?void 0:s.layout)??t.layout,messages:(s==null?void 0:s.messages)??t.messages,branding:(s==null?void 0:s.branding)??t.branding};if(i.screen!==t.screen){const m={},a={};for(const p of i.forms??[])m[p.id]={},a[p.id]={};j(m),S(a)}Object.keys(i.messages??{}).forEach(m=>{var a,p;m==="global"?r==null||r(((p=(a=i.messages)==null?void 0:a.global)==null?void 0:p.text)??""):S(H=>({...H,[m]:i.messages[m]}))}),E(i),z(!1),setTimeout(()=>{f==null||f({previousState:o,state:structuredClone(i)})},1)}}catch(s){console.error("Error submitting form:",s),s instanceof v.FallbackError?l==null||l(s):g==null||g(s)}},[d,C,x,t,n,l,g,r,f]),F={loading:I,forms:x,messages:P,state:t,submitForm:$,triggerFallback:R,setFormValue:V,setMessage:W};return u.useEffect(()=>{b.current=d.login(C),(async()=>{var c;try{const e=await((c=b.current)==null?void 0:c.startSession(w)),s=structuredClone(t),o={hostedUrl:(e==null?void 0:e.hostedUrl)??t.hostedUrl,finalizeUrl:(e==null?void 0:e.finalizeUrl)??t.finalizeUrl,screen:(e==null?void 0:e.screen)??t.screen,forms:(e==null?void 0:e.forms)??t.forms,layout:(e==null?void 0:e.layout)??t.layout,messages:(e==null?void 0:e.messages)??t.messages,branding:(e==null?void 0:e.branding)??t.branding};if(await d.isAuthenticated)n==null||n(d.idTokenClaims);else{if(o.screen!==t.screen){const i={},m={};for(const a of o.forms??[])i[a.id]={},m[a.id]={};j(i),S(m)}Object.keys(o.messages??{}).forEach(i=>{var m,a;i==="global"?r==null||r(((a=(m=o.messages)==null?void 0:m.global)==null?void 0:a.text)??""):S(p=>({...p,[i]:o.messages[i]}))}),E(o),setTimeout(()=>{f==null||f({previousState:s,state:structuredClone(o)})},1)}}catch(e){e instanceof v.FallbackError?l==null||l(e):g==null||g(e)}})()},[]),h.jsx(k.Provider,{value:F,children:h.jsx("div",{className:"login-renderer",children:t.screen&&y.layout?u.createElement(y.layout,{formId:(N=(T=(q=t.layout)==null?void 0:q.items)==null?void 0:T[0])==null?void 0:N.formId,type:(O=t.layout)==null?void 0:O.type,tag:"form"},h.jsx(A,{items:((L=t.layout)==null?void 0:L.items)??[],widgets:y,state:t,triggerFallback:R})):y.loading?u.createElement(y.loading):null})})};exports.NativeFlowContext=k;exports.StyLoginRenderer=K;
2
+ //# sourceMappingURL=LoginRenderer.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LoginRenderer.cjs","sources":["../src/LoginRenderer.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { NativeParams, PartialRecord, WidgetType, LayoutWidget, LoginFlowState, Widget, IdTokenClaims, LoginFlowMessage } from '@strivacity/sdk-core';\nimport type { NativeContext, NativeFlowContextValue } from './types';\nimport React, { useRef, useState, useEffect, createContext, useCallback } from 'react';\nimport { FallbackError } from '@strivacity/sdk-core';\nimport { unflattenObject } from '@strivacity/sdk-core/utils/object';\nimport { useStrivacity } from './composables';\n\nexport const NativeFlowContext = createContext<NativeFlowContextValue | null>(null);\n\nconst StyWidgetRenderer: React.FC<{\n\titems: LayoutWidget['items'];\n\twidgets: PartialRecord<WidgetType, React.ComponentType<any>>;\n\tstate: LoginFlowState;\n\ttriggerFallback: (hostedUrl?: string) => void;\n}> = ({ items, widgets, state, triggerFallback }) => {\n\treturn (\n\t\t<>\n\t\t\t{items.map((item, idx) => {\n\t\t\t\tif (item.type === 'widget') {\n\t\t\t\t\tconst form = state.forms?.find((f) => f.id === item.formId);\n\t\t\t\t\tconst widget = form?.widgets.find((w) => w.id === item.widgetId);\n\n\t\t\t\t\tif (!form || !widget) {\n\t\t\t\t\t\ttriggerFallback();\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst WidgetComponent = widgets[widget.type];\n\n\t\t\t\t\tif (!WidgetComponent) {\n\t\t\t\t\t\ttriggerFallback();\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn <WidgetComponent key={`${form.id}.${widget.id}`} formId={form.id} config={widget} />;\n\t\t\t\t} else if (item.type === 'vertical' || item.type === 'horizontal') {\n\t\t\t\t\tconst LayoutComponent = widgets.layout;\n\n\t\t\t\t\tif (!LayoutComponent) {\n\t\t\t\t\t\ttriggerFallback();\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn (\n\t\t\t\t\t\t<LayoutComponent key={idx} formId={(item.items[0] as Widget).formId} type={item.type}>\n\t\t\t\t\t\t\t<StyWidgetRenderer items={item.items} widgets={widgets} state={state} triggerFallback={triggerFallback} />\n\t\t\t\t\t\t</LayoutComponent>\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\ttriggerFallback();\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t})}\n\t\t</>\n\t);\n};\n\nexport const StyLoginRenderer: React.FC<{\n\tparams?: NativeParams;\n\twidgets?: PartialRecord<WidgetType, React.ComponentType<any>>;\n\tsessionId?: string | null;\n\tonLogin?: (claims?: IdTokenClaims | null) => void;\n\tonFallback?: (error: FallbackError) => void;\n\tonError?: (error: any) => void;\n\tonGlobalMessage?: (message: string) => void;\n\tonBlockReady?: ({ previousState, state }: { previousState: LoginFlowState; state: LoginFlowState }) => void;\n}> = (props) => {\n\tconst { params, widgets, sessionId, onLogin, onFallback, onError, onGlobalMessage, onBlockReady } = {\n\t\tparams: {},\n\t\twidgets: {},\n\t\tsessionId: null,\n\t\t...props,\n\t};\n\tconst { sdk } = useStrivacity<NativeContext>();\n\tconst loginHandlerRef = useRef<ReturnType<(typeof sdk)['login']> | null>(null);\n\n\tconst [loading, setLoading] = useState(false);\n\tconst [forms, setforms] = useState<Record<string, Record<string, unknown>>>({});\n\tconst [messages, setmessages] = useState<Record<string, Record<string, LoginFlowMessage>>>({});\n\tconst [state, setState] = useState<LoginFlowState>({});\n\n\tconst triggerFallback = useCallback(\n\t\t(hostedUrl?: string) => {\n\t\t\tconst url = hostedUrl || state.hostedUrl;\n\n\t\t\tif (!url) {\n\t\t\t\tthrow new Error('No hosted URL provided');\n\t\t\t}\n\n\t\t\tonFallback?.(new FallbackError(new URL(url)));\n\t\t},\n\t\t[state, onFallback],\n\t);\n\n\tconst setFormValue = useCallback((formId: string, widgetId: string, value: unknown) => {\n\t\tsetforms((prev) => ({\n\t\t\t...prev,\n\t\t\t[formId]: { ...(prev[formId] || {}), [widgetId]: value === '' ? null : value },\n\t\t}));\n\t}, []);\n\n\tconst setMessage = useCallback((formId: string, widgetId: string, value: LoginFlowMessage) => {\n\t\tsetmessages((prev) => ({\n\t\t\t...prev,\n\t\t\t[formId]: { ...(prev[formId] || {}), [widgetId]: value },\n\t\t}));\n\t}, []);\n\n\tconst submitForm = useCallback(\n\t\tasync (formId: string) => {\n\t\t\ttry {\n\t\t\t\tsetLoading(true);\n\n\t\t\t\tconst data = await loginHandlerRef.current?.submitForm(formId, unflattenObject(forms[formId]));\n\n\t\t\t\tif (await sdk.isAuthenticated) {\n\t\t\t\t\tonLogin?.(sdk.idTokenClaims);\n\t\t\t\t} else {\n\t\t\t\t\tconst previousState = structuredClone(state);\n\t\t\t\t\tconst newState: LoginFlowState = {\n\t\t\t\t\t\thostedUrl: data?.hostedUrl ?? state.hostedUrl,\n\t\t\t\t\t\tfinalizeUrl: data?.finalizeUrl ?? state.finalizeUrl,\n\t\t\t\t\t\tscreen: data?.screen ?? state.screen,\n\t\t\t\t\t\tforms: data?.forms ?? state.forms,\n\t\t\t\t\t\tlayout: data?.layout ?? state.layout,\n\t\t\t\t\t\tmessages: data?.messages ?? state.messages,\n\t\t\t\t\t\tbranding: data?.branding ?? state.branding,\n\t\t\t\t\t};\n\n\t\t\t\t\tif (newState.screen !== state.screen) {\n\t\t\t\t\t\tconst newforms: typeof forms = {};\n\t\t\t\t\t\tconst newmessages: typeof messages = {};\n\n\t\t\t\t\t\tfor (const form of newState.forms ?? []) {\n\t\t\t\t\t\t\tnewforms[form.id] = {};\n\t\t\t\t\t\t\tnewmessages[form.id] = {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsetforms(newforms);\n\t\t\t\t\t\tsetmessages(newmessages);\n\t\t\t\t\t}\n\n\t\t\t\t\tObject.keys(newState.messages ?? {}).forEach((formId) => {\n\t\t\t\t\t\tif (formId === 'global') {\n\t\t\t\t\t\t\tonGlobalMessage?.(newState.messages?.global?.text ?? '');\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsetmessages((prev) => ({\n\t\t\t\t\t\t\t\t...prev,\n\t\t\t\t\t\t\t\t[formId]: newState.messages![formId],\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tsetState(newState);\n\t\t\t\t\tsetLoading(false);\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tonBlockReady?.({ previousState, state: structuredClone(newState) });\n\t\t\t\t\t}, 1);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\tconsole.error('Error submitting form:', error);\n\n\t\t\t\tif (error instanceof FallbackError) {\n\t\t\t\t\tonFallback?.(error);\n\t\t\t\t} else {\n\t\t\t\t\tonError?.(error);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t[sdk, params, forms, state, onLogin, onFallback, onError, onGlobalMessage, onBlockReady],\n\t);\n\n\t// Provide context value\n\tconst contextValue: NativeFlowContextValue = {\n\t\tloading,\n\t\tforms,\n\t\tmessages,\n\t\tstate,\n\t\tsubmitForm,\n\t\ttriggerFallback,\n\t\tsetFormValue,\n\t\tsetMessage,\n\t};\n\n\tuseEffect(() => {\n\t\tloginHandlerRef.current = sdk.login(params);\n\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tconst data = await loginHandlerRef.current?.startSession(sessionId);\n\t\t\t\tconst previousState = structuredClone(state);\n\t\t\t\tconst newState: LoginFlowState = {\n\t\t\t\t\thostedUrl: data?.hostedUrl ?? state.hostedUrl,\n\t\t\t\t\tfinalizeUrl: data?.finalizeUrl ?? state.finalizeUrl,\n\t\t\t\t\tscreen: data?.screen ?? state.screen,\n\t\t\t\t\tforms: data?.forms ?? state.forms,\n\t\t\t\t\tlayout: data?.layout ?? state.layout,\n\t\t\t\t\tmessages: data?.messages ?? state.messages,\n\t\t\t\t\tbranding: data?.branding ?? state.branding,\n\t\t\t\t};\n\n\t\t\t\tif (await sdk.isAuthenticated) {\n\t\t\t\t\tonLogin?.(sdk.idTokenClaims);\n\t\t\t\t} else {\n\t\t\t\t\tif (newState.screen !== state.screen) {\n\t\t\t\t\t\tconst newforms: typeof forms = {};\n\t\t\t\t\t\tconst newmessages: typeof messages = {};\n\n\t\t\t\t\t\tfor (const form of newState.forms ?? []) {\n\t\t\t\t\t\t\tnewforms[form.id] = {};\n\t\t\t\t\t\t\tnewmessages[form.id] = {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsetforms(newforms);\n\t\t\t\t\t\tsetmessages(newmessages);\n\t\t\t\t\t}\n\n\t\t\t\t\tObject.keys(newState.messages ?? {}).forEach((formId) => {\n\t\t\t\t\t\tif (formId === 'global') {\n\t\t\t\t\t\t\tonGlobalMessage?.(newState.messages?.global?.text ?? '');\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsetmessages((prev) => ({\n\t\t\t\t\t\t\t\t...prev,\n\t\t\t\t\t\t\t\t[formId]: newState.messages![formId],\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tsetState(newState);\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tonBlockReady?.({ previousState, state: structuredClone(newState) });\n\t\t\t\t\t}, 1);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof FallbackError) {\n\t\t\t\t\tonFallback?.(error);\n\t\t\t\t} else {\n\t\t\t\t\tonError?.(error);\n\t\t\t\t}\n\t\t\t}\n\t\t})();\n\t}, []);\n\n\treturn (\n\t\t<NativeFlowContext.Provider value={contextValue}>\n\t\t\t<div className=\"login-renderer\">\n\t\t\t\t{state.screen && widgets.layout\n\t\t\t\t\t? React.createElement(\n\t\t\t\t\t\t\twidgets.layout,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tformId: (state.layout?.items?.[0] as Widget)?.formId,\n\t\t\t\t\t\t\t\ttype: state.layout?.type,\n\t\t\t\t\t\t\t\ttag: 'form',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t<StyWidgetRenderer items={state.layout?.items ?? []} widgets={widgets} state={state} triggerFallback={triggerFallback} />,\n\t\t\t\t\t\t)\n\t\t\t\t\t: widgets.loading\n\t\t\t\t\t\t? React.createElement(widgets.loading)\n\t\t\t\t\t\t: null}\n\t\t\t</div>\n\t\t</NativeFlowContext.Provider>\n\t);\n};\n"],"names":["NativeFlowContext","createContext","StyWidgetRenderer","items","widgets","state","triggerFallback","jsx","Fragment","item","idx","form","_a","f","widget","w","WidgetComponent","LayoutComponent","StyLoginRenderer","props","params","sessionId","onLogin","onFallback","onError","onGlobalMessage","onBlockReady","sdk","useStrivacity","loginHandlerRef","useRef","loading","setLoading","useState","forms","setforms","messages","setmessages","setState","useCallback","hostedUrl","url","FallbackError","setFormValue","formId","widgetId","value","prev","setMessage","submitForm","data","unflattenObject","previousState","newState","newforms","newmessages","_b","error","contextValue","useEffect","React","_c","_d","_e"],"mappings":"wPAQaA,EAAoBC,EAAAA,cAA6C,IAAI,EAE5EC,EAKD,CAAC,CAAE,MAAAC,EAAO,QAAAC,EAAS,MAAAC,EAAO,gBAAAC,KAE7BC,EAAAA,IAAAC,EAAAA,SAAA,CACE,SAAAL,EAAM,IAAI,CAACM,EAAMC,IAAQ,OACzB,GAAID,EAAK,OAAS,SAAU,CAC3B,MAAME,GAAOC,EAAAP,EAAM,QAAN,YAAAO,EAAa,KAAMC,GAAMA,EA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CACL,OACQI,EAAO,CACXA,aAAiBf,EAAAA,cACpBnB,GAAA,MAAAA,EAAakC,GAEbjC,GAAA,MAAAA,EAAUiC,EACX,CACD,GACD,CAAG,EACD,EAAE,EAGJlD,EAAAA,IAACP,EAAkB,SAAlB,CAA2B,MAAO0D,EAClC,SAAAnD,MAAC,MAAA,CAAI,UAAU,iBACb,SAAAF,EAAM,QAAUD,EAAQ,OACtBwD,EAAM,cACNxD,EAAQ,OACR,CACC,QAASyD,GAAAL,GAAA5C,EAAAP,EAAM,SAAN,YAAAO,EAAc,QAAd,YAAA4C,EAAsB,KAAtB,YAAAK,EAAqC,OAC9C,MAAMC,EAAAzD,EAAM,SAAN,YAAAyD,EAAc,KACpB,IAAK,MAAA,EAENvD,EAAAA,IAACL,EAAA,CAAkB,QAAO6D,EAAA1D,EAAM,SAAN,YAAA0D,EAAc,QAAS,GAAI,QAAA3D,EAAkB,MAAAC,EAAc,gBAAAC,CAAA,CAAkC,CAAA,EAEvHF,EAAQ,QACPwD,EAAM,cAAcxD,EAAQ,OAAO,EACnC,IAAA,CACL,EACD,CAEF"}
@@ -0,0 +1,17 @@
1
+ import { NativeParams, PartialRecord, WidgetType, LoginFlowState, IdTokenClaims, FallbackError } from '@strivacity/sdk-core';
2
+ import { NativeFlowContextValue } from './types';
3
+ import { default as React } from 'react';
4
+ export declare const NativeFlowContext: React.Context<NativeFlowContextValue | null>;
5
+ export declare const StyLoginRenderer: React.FC<{
6
+ params?: NativeParams;
7
+ widgets?: PartialRecord<WidgetType, React.ComponentType<any>>;
8
+ sessionId?: string | null;
9
+ onLogin?: (claims?: IdTokenClaims | null) => void;
10
+ onFallback?: (error: FallbackError) => void;
11
+ onError?: (error: any) => void;
12
+ onGlobalMessage?: (message: string) => void;
13
+ onBlockReady?: ({ previousState, state }: {
14
+ previousState: LoginFlowState;
15
+ state: LoginFlowState;
16
+ }) => void;
17
+ }>;
@@ -0,0 +1,2 @@
1
+ import{jsx as w,Fragment as Q}from"react/jsx-runtime";import V,{createContext as X,useRef as Y,useState as S,useCallback as b,useEffect as Z}from"react";import{FallbackError as E}from"@strivacity/sdk-core";import{unflattenObject as _}from"@strivacity/sdk-core/utils/object";import{useStrivacity as F}from"./composables.mjs";const M=X(null),W=({items:v,widgets:U,state:a,triggerFallback:y})=>w(Q,{children:v.map((n,l)=>{var g;if(n.type==="widget"){const r=(g=a.forms)==null?void 0:g.find(h=>h.id===n.formId),u=r==null?void 0:r.widgets.find(h=>h.id===n.widgetId);if(!r||!u)return y(),null;const d=U[u.type];return d?w(d,{formId:r.id,config:u},`${r.id}.${u.id}`):(y(),null)}else if(n.type==="vertical"||n.type==="horizontal"){const r=U.layout;return r?w(r,{formId:n.items[0].formId,type:n.type,children:w(W,{items:n.items,widgets:U,state:a,triggerFallback:y})},l):(y(),null)}else return y(),null})}),te=v=>{var N,O,A,I,L;const{params:U,widgets:a,sessionId:y,onLogin:n,onFallback:l,onError:g,onGlobalMessage:r,onBlockReady:u}={params:{},widgets:{},sessionId:null,...v},{sdk:d}=F(),h=Y(null),[$,j]=S(!1),[x,z]=S({}),[H,C]=S({}),[t,R]=S({}),T=b(c=>{const e=c||t.hostedUrl;if(!e)throw new Error("No hosted URL provided");l==null||l(new E(new URL(e)))},[t,l]),P=b((c,e,s)=>{z(o=>({...o,[c]:{...o[c]||{},[e]:s===""?null:s}}))},[]),q=b((c,e,s)=>{C(o=>({...o,[c]:{...o[c]||{},[e]:s}}))},[]),D=b(async c=>{var e;try{j(!0);const s=await((e=h.current)==null?void 0:e.submitForm(c,_(x[c])));if(await d.isAuthenticated)n==null||n(d.idTokenClaims);else{const o=structuredClone(t),i={hostedUrl:(s==null?void 0:s.hostedUrl)??t.hostedUrl,finalizeUrl:(s==null?void 0:s.finalizeUrl)??t.finalizeUrl,screen:(s==null?void 0:s.screen)??t.screen,forms:(s==null?void 0:s.forms)??t.forms,layout:(s==null?void 0:s.layout)??t.layout,messages:(s==null?void 0:s.messages)??t.messages,branding:(s==null?void 0:s.branding)??t.branding};if(i.screen!==t.screen){const m={},f={};for(const p of i.forms??[])m[p.id]={},f[p.id]={};z(m),C(f)}Object.keys(i.messages??{}).forEach(m=>{var f,p;m==="global"?r==null||r(((p=(f=i.messages)==null?void 0:f.global)==null?void 0:p.text)??""):C(K=>({...K,[m]:i.messages[m]}))}),R(i),j(!1),setTimeout(()=>{u==null||u({previousState:o,state:structuredClone(i)})},1)}}catch(s){console.error("Error submitting form:",s),s instanceof E?l==null||l(s):g==null||g(s)}},[d,U,x,t,n,l,g,r,u]),J={loading:$,forms:x,messages:H,state:t,submitForm:D,triggerFallback:T,setFormValue:P,setMessage:q};return Z(()=>{h.current=d.login(U),(async()=>{var c;try{const e=await((c=h.current)==null?void 0:c.startSession(y)),s=structuredClone(t),o={hostedUrl:(e==null?void 0:e.hostedUrl)??t.hostedUrl,finalizeUrl:(e==null?void 0:e.finalizeUrl)??t.finalizeUrl,screen:(e==null?void 0:e.screen)??t.screen,forms:(e==null?void 0:e.forms)??t.forms,layout:(e==null?void 0:e.layout)??t.layout,messages:(e==null?void 0:e.messages)??t.messages,branding:(e==null?void 0:e.branding)??t.branding};if(await d.isAuthenticated)n==null||n(d.idTokenClaims);else{if(o.screen!==t.screen){const i={},m={};for(const f of o.forms??[])i[f.id]={},m[f.id]={};z(i),C(m)}Object.keys(o.messages??{}).forEach(i=>{var m,f;i==="global"?r==null||r(((f=(m=o.messages)==null?void 0:m.global)==null?void 0:f.text)??""):C(p=>({...p,[i]:o.messages[i]}))}),R(o),setTimeout(()=>{u==null||u({previousState:s,state:structuredClone(o)})},1)}}catch(e){e instanceof E?l==null||l(e):g==null||g(e)}})()},[]),w(M.Provider,{value:J,children:w("div",{className:"login-renderer",children:t.screen&&a.layout?V.createElement(a.layout,{formId:(A=(O=(N=t.layout)==null?void 0:N.items)==null?void 0:O[0])==null?void 0:A.formId,type:(I=t.layout)==null?void 0:I.type,tag:"form"},w(W,{items:((L=t.layout)==null?void 0:L.items)??[],widgets:a,state:t,triggerFallback:T})):a.loading?V.createElement(a.loading):null})})};export{M as NativeFlowContext,te as StyLoginRenderer};
2
+ //# sourceMappingURL=LoginRenderer.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LoginRenderer.mjs","sources":["../src/LoginRenderer.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { NativeParams, PartialRecord, WidgetType, LayoutWidget, LoginFlowState, Widget, IdTokenClaims, LoginFlowMessage } from '@strivacity/sdk-core';\nimport type { NativeContext, NativeFlowContextValue } from './types';\nimport React, { useRef, useState, useEffect, createContext, useCallback } from 'react';\nimport { FallbackError } from '@strivacity/sdk-core';\nimport { unflattenObject } from '@strivacity/sdk-core/utils/object';\nimport { useStrivacity } from './composables';\n\nexport const NativeFlowContext = createContext<NativeFlowContextValue | null>(null);\n\nconst StyWidgetRenderer: React.FC<{\n\titems: LayoutWidget['items'];\n\twidgets: PartialRecord<WidgetType, React.ComponentType<any>>;\n\tstate: LoginFlowState;\n\ttriggerFallback: (hostedUrl?: string) => void;\n}> = ({ items, widgets, state, triggerFallback }) => {\n\treturn (\n\t\t<>\n\t\t\t{items.map((item, idx) => {\n\t\t\t\tif (item.type === 'widget') {\n\t\t\t\t\tconst form = state.forms?.find((f) => f.id === item.formId);\n\t\t\t\t\tconst widget = form?.widgets.find((w) => w.id === item.widgetId);\n\n\t\t\t\t\tif (!form || !widget) {\n\t\t\t\t\t\ttriggerFallback();\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst WidgetComponent = widgets[widget.type];\n\n\t\t\t\t\tif (!WidgetComponent) {\n\t\t\t\t\t\ttriggerFallback();\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn <WidgetComponent key={`${form.id}.${widget.id}`} formId={form.id} config={widget} />;\n\t\t\t\t} else if (item.type === 'vertical' || item.type === 'horizontal') {\n\t\t\t\t\tconst LayoutComponent = widgets.layout;\n\n\t\t\t\t\tif (!LayoutComponent) {\n\t\t\t\t\t\ttriggerFallback();\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn (\n\t\t\t\t\t\t<LayoutComponent key={idx} formId={(item.items[0] as Widget).formId} type={item.type}>\n\t\t\t\t\t\t\t<StyWidgetRenderer items={item.items} widgets={widgets} state={state} triggerFallback={triggerFallback} />\n\t\t\t\t\t\t</LayoutComponent>\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\ttriggerFallback();\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t})}\n\t\t</>\n\t);\n};\n\nexport const StyLoginRenderer: React.FC<{\n\tparams?: NativeParams;\n\twidgets?: PartialRecord<WidgetType, React.ComponentType<any>>;\n\tsessionId?: string | null;\n\tonLogin?: (claims?: IdTokenClaims | null) => void;\n\tonFallback?: (error: FallbackError) => void;\n\tonError?: (error: any) => void;\n\tonGlobalMessage?: (message: string) => void;\n\tonBlockReady?: ({ previousState, state }: { previousState: LoginFlowState; state: LoginFlowState }) => void;\n}> = (props) => {\n\tconst { params, widgets, sessionId, onLogin, onFallback, onError, onGlobalMessage, onBlockReady } = {\n\t\tparams: {},\n\t\twidgets: {},\n\t\tsessionId: null,\n\t\t...props,\n\t};\n\tconst { sdk } = useStrivacity<NativeContext>();\n\tconst loginHandlerRef = useRef<ReturnType<(typeof sdk)['login']> | null>(null);\n\n\tconst [loading, setLoading] = useState(false);\n\tconst [forms, setforms] = useState<Record<string, Record<string, unknown>>>({});\n\tconst [messages, setmessages] = useState<Record<string, Record<string, LoginFlowMessage>>>({});\n\tconst [state, setState] = useState<LoginFlowState>({});\n\n\tconst triggerFallback = useCallback(\n\t\t(hostedUrl?: string) => {\n\t\t\tconst url = hostedUrl || state.hostedUrl;\n\n\t\t\tif (!url) {\n\t\t\t\tthrow new Error('No hosted URL provided');\n\t\t\t}\n\n\t\t\tonFallback?.(new FallbackError(new URL(url)));\n\t\t},\n\t\t[state, onFallback],\n\t);\n\n\tconst setFormValue = useCallback((formId: string, widgetId: string, value: unknown) => {\n\t\tsetforms((prev) => ({\n\t\t\t...prev,\n\t\t\t[formId]: { ...(prev[formId] || {}), [widgetId]: value === '' ? null : value },\n\t\t}));\n\t}, []);\n\n\tconst setMessage = useCallback((formId: string, widgetId: string, value: LoginFlowMessage) => {\n\t\tsetmessages((prev) => ({\n\t\t\t...prev,\n\t\t\t[formId]: { ...(prev[formId] || {}), [widgetId]: value },\n\t\t}));\n\t}, []);\n\n\tconst submitForm = useCallback(\n\t\tasync (formId: string) => {\n\t\t\ttry {\n\t\t\t\tsetLoading(true);\n\n\t\t\t\tconst data = await loginHandlerRef.current?.submitForm(formId, unflattenObject(forms[formId]));\n\n\t\t\t\tif (await sdk.isAuthenticated) {\n\t\t\t\t\tonLogin?.(sdk.idTokenClaims);\n\t\t\t\t} else {\n\t\t\t\t\tconst previousState = structuredClone(state);\n\t\t\t\t\tconst newState: LoginFlowState = {\n\t\t\t\t\t\thostedUrl: data?.hostedUrl ?? state.hostedUrl,\n\t\t\t\t\t\tfinalizeUrl: data?.finalizeUrl ?? state.finalizeUrl,\n\t\t\t\t\t\tscreen: data?.screen ?? state.screen,\n\t\t\t\t\t\tforms: data?.forms ?? state.forms,\n\t\t\t\t\t\tlayout: data?.layout ?? state.layout,\n\t\t\t\t\t\tmessages: data?.messages ?? state.messages,\n\t\t\t\t\t\tbranding: data?.branding ?? state.branding,\n\t\t\t\t\t};\n\n\t\t\t\t\tif (newState.screen !== state.screen) {\n\t\t\t\t\t\tconst newforms: typeof forms = {};\n\t\t\t\t\t\tconst newmessages: typeof messages = {};\n\n\t\t\t\t\t\tfor (const form of newState.forms ?? []) {\n\t\t\t\t\t\t\tnewforms[form.id] = {};\n\t\t\t\t\t\t\tnewmessages[form.id] = {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsetforms(newforms);\n\t\t\t\t\t\tsetmessages(newmessages);\n\t\t\t\t\t}\n\n\t\t\t\t\tObject.keys(newState.messages ?? {}).forEach((formId) => {\n\t\t\t\t\t\tif (formId === 'global') {\n\t\t\t\t\t\t\tonGlobalMessage?.(newState.messages?.global?.text ?? '');\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsetmessages((prev) => ({\n\t\t\t\t\t\t\t\t...prev,\n\t\t\t\t\t\t\t\t[formId]: newState.messages![formId],\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tsetState(newState);\n\t\t\t\t\tsetLoading(false);\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tonBlockReady?.({ previousState, state: structuredClone(newState) });\n\t\t\t\t\t}, 1);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\tconsole.error('Error submitting form:', error);\n\n\t\t\t\tif (error instanceof FallbackError) {\n\t\t\t\t\tonFallback?.(error);\n\t\t\t\t} else {\n\t\t\t\t\tonError?.(error);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t[sdk, params, forms, state, onLogin, onFallback, onError, onGlobalMessage, onBlockReady],\n\t);\n\n\t// Provide context value\n\tconst contextValue: NativeFlowContextValue = {\n\t\tloading,\n\t\tforms,\n\t\tmessages,\n\t\tstate,\n\t\tsubmitForm,\n\t\ttriggerFallback,\n\t\tsetFormValue,\n\t\tsetMessage,\n\t};\n\n\tuseEffect(() => {\n\t\tloginHandlerRef.current = sdk.login(params);\n\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tconst data = await loginHandlerRef.current?.startSession(sessionId);\n\t\t\t\tconst previousState = structuredClone(state);\n\t\t\t\tconst newState: LoginFlowState = {\n\t\t\t\t\thostedUrl: data?.hostedUrl ?? state.hostedUrl,\n\t\t\t\t\tfinalizeUrl: data?.finalizeUrl ?? state.finalizeUrl,\n\t\t\t\t\tscreen: data?.screen ?? state.screen,\n\t\t\t\t\tforms: data?.forms ?? state.forms,\n\t\t\t\t\tlayout: data?.layout ?? state.layout,\n\t\t\t\t\tmessages: data?.messages ?? state.messages,\n\t\t\t\t\tbranding: data?.branding ?? state.branding,\n\t\t\t\t};\n\n\t\t\t\tif (await sdk.isAuthenticated) {\n\t\t\t\t\tonLogin?.(sdk.idTokenClaims);\n\t\t\t\t} else {\n\t\t\t\t\tif (newState.screen !== state.screen) {\n\t\t\t\t\t\tconst newforms: typeof forms = {};\n\t\t\t\t\t\tconst newmessages: typeof messages = {};\n\n\t\t\t\t\t\tfor (const form of newState.forms ?? []) {\n\t\t\t\t\t\t\tnewforms[form.id] = {};\n\t\t\t\t\t\t\tnewmessages[form.id] = {};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsetforms(newforms);\n\t\t\t\t\t\tsetmessages(newmessages);\n\t\t\t\t\t}\n\n\t\t\t\t\tObject.keys(newState.messages ?? {}).forEach((formId) => {\n\t\t\t\t\t\tif (formId === 'global') {\n\t\t\t\t\t\t\tonGlobalMessage?.(newState.messages?.global?.text ?? '');\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsetmessages((prev) => ({\n\t\t\t\t\t\t\t\t...prev,\n\t\t\t\t\t\t\t\t[formId]: newState.messages![formId],\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tsetState(newState);\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tonBlockReady?.({ previousState, state: structuredClone(newState) });\n\t\t\t\t\t}, 1);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof FallbackError) {\n\t\t\t\t\tonFallback?.(error);\n\t\t\t\t} else {\n\t\t\t\t\tonError?.(error);\n\t\t\t\t}\n\t\t\t}\n\t\t})();\n\t}, []);\n\n\treturn (\n\t\t<NativeFlowContext.Provider value={contextValue}>\n\t\t\t<div className=\"login-renderer\">\n\t\t\t\t{state.screen && widgets.layout\n\t\t\t\t\t? React.createElement(\n\t\t\t\t\t\t\twidgets.layout,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tformId: (state.layout?.items?.[0] as Widget)?.formId,\n\t\t\t\t\t\t\t\ttype: state.layout?.type,\n\t\t\t\t\t\t\t\ttag: 'form',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t<StyWidgetRenderer items={state.layout?.items ?? []} widgets={widgets} state={state} triggerFallback={triggerFallback} />,\n\t\t\t\t\t\t)\n\t\t\t\t\t: widgets.loading\n\t\t\t\t\t\t? React.createElement(widgets.loading)\n\t\t\t\t\t\t: null}\n\t\t\t</div>\n\t\t</NativeFlowContext.Provider>\n\t);\n};\n"],"names":["NativeFlowContext","createContext","StyWidgetRenderer","items","widgets","state","triggerFallback","jsx","Fragment","item","idx","form","_a","f","widget","w","WidgetComponent","LayoutComponent","StyLoginRenderer","props","params","sessionId","onLogin","onFallback","onError","onGlobalMessage","onBlockReady","sdk","useStrivacity","loginHandlerRef","useRef","loading","setLoading","useState","forms","setforms","messages","setmessages","setState","useCallback","hostedUrl","url","FallbackError","setFormValue","formId","widgetId","value","prev","setMessage","submitForm","data","unflattenObject","previousState","newState","newforms","newmessages","_b","error","contextValue","useEffect","React","_c","_d","_e"],"mappings":"oUAQO,MAAMA,EAAoBC,EAA6C,IAAI,EAE5EC,EAKD,CAAC,CAAE,MAAAC,EAAO,QAAAC,EAAS,MAAAC,EAAO,gBAAAC,KAE7BC,EAAAC,EAAA,CACE,SAAAL,EAAM,IAAI,CAACM,EAAMC,IAAQ,OACzB,GAAID,EAAK,OAAS,SAAU,CAC3B,MAAME,GAAOC,EAAAP,EAAM,QAAN,YAAAO,EAAa,KAAMC,GAAMA,EAAE,KAAOJ,EAAK,QAC9CK,EAASH,GAAA,YAAAA,EAAM,QAAQ,KAAMI,GAAMA,EAAE,KAAON,EAAK,UAEvD,GAAI,CAACE,GAAQ,CAACG,EACb,OAAAR,EAAA,EACO,KAGR,MAAMU,EAAkBZ,EAAQU,EAAO,IAAI,EAE3C,OAAKE,EAKET,EAACS,EAAA,CAAgD,OAAQL,EAA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C,EAAsB,KAAtB,YAAAK,EAAqC,OAC9C,MAAMC,EAAAzD,EAAM,SAAN,YAAAyD,EAAc,KACpB,IAAK,MAAA,EAENvD,EAACL,EAAA,CAAkB,QAAO6D,EAAA1D,EAAM,SAAN,YAAA0D,EAAc,QAAS,GAAI,QAAA3D,EAAkB,MAAAC,EAAc,gBAAAC,CAAA,CAAkC,CAAA,EAEvHF,EAAQ,QACPwD,EAAM,cAAcxD,EAAQ,OAAO,EACnC,IAAA,CACL,EACD,CAEF"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react"),r=e.createContext(null),n=()=>{const t=e.useContext(r);if(!t)throw new Error("Missing Strivacity SDK context");return t};exports.STRIVACITY_SDK=r;exports.useStrivacity=n;
2
+ //# sourceMappingURL=composables.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"composables.cjs","sources":["../src/composables.tsx"],"sourcesContent":["import { createContext, useContext } from 'react';\nimport type { PopupContext, RedirectContext, NativeContext } from './types';\n\nexport const STRIVACITY_SDK = createContext<PopupContext | RedirectContext | NativeContext>(null!);\n\n/**\n * Hook to access the Strivacity SDK context\n *\n * @template T Extends either PopupContext, RedirectContext or NativeContext.\n *\n * @returns {T} The current Strivacity SDK context.\n *\n * @throws {Error} If the context is not provided by an AuthProvider.\n */\nexport const useStrivacity = <T extends PopupContext | RedirectContext | NativeContext>() => {\n\tconst context = useContext(STRIVACITY_SDK);\n\n\tif (!context) {\n\t\tthrow new Error('Missing Strivacity SDK context');\n\t}\n\n\treturn context as T;\n};\n"],"names":["STRIVACITY_SDK","createContext","useStrivacity","context","useContext"],"mappings":"yGAGaA,EAAiBC,EAAAA,cAA8D,IAAK,EAWpFC,EAAgB,IAAgE,CAC5F,MAAMC,EAAUC,EAAAA,WAAWJ,CAAc,EAEzC,GAAI,CAACG,EACJ,MAAM,IAAI,MAAM,gCAAgC,EAGjD,OAAOA,CACR"}
@@ -0,0 +1,12 @@
1
+ import { PopupContext, RedirectContext, NativeContext } from './types';
2
+ export declare const STRIVACITY_SDK: import('react').Context<PopupContext | RedirectContext | NativeContext>;
3
+ /**
4
+ * Hook to access the Strivacity SDK context
5
+ *
6
+ * @template T Extends either PopupContext, RedirectContext or NativeContext.
7
+ *
8
+ * @returns {T} The current Strivacity SDK context.
9
+ *
10
+ * @throws {Error} If the context is not provided by an AuthProvider.
11
+ */
12
+ export declare const useStrivacity: <T extends PopupContext | RedirectContext | NativeContext>() => T;
@@ -0,0 +1,2 @@
1
+ import{createContext as o,useContext as r}from"react";const e=o(null),c=()=>{const t=r(e);if(!t)throw new Error("Missing Strivacity SDK context");return t};export{e as STRIVACITY_SDK,c as useStrivacity};
2
+ //# sourceMappingURL=composables.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"composables.mjs","sources":["../src/composables.tsx"],"sourcesContent":["import { createContext, useContext } from 'react';\nimport type { PopupContext, RedirectContext, NativeContext } from './types';\n\nexport const STRIVACITY_SDK = createContext<PopupContext | RedirectContext | NativeContext>(null!);\n\n/**\n * Hook to access the Strivacity SDK context\n *\n * @template T Extends either PopupContext, RedirectContext or NativeContext.\n *\n * @returns {T} The current Strivacity SDK context.\n *\n * @throws {Error} If the context is not provided by an AuthProvider.\n */\nexport const useStrivacity = <T extends PopupContext | RedirectContext | NativeContext>() => {\n\tconst context = useContext(STRIVACITY_SDK);\n\n\tif (!context) {\n\t\tthrow new Error('Missing Strivacity SDK context');\n\t}\n\n\treturn context as T;\n};\n"],"names":["STRIVACITY_SDK","createContext","useStrivacity","context","useContext"],"mappings":"sDAGO,MAAMA,EAAiBC,EAA8D,IAAK,EAWpFC,EAAgB,IAAgE,CAC5F,MAAMC,EAAUC,EAAWJ,CAAc,EAEzC,GAAI,CAACG,EACJ,MAAM,IAAI,MAAM,gCAAgC,EAGjD,OAAOA,CACR"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("react/jsx-runtime"),s=require("react"),x=require("@strivacity/sdk-core"),p=require("@strivacity/sdk-core/storages/LocalStorage"),m=require("@strivacity/sdk-core/storages/SessionStorage"),k=s.createContext(null);let e;const A=()=>{const o=s.useContext(k);if(!o)throw Error("Missing Strivacity SDK context");return o},C=({options:o,children:S=void 0})=>{const[a,b]=s.useState(!0),[i,T]=s.useState(!1),[r,v]=s.useState(null),[c,g]=s.useState(null),[u,f]=s.useState(null),[l,E]=s.useState(!0),[d,h]=s.useState(null),t=async()=>{T(await e.isAuthenticated),v(e.idTokenClaims||null),g(e.accessToken||null),f(e.refreshToken||null),E(e.accessTokenExpired),h(e.accessTokenExpirationDate||null),a&&b(!1)},w=s.useMemo(()=>(e||(e=x.initFlow(o)),{loading:a,isAuthenticated:i,idTokenClaims:r,accessToken:c,refreshToken:u,accessTokenExpired:l,accessTokenExpirationDate:d,login:async n=>{await e.login(n),await t()},register:async n=>{await e.register(n),await t()},refresh:async()=>{await e.refresh(),await t()},revoke:async()=>{await e.revoke(),await t()},logout:async n=>{await e.logout(n),await t()},handleCallback:async n=>{await e.handleCallback(n),await t()}}),[a,r,c,u,l,d,i]);return s.useEffect(()=>{e&&(t(),e.subscribeToEvent("init",t),e.subscribeToEvent("loggedIn",t),e.subscribeToEvent("sessionLoaded",t),e.subscribeToEvent("tokenRefreshed",t),e.subscribeToEvent("tokenRefreshFailed",t),e.subscribeToEvent("logoutInitiated",t),e.subscribeToEvent("tokenRevoked",t),e.subscribeToEvent("tokenRevokeFailed",t))},[]),y.jsx(k.Provider,{value:w,children:S})};Object.defineProperty(exports,"LocalStorage",{enumerable:!0,get:()=>p.LocalStorage});Object.defineProperty(exports,"SessionStorage",{enumerable:!0,get:()=>m.SessionStorage});exports.AuthProvider=C;exports.useStrivacity=A;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("@strivacity/sdk-core"),o=require("@strivacity/sdk-core/utils/HttpClient"),i=require("@strivacity/sdk-core/storages/LocalStorage"),n=require("@strivacity/sdk-core/storages/SessionStorage"),u=require("./composables.cjs"),a=require("./AuthProvider.cjs"),r=require("./LoginRenderer.cjs");require("react");require("react/jsx-runtime");require("@strivacity/sdk-core/utils/object");Object.defineProperty(exports,"HttpClient",{enumerable:!0,get:()=>o.HttpClient});Object.defineProperty(exports,"LocalStorage",{enumerable:!0,get:()=>i.LocalStorage});Object.defineProperty(exports,"SessionStorage",{enumerable:!0,get:()=>n.SessionStorage});exports.useStrivacity=u.useStrivacity;exports.StyAuthProvider=a.StyAuthProvider;exports.NativeFlowContext=r.NativeFlowContext;exports.StyLoginRenderer=r.StyLoginRenderer;Object.keys(t).forEach(e=>{e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:()=>t[e]})});
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/index.tsx"],"sourcesContent":["import { type FC, createContext, useContext, useMemo, useEffect, useState } from 'react';\nimport { initFlow, type SDKOptions, type SDKStorage, type IdTokenClaims } from '@strivacity/sdk-core';\nimport type { PopupFlow } from '@strivacity/sdk-core/flows/PopupFlow';\nimport type { RedirectFlow } from '@strivacity/sdk-core/flows/RedirectFlow';\nimport { LocalStorage } from '@strivacity/sdk-core/storages/LocalStorage';\nimport { SessionStorage } from '@strivacity/sdk-core/storages/SessionStorage';\nimport type { Session, PopupContext, PopupSDK, RedirectContext, RedirectSDK, Children } from './types';\n\nexport type { SDKOptions, SDKStorage, Session, IdTokenClaims, PopupFlow, RedirectFlow, PopupContext, PopupSDK, RedirectContext, RedirectSDK };\nexport { LocalStorage, SessionStorage };\n\nconst StrivacitySdk = createContext<PopupContext | RedirectContext>(null!);\n\nlet sdk: RedirectFlow | PopupFlow;\n\n/**\n * Hook to access the Strivacity SDK context\n *\n * @template T Extends either PopupContext or RedirectContext.\n *\n * @returns {T} The current Strivacity SDK context.\n *\n * @throws {Error} If the context is not provided by an AuthProvider.\n */\nexport const useStrivacity = <T extends PopupContext | RedirectContext>() => {\n\tconst context = useContext(StrivacitySdk);\n\n\tif (!context) {\n\t\tthrow Error('Missing Strivacity SDK context');\n\t}\n\n\treturn context as T;\n};\n\n/**\n * Strivacity authentication provider component\n *\n * @param {SDKOptions} options - The SDK configuration options.\n * @param {Children} [children] - The child components wrapped by the provider.\n *\n * @returns {JSX.Element} A provider that passes the Strivacity SDK context to its children.\n */\nexport const AuthProvider: FC<{ options: SDKOptions; children?: Children }> = ({\n\toptions,\n\tchildren = undefined,\n}: {\n\toptions: SDKOptions;\n\tchildren?: Children;\n}) => {\n\tconst [loading, setLoading] = useState<boolean>(true);\n\tconst [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);\n\tconst [idTokenClaims, setIdTokenClaims] = useState<IdTokenClaims | null>(null);\n\tconst [accessToken, setAccessToken] = useState<string | null>(null);\n\tconst [refreshToken, setRefreshToken] = useState<string | null>(null);\n\tconst [accessTokenExpired, setAccessTokenExpired] = useState<boolean>(true);\n\tconst [accessTokenExpirationDate, setAccessTokenExpirationDate] = useState<number | null>(null);\n\n\tconst updateSession = async () => {\n\t\tsetIsAuthenticated(await sdk.isAuthenticated);\n\t\tsetIdTokenClaims(sdk.idTokenClaims || null);\n\t\tsetAccessToken(sdk.accessToken || null);\n\t\tsetRefreshToken(sdk.refreshToken || null);\n\t\tsetAccessTokenExpired(sdk.accessTokenExpired);\n\t\tsetAccessTokenExpirationDate(sdk.accessTokenExpirationDate || null);\n\n\t\tif (loading) {\n\t\t\tsetLoading(false);\n\t\t}\n\t};\n\n\tconst value = useMemo<PopupContext | RedirectContext>(() => {\n\t\tif (!sdk) {\n\t\t\tsdk = initFlow(options);\n\t\t}\n\n\t\treturn {\n\t\t\tloading,\n\t\t\tisAuthenticated,\n\t\t\tidTokenClaims,\n\t\t\taccessToken,\n\t\t\trefreshToken,\n\t\t\taccessTokenExpired,\n\t\t\taccessTokenExpirationDate,\n\n\t\t\tlogin: async (options?: Parameters<PopupFlow['login'] | RedirectFlow['login']>[0]) => {\n\t\t\t\tawait sdk.login(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\tregister: async (options?: Parameters<PopupFlow['register'] | RedirectFlow['register']>[0]) => {\n\t\t\t\tawait sdk.register(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\trefresh: async () => {\n\t\t\t\tawait sdk.refresh();\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\trevoke: async () => {\n\t\t\t\tawait sdk.revoke();\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\tlogout: async (options?: Parameters<PopupFlow['logout'] | RedirectFlow['logout']>[0]) => {\n\t\t\t\tawait sdk.logout(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\thandleCallback: async (url?: Parameters<PopupFlow['handleCallback'] | RedirectFlow['handleCallback']>[0]) => {\n\t\t\t\tawait sdk.handleCallback(url);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t};\n\t}, [loading, idTokenClaims, accessToken, refreshToken, accessTokenExpired, accessTokenExpirationDate, isAuthenticated]);\n\n\tuseEffect(() => {\n\t\tif (!sdk) {\n\t\t\treturn;\n\t\t}\n\n\t\tvoid updateSession();\n\n\t\tsdk.subscribeToEvent('init', updateSession);\n\t\tsdk.subscribeToEvent('loggedIn', updateSession);\n\t\tsdk.subscribeToEvent('sessionLoaded', updateSession);\n\t\tsdk.subscribeToEvent('tokenRefreshed', updateSession);\n\t\tsdk.subscribeToEvent('tokenRefreshFailed', updateSession);\n\t\tsdk.subscribeToEvent('logoutInitiated', updateSession);\n\t\tsdk.subscribeToEvent('tokenRevoked', updateSession);\n\t\tsdk.subscribeToEvent('tokenRevokeFailed', updateSession);\n\t}, []);\n\n\treturn <StrivacitySdk.Provider value={value}>{children}</StrivacitySdk.Provider>;\n};\n"],"names":["StrivacitySdk","createContext","sdk","useStrivacity","context","useContext","AuthProvider","options","children","loading","setLoading","useState","isAuthenticated","setIsAuthenticated","idTokenClaims","setIdTokenClaims","accessToken","setAccessToken","refreshToken","setRefreshToken","accessTokenExpired","setAccessTokenExpired","accessTokenExpirationDate","setAccessTokenExpirationDate","updateSession","value","useMemo","initFlow","url","useEffect","jsx"],"mappings":"4RAWMA,EAAgBC,EAAAA,cAA8C,IAAK,EAEzE,IAAIC,EAWG,MAAMC,EAAgB,IAAgD,CACtE,MAAAC,EAAUC,aAAWL,CAAa,EAExC,GAAI,CAACI,EACJ,MAAM,MAAM,gCAAgC,EAGtC,OAAAA,CACR,EAUaE,EAAiE,CAAC,CAC9E,QAAAC,EACA,SAAAC,EAAW,MACZ,IAGM,CACL,KAAM,CAACC,EAASC,CAAU,EAAIC,WAAkB,EAAI,EAC9C,CAACC,EAAiBC,CAAkB,EAAIF,WAAkB,EAAK,EAC/D,CAACG,EAAeC,CAAgB,EAAIJ,WAA+B,IAAI,EACvE,CAACK,EAAaC,CAAc,EAAIN,WAAwB,IAAI,EAC5D,CAACO,EAAcC,CAAe,EAAIR,WAAwB,IAAI,EAC9D,CAACS,EAAoBC,CAAqB,EAAIV,WAAkB,EAAI,EACpE,CAACW,EAA2BC,CAA4B,EAAIZ,WAAwB,IAAI,EAExFa,EAAgB,SAAY,CACdX,EAAA,MAAMX,EAAI,eAAe,EAC3Ba,EAAAb,EAAI,eAAiB,IAAI,EAC3Be,EAAAf,EAAI,aAAe,IAAI,EACtBiB,EAAAjB,EAAI,cAAgB,IAAI,EACxCmB,EAAsBnB,EAAI,kBAAkB,EACfqB,EAAArB,EAAI,2BAA6B,IAAI,EAE9DO,GACHC,EAAW,EAAK,CACjB,EAGKe,EAAQC,EAAAA,QAAwC,KAChDxB,IACJA,EAAMyB,EAAAA,SAASpB,CAAO,GAGhB,CACN,QAAAE,EACA,gBAAAG,EACA,cAAAE,EACA,YAAAE,EACA,aAAAE,EACA,mBAAAE,EACA,0BAAAE,EAEA,MAAO,MAAOf,GAAwE,CAC/E,MAAAL,EAAI,MAAMK,CAAO,EACvB,MAAMiB,EAAc,CACrB,EACA,SAAU,MAAOjB,GAA8E,CACxF,MAAAL,EAAI,SAASK,CAAO,EAC1B,MAAMiB,EAAc,CACrB,EACA,QAAS,SAAY,CACpB,MAAMtB,EAAI,UACV,MAAMsB,EAAc,CACrB,EACA,OAAQ,SAAY,CACnB,MAAMtB,EAAI,SACV,MAAMsB,EAAc,CACrB,EACA,OAAQ,MAAOjB,GAA0E,CAClF,MAAAL,EAAI,OAAOK,CAAO,EACxB,MAAMiB,EAAc,CACrB,EACA,eAAgB,MAAOI,GAAsF,CACtG,MAAA1B,EAAI,eAAe0B,CAAG,EAC5B,MAAMJ,EAAc,CACrB,CAAA,GAEC,CAACf,EAASK,EAAeE,EAAaE,EAAcE,EAAoBE,EAA2BV,CAAe,CAAC,EAEtHiB,OAAAA,EAAAA,UAAU,IAAM,CACV3B,IAIAsB,EAAc,EAEftB,EAAA,iBAAiB,OAAQsB,CAAa,EACtCtB,EAAA,iBAAiB,WAAYsB,CAAa,EAC1CtB,EAAA,iBAAiB,gBAAiBsB,CAAa,EAC/CtB,EAAA,iBAAiB,iBAAkBsB,CAAa,EAChDtB,EAAA,iBAAiB,qBAAsBsB,CAAa,EACpDtB,EAAA,iBAAiB,kBAAmBsB,CAAa,EACjDtB,EAAA,iBAAiB,eAAgBsB,CAAa,EAC9CtB,EAAA,iBAAiB,oBAAqBsB,CAAa,EACxD,EAAG,CAAE,CAAA,EAEGM,EAAAA,IAAA9B,EAAc,SAAd,CAAuB,MAAAyB,EAAe,SAAAjB,CAAS,CAAA,CACxD"}
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":""}
package/dist/index.d.ts CHANGED
@@ -1,31 +1,13 @@
1
- import { FC } from 'react';
2
- import { SDKOptions, SDKStorage, IdTokenClaims } from '@strivacity/sdk-core';
3
- import { PopupFlow } from '@strivacity/sdk-core/flows/PopupFlow';
4
- import { RedirectFlow } from '@strivacity/sdk-core/flows/RedirectFlow';
5
- import { LocalStorage } from '@strivacity/sdk-core/storages/LocalStorage';
6
- import { SessionStorage } from '@strivacity/sdk-core/storages/SessionStorage';
7
- import { Session, PopupContext, PopupSDK, RedirectContext, RedirectSDK, Children } from './types';
8
- export type { SDKOptions, SDKStorage, Session, IdTokenClaims, PopupFlow, RedirectFlow, PopupContext, PopupSDK, RedirectContext, RedirectSDK };
9
- export { LocalStorage, SessionStorage };
10
- /**
11
- * Hook to access the Strivacity SDK context
12
- *
13
- * @template T Extends either PopupContext or RedirectContext.
14
- *
15
- * @returns {T} The current Strivacity SDK context.
16
- *
17
- * @throws {Error} If the context is not provided by an AuthProvider.
18
- */
19
- export declare const useStrivacity: <T extends PopupContext | RedirectContext>() => T;
20
- /**
21
- * Strivacity authentication provider component
22
- *
23
- * @param {SDKOptions} options - The SDK configuration options.
24
- * @param {Children} [children] - The child components wrapped by the provider.
25
- *
26
- * @returns {JSX.Element} A provider that passes the Strivacity SDK context to its children.
27
- */
28
- export declare const AuthProvider: FC<{
29
- options: SDKOptions;
30
- children?: Children;
31
- }>;
1
+ export * from '@strivacity/sdk-core';
2
+ export type * from './types';
3
+ export type { PopupFlow } from '@strivacity/sdk-core/flows/PopupFlow';
4
+ export type { RedirectFlow } from '@strivacity/sdk-core/flows/RedirectFlow';
5
+ export type { NativeFlow } from '@strivacity/sdk-core/flows/NativeFlow';
6
+ export { HttpClient } from '@strivacity/sdk-core/utils/HttpClient';
7
+ export { LocalStorage } from '@strivacity/sdk-core/storages/LocalStorage';
8
+ export { SessionStorage } from '@strivacity/sdk-core/storages/SessionStorage';
9
+ export { useStrivacity } from './composables';
10
+ export { StyAuthProvider } from './AuthProvider';
11
+ export { StyLoginRenderer, NativeFlowContext } from './LoginRenderer';
12
+ export * from '@strivacity/sdk-core';
13
+ export type * from './types';
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{jsx as p}from"react/jsx-runtime";import{createContext as m,useContext as y,useState as o,useMemo as S,useEffect as A}from"react";import{initFlow as C}from"@strivacity/sdk-core";import{LocalStorage as j}from"@strivacity/sdk-core/storages/LocalStorage";import{SessionStorage as q}from"@strivacity/sdk-core/storages/SessionStorage";const k=m(null);let e;const F=()=>{const n=y(k);if(!n)throw Error("Missing Strivacity SDK context");return n},L=({options:n,children:T=void 0})=>{const[i,f]=o(!0),[a,v]=o(!1),[r,b]=o(null),[c,E]=o(null),[l,w]=o(null),[u,g]=o(!0),[d,h]=o(null),t=async()=>{v(await e.isAuthenticated),b(e.idTokenClaims||null),E(e.accessToken||null),w(e.refreshToken||null),g(e.accessTokenExpired),h(e.accessTokenExpirationDate||null),i&&f(!1)},x=S(()=>(e||(e=C(n)),{loading:i,isAuthenticated:a,idTokenClaims:r,accessToken:c,refreshToken:l,accessTokenExpired:u,accessTokenExpirationDate:d,login:async s=>{await e.login(s),await t()},register:async s=>{await e.register(s),await t()},refresh:async()=>{await e.refresh(),await t()},revoke:async()=>{await e.revoke(),await t()},logout:async s=>{await e.logout(s),await t()},handleCallback:async s=>{await e.handleCallback(s),await t()}}),[i,r,c,l,u,d,a]);return A(()=>{e&&(t(),e.subscribeToEvent("init",t),e.subscribeToEvent("loggedIn",t),e.subscribeToEvent("sessionLoaded",t),e.subscribeToEvent("tokenRefreshed",t),e.subscribeToEvent("tokenRefreshFailed",t),e.subscribeToEvent("logoutInitiated",t),e.subscribeToEvent("tokenRevoked",t),e.subscribeToEvent("tokenRevokeFailed",t))},[]),p(k.Provider,{value:x,children:T})};export{L as AuthProvider,j as LocalStorage,q as SessionStorage,F as useStrivacity};
1
+ export*from"@strivacity/sdk-core";import{HttpClient as m}from"@strivacity/sdk-core/utils/HttpClient";import{LocalStorage as f}from"@strivacity/sdk-core/storages/LocalStorage";import{SessionStorage as a}from"@strivacity/sdk-core/storages/SessionStorage";import{useStrivacity as g}from"./composables.mjs";import{StyAuthProvider as s}from"./AuthProvider.mjs";import{NativeFlowContext as y,StyLoginRenderer as c}from"./LoginRenderer.mjs";import"react";import"react/jsx-runtime";import"@strivacity/sdk-core/utils/object";export{m as HttpClient,f as LocalStorage,y as NativeFlowContext,a as SessionStorage,s as StyAuthProvider,c as StyLoginRenderer,g as useStrivacity};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/index.tsx"],"sourcesContent":["import { type FC, createContext, useContext, useMemo, useEffect, useState } from 'react';\nimport { initFlow, type SDKOptions, type SDKStorage, type IdTokenClaims } from '@strivacity/sdk-core';\nimport type { PopupFlow } from '@strivacity/sdk-core/flows/PopupFlow';\nimport type { RedirectFlow } from '@strivacity/sdk-core/flows/RedirectFlow';\nimport { LocalStorage } from '@strivacity/sdk-core/storages/LocalStorage';\nimport { SessionStorage } from '@strivacity/sdk-core/storages/SessionStorage';\nimport type { Session, PopupContext, PopupSDK, RedirectContext, RedirectSDK, Children } from './types';\n\nexport type { SDKOptions, SDKStorage, Session, IdTokenClaims, PopupFlow, RedirectFlow, PopupContext, PopupSDK, RedirectContext, RedirectSDK };\nexport { LocalStorage, SessionStorage };\n\nconst StrivacitySdk = createContext<PopupContext | RedirectContext>(null!);\n\nlet sdk: RedirectFlow | PopupFlow;\n\n/**\n * Hook to access the Strivacity SDK context\n *\n * @template T Extends either PopupContext or RedirectContext.\n *\n * @returns {T} The current Strivacity SDK context.\n *\n * @throws {Error} If the context is not provided by an AuthProvider.\n */\nexport const useStrivacity = <T extends PopupContext | RedirectContext>() => {\n\tconst context = useContext(StrivacitySdk);\n\n\tif (!context) {\n\t\tthrow Error('Missing Strivacity SDK context');\n\t}\n\n\treturn context as T;\n};\n\n/**\n * Strivacity authentication provider component\n *\n * @param {SDKOptions} options - The SDK configuration options.\n * @param {Children} [children] - The child components wrapped by the provider.\n *\n * @returns {JSX.Element} A provider that passes the Strivacity SDK context to its children.\n */\nexport const AuthProvider: FC<{ options: SDKOptions; children?: Children }> = ({\n\toptions,\n\tchildren = undefined,\n}: {\n\toptions: SDKOptions;\n\tchildren?: Children;\n}) => {\n\tconst [loading, setLoading] = useState<boolean>(true);\n\tconst [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);\n\tconst [idTokenClaims, setIdTokenClaims] = useState<IdTokenClaims | null>(null);\n\tconst [accessToken, setAccessToken] = useState<string | null>(null);\n\tconst [refreshToken, setRefreshToken] = useState<string | null>(null);\n\tconst [accessTokenExpired, setAccessTokenExpired] = useState<boolean>(true);\n\tconst [accessTokenExpirationDate, setAccessTokenExpirationDate] = useState<number | null>(null);\n\n\tconst updateSession = async () => {\n\t\tsetIsAuthenticated(await sdk.isAuthenticated);\n\t\tsetIdTokenClaims(sdk.idTokenClaims || null);\n\t\tsetAccessToken(sdk.accessToken || null);\n\t\tsetRefreshToken(sdk.refreshToken || null);\n\t\tsetAccessTokenExpired(sdk.accessTokenExpired);\n\t\tsetAccessTokenExpirationDate(sdk.accessTokenExpirationDate || null);\n\n\t\tif (loading) {\n\t\t\tsetLoading(false);\n\t\t}\n\t};\n\n\tconst value = useMemo<PopupContext | RedirectContext>(() => {\n\t\tif (!sdk) {\n\t\t\tsdk = initFlow(options);\n\t\t}\n\n\t\treturn {\n\t\t\tloading,\n\t\t\tisAuthenticated,\n\t\t\tidTokenClaims,\n\t\t\taccessToken,\n\t\t\trefreshToken,\n\t\t\taccessTokenExpired,\n\t\t\taccessTokenExpirationDate,\n\n\t\t\tlogin: async (options?: Parameters<PopupFlow['login'] | RedirectFlow['login']>[0]) => {\n\t\t\t\tawait sdk.login(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\tregister: async (options?: Parameters<PopupFlow['register'] | RedirectFlow['register']>[0]) => {\n\t\t\t\tawait sdk.register(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\trefresh: async () => {\n\t\t\t\tawait sdk.refresh();\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\trevoke: async () => {\n\t\t\t\tawait sdk.revoke();\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\tlogout: async (options?: Parameters<PopupFlow['logout'] | RedirectFlow['logout']>[0]) => {\n\t\t\t\tawait sdk.logout(options);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t\thandleCallback: async (url?: Parameters<PopupFlow['handleCallback'] | RedirectFlow['handleCallback']>[0]) => {\n\t\t\t\tawait sdk.handleCallback(url);\n\t\t\t\tawait updateSession();\n\t\t\t},\n\t\t};\n\t}, [loading, idTokenClaims, accessToken, refreshToken, accessTokenExpired, accessTokenExpirationDate, isAuthenticated]);\n\n\tuseEffect(() => {\n\t\tif (!sdk) {\n\t\t\treturn;\n\t\t}\n\n\t\tvoid updateSession();\n\n\t\tsdk.subscribeToEvent('init', updateSession);\n\t\tsdk.subscribeToEvent('loggedIn', updateSession);\n\t\tsdk.subscribeToEvent('sessionLoaded', updateSession);\n\t\tsdk.subscribeToEvent('tokenRefreshed', updateSession);\n\t\tsdk.subscribeToEvent('tokenRefreshFailed', updateSession);\n\t\tsdk.subscribeToEvent('logoutInitiated', updateSession);\n\t\tsdk.subscribeToEvent('tokenRevoked', updateSession);\n\t\tsdk.subscribeToEvent('tokenRevokeFailed', updateSession);\n\t}, []);\n\n\treturn <StrivacitySdk.Provider value={value}>{children}</StrivacitySdk.Provider>;\n};\n"],"names":["StrivacitySdk","createContext","sdk","useStrivacity","context","useContext","AuthProvider","options","children","loading","setLoading","useState","isAuthenticated","setIsAuthenticated","idTokenClaims","setIdTokenClaims","accessToken","setAccessToken","refreshToken","setRefreshToken","accessTokenExpired","setAccessTokenExpired","accessTokenExpirationDate","setAccessTokenExpirationDate","updateSession","value","useMemo","initFlow","url","useEffect","jsx"],"mappings":"gVAWA,MAAMA,EAAgBC,EAA8C,IAAK,EAEzE,IAAIC,EAWG,MAAMC,EAAgB,IAAgD,CACtE,MAAAC,EAAUC,EAAWL,CAAa,EAExC,GAAI,CAACI,EACJ,MAAM,MAAM,gCAAgC,EAGtC,OAAAA,CACR,EAUaE,EAAiE,CAAC,CAC9E,QAAAC,EACA,SAAAC,EAAW,MACZ,IAGM,CACL,KAAM,CAACC,EAAS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E,EAAaE,EAAcE,EAAoBE,EAA2BV,CAAe,CAAC,EAEtH,OAAAiB,EAAU,IAAM,CACV3B,IAIAsB,EAAc,EAEftB,EAAA,iBAAiB,OAAQsB,CAAa,EACtCtB,EAAA,iBAAiB,WAAYsB,CAAa,EAC1CtB,EAAA,iBAAiB,gBAAiBsB,CAAa,EAC/CtB,EAAA,iBAAiB,iBAAkBsB,CAAa,EAChDtB,EAAA,iBAAiB,qBAAsBsB,CAAa,EACpDtB,EAAA,iBAAiB,kBAAmBsB,CAAa,EACjDtB,EAAA,iBAAiB,eAAgBsB,CAAa,EAC9CtB,EAAA,iBAAiB,oBAAqBsB,CAAa,EACxD,EAAG,CAAE,CAAA,EAEGM,EAAA9B,EAAc,SAAd,CAAuB,MAAAyB,EAAe,SAAAjB,CAAS,CAAA,CACxD"}
1
+ {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":""}
package/dist/types.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { IdTokenClaims } from '@strivacity/sdk-core';
1
+ import { IdTokenClaims, LoginFlowMessage, LoginFlowState, SDKOptions } from '@strivacity/sdk-core';
2
2
  import { PopupFlow } from '@strivacity/sdk-core/flows/PopupFlow';
3
3
  import { RedirectFlow } from '@strivacity/sdk-core/flows/RedirectFlow';
4
+ import { NativeFlow } from '@strivacity/sdk-core/flows/NativeFlow';
4
5
  export type Children = React.ReactElement | React.ReactNode | Array<React.ReactElement | React.ReactNode>;
5
6
  /**
6
7
  * Represents the session state, including authentication details and token information.
@@ -10,6 +11,10 @@ export type Session = {
10
11
  * Indicates if the session is being loaded.
11
12
  */
12
13
  loading: boolean;
14
+ /**
15
+ * The SDK options used to configure the session.
16
+ */
17
+ options: SDKOptions;
13
18
  /**
14
19
  * Indicates whether the user is authenticated.
15
20
  */
@@ -40,27 +45,31 @@ export type Session = {
40
45
  */
41
46
  export type PopupSDK = {
42
47
  /**
43
- * Initiates the login process using a popup window.
48
+ * Represents the SDK instance.
49
+ */
50
+ sdk: InstanceType<typeof PopupFlow>;
51
+ /**
52
+ * Initiates the login process.
44
53
  */
45
54
  login: InstanceType<typeof PopupFlow>['login'];
46
55
  /**
47
- * Registers a new user using a popup flow.
56
+ * Registers a new user.
48
57
  */
49
58
  register: InstanceType<typeof PopupFlow>['register'];
50
59
  /**
51
- * Refreshes the user's session using a popup.
60
+ * Refreshes the user's session.
52
61
  */
53
62
  refresh: InstanceType<typeof PopupFlow>['refresh'];
54
63
  /**
55
- * Revokes the current session tokens using a popup flow.
64
+ * Revokes the current session tokens.
56
65
  */
57
66
  revoke: InstanceType<typeof PopupFlow>['revoke'];
58
67
  /**
59
- * Logs out the user using a popup window.
68
+ * Logs out the user.
60
69
  */
61
70
  logout: InstanceType<typeof PopupFlow>['logout'];
62
71
  /**
63
- * Handles the callback after a popup-based authentication or token exchange.
72
+ * Handles the callback after authentication or token exchange.
64
73
  */
65
74
  handleCallback: InstanceType<typeof PopupFlow>['handleCallback'];
66
75
  };
@@ -69,30 +78,67 @@ export type PopupSDK = {
69
78
  */
70
79
  export type RedirectSDK = {
71
80
  /**
72
- * Initiates the login process by redirecting the user to the identity provider.
81
+ * Represents the SDK instance.
82
+ */
83
+ sdk: InstanceType<typeof RedirectFlow>;
84
+ /**
85
+ * Initiates the login process.
73
86
  */
74
87
  login: InstanceType<typeof RedirectFlow>['login'];
75
88
  /**
76
- * Registers a new user using a redirect flow.
89
+ * Registers a new user.
77
90
  */
78
91
  register: InstanceType<typeof RedirectFlow>['register'];
79
92
  /**
80
- * Refreshes the user's session using a redirect flow.
93
+ * Refreshes the user's session.
81
94
  */
82
95
  refresh: InstanceType<typeof RedirectFlow>['refresh'];
83
96
  /**
84
- * Revokes the current session tokens using a redirect flow.
97
+ * Revokes the current session tokens.
85
98
  */
86
99
  revoke: InstanceType<typeof RedirectFlow>['revoke'];
87
100
  /**
88
- * Logs out the user by redirecting to the logout page.
101
+ * Logs out the user.
89
102
  */
90
103
  logout: InstanceType<typeof RedirectFlow>['logout'];
91
104
  /**
92
- * Handles the callback after a redirect-based authentication or token exchange.
105
+ * Handles the callback after authentication or token exchange.
93
106
  */
94
107
  handleCallback: InstanceType<typeof RedirectFlow>['handleCallback'];
95
108
  };
109
+ /**
110
+ * Represents the available authentication flows and operations for Native-based interactions.
111
+ */
112
+ export type NativeSDK = {
113
+ /**
114
+ * Represents the SDK instance.
115
+ */
116
+ sdk: InstanceType<typeof NativeFlow>;
117
+ /**
118
+ * Initiates the login process.
119
+ */
120
+ login: InstanceType<typeof NativeFlow>['login'];
121
+ /**
122
+ * Registers a new user.
123
+ */
124
+ register: InstanceType<typeof NativeFlow>['register'];
125
+ /**
126
+ * Refreshes the user's session.
127
+ */
128
+ refresh: InstanceType<typeof NativeFlow>['refresh'];
129
+ /**
130
+ * Revokes the current session tokens.
131
+ */
132
+ revoke: InstanceType<typeof NativeFlow>['revoke'];
133
+ /**
134
+ * Logs out the user.
135
+ */
136
+ logout: InstanceType<typeof NativeFlow>['logout'];
137
+ /**
138
+ * Handles the callback after authentication or token exchange.
139
+ */
140
+ handleCallback: InstanceType<typeof NativeFlow>['handleCallback'];
141
+ };
96
142
  /**
97
143
  * Represents a combined context for Popup-based flows, containing both the Popup SDK and the session state.
98
144
  */
@@ -101,3 +147,17 @@ export type PopupContext = PopupSDK & Session;
101
147
  * Represents a combined context for Redirect-based flows, containing both the Redirect SDK and the session state.
102
148
  */
103
149
  export type RedirectContext = RedirectSDK & Session;
150
+ /**
151
+ * Represents a combined context for Native-based flows, containing both the Native SDK and the session state.
152
+ */
153
+ export type NativeContext = NativeSDK & Session;
154
+ export type NativeFlowContextValue = {
155
+ loading: boolean;
156
+ forms: Record<string, Record<string, unknown>>;
157
+ messages: Record<string, Record<string, LoginFlowMessage>>;
158
+ state: Partial<LoginFlowState>;
159
+ submitForm: (formId: string) => Promise<void>;
160
+ triggerFallback: (hostedUrl?: string) => void;
161
+ setFormValue: (formId: string, widgetId: string, value: unknown) => void;
162
+ setMessage: (formId: string, widgetId: string, value: LoginFlowMessage) => void;
163
+ };
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@strivacity/sdk-next",
3
- "version": "1.0.1",
3
+ "version": "2.0.0-beta",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Strivacity Next.js SDK client",
7
7
  "author": "strivacity <info@strivacity.com>",
8
8
  "dependencies": {
9
- "@strivacity/sdk-core": "1.0.1"
9
+ "@strivacity/sdk-core": "2.0.0-beta"
10
10
  },
11
11
  "peerDependencies": {
12
12
  "next": ">=13"