@descope/react-sdk 1.0.9 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,9 +17,7 @@ npm i --save @descope/react-sdk
17
17
 
18
18
  ## Usage
19
19
 
20
- ### Render it in your application
21
-
22
- #### Wrap your app with Auth Provider
20
+ ### Wrap your app with Auth Provider
23
21
 
24
22
  ```js
25
23
  import { AuthProvider } from '@descope/react-sdk';
@@ -39,11 +37,11 @@ const AppRoot = () => {
39
37
  };
40
38
  ```
41
39
 
42
- #### Use Descope to render specific flow
40
+ ### Use Descope to render specific flow
43
41
 
44
42
  You can use **default flows** or **provide flow id** directly to the Descope component
45
43
 
46
- ##### 1. Default flows
44
+ #### 1. Default flows
47
45
 
48
46
  ```js
49
47
  import { SignInFlow } from '@descope/react-sdk'
@@ -62,7 +60,7 @@ const App = () => {
62
60
  }
63
61
  ```
64
62
 
65
- ##### 2. Provide flow id
63
+ #### 2. Provide flow id
66
64
 
67
65
  ```js
68
66
  import { Descope } from '@descope/react-sdk'
@@ -77,6 +75,9 @@ const App = () => {
77
75
  // theme can be "light", "dark" or "os", which auto select a theme based on the OS theme. Default is "light"
78
76
  // theme="dark"
79
77
 
78
+ // locale can be any supported locale which the flow's screen translated to, if not provided, the locale is taken from the browser's locale.
79
+ // locale="en"
80
+
80
81
  // debug can be set to true to enable debug mode
81
82
  // debug={true}
82
83
 
@@ -91,12 +92,47 @@ const App = () => {
91
92
  // - false: do not automatically focus on screen's inputs
92
93
  // - "skipFirstScreen": automatically focus on the first input of each screen, except first screen
93
94
  // autoFocus="skipFirstScreen"
95
+
96
+ // errorTransformer is a function that receives an error object and returns a string. The returned string will be displayed to the user.
97
+ // NOTE: errorTransformer is not required. If not provided, the error object will be displayed as is.
98
+ // Example:
99
+ // const errorTransformer = useCallback(
100
+ // (error: { text: string; type: string }) => {
101
+ // const translationMap = {
102
+ // SAMLStartFailed: 'Failed to start SAML flow'
103
+ // };
104
+ // return translationMap[error.type] || error.text;
105
+ // },
106
+ // []
107
+ // );
108
+ // ...
109
+ // errorTransformer={errorTransformer}
110
+ // ...
111
+
112
+
113
+ // logger is an object describing how to log info, warn and errors.
114
+ // NOTE: logger is not required. If not provided, the logs will be printed to the console.
115
+ // Example:
116
+ // const logger = {
117
+ // info: (title: string, description: string, state: any) => {
118
+ // console.log(title, description, JSON.stringify(state));
119
+ // },
120
+ // warn: (title: string, description: string) => {
121
+ // console.warn(title);
122
+ // },
123
+ // error: (title: string, description: string) => {
124
+ // console.error('OH NOO');
125
+ // },
126
+ // }
127
+ // ...
128
+ // logger={logger}
129
+ // ...
94
130
  />
95
131
  )
96
132
  }
97
133
  ```
98
134
 
99
- #### Use the `useDescope`, `useSession` and `useUser` hooks in your components in order to get authentication state, user details and utilities
135
+ ### Use the `useDescope`, `useSession` and `useUser` hooks in your components in order to get authentication state, user details and utilities
100
136
 
101
137
  This can be helpful to implement application-specific logic. Examples:
102
138
 
@@ -147,7 +183,7 @@ useEffect(() => {
147
183
 
148
184
  **For more SDK usage examples refer to [docs](https://docs.descope.com/build/guides/client_sdks/)**
149
185
 
150
- #### Session token server validation (pass session token to server API)
186
+ ### Session token server validation (pass session token to server API)
151
187
 
152
188
  When developing a full-stack application, it is common to have private server API which requires a valid session token:
153
189
 
@@ -160,7 +196,7 @@ There are 2 ways to achieve that:
160
196
  1. Using `getSessionToken` to get the token, and pass it on the `Authorization` Header (Recommended)
161
197
  2. Passing `sessionTokenViaCookie` boolean prop to the `AuthProvider` component (Use cautiously, session token may grow, especially in cases of using authorization, or adding custom claim)
162
198
 
163
- ##### 1. Using `getSessionToken` to get the token
199
+ #### 1. Using `getSessionToken` to get the token
164
200
 
165
201
  An example for api function, and passing the token on the `Authorization` header:
166
202
 
@@ -201,7 +237,7 @@ const Component = () => {
201
237
  }
202
238
  ```
203
239
 
204
- ##### 2. Passing `sessionTokenViaCookie` boolean prop to the `AuthProvider`
240
+ #### 2. Passing `sessionTokenViaCookie` boolean prop to the `AuthProvider`
205
241
 
206
242
  Passing `sessionTokenViaCookie` prop to `AuthProvider` component. Descope SDK will automatically store session token on the `DS` cookie.
207
243
 
@@ -223,7 +259,21 @@ const AppRoot = () => {
223
259
 
224
260
  Now, whenever you call `fetch`, the cookie will automatically be sent with the request. Descope backend SDKs also support extracting the token from the `DS` cookie.
225
261
 
226
- #### Refresh token lifecycle
262
+ Note:
263
+ The session token cookie is set as a [`Secure`](https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.5) cookie. It will be sent only over HTTPS connections.
264
+ In addition, some browsers (e.g. Safari) may not store `Secure` cookie if the hosted page is running on an HTTP protocol.
265
+
266
+ ### Helper Functions
267
+
268
+ You can also use the following functions to assist with various actions managing your JWT.
269
+
270
+ `getSessionToken()` - Get current session token.
271
+ `getRefreshToken()` - Get current refresh token.
272
+ `refresh(token = getRefreshToken())` - Force a refresh on current session token using an existing valid refresh token.
273
+ `getJwtRoles(token = getSessionToken(), tenant = '')` - Get current roles from an existing session token. Provide tenant id for specific tenant roles.
274
+ `getJwtPermissions(token = getSessionToken(), tenant = '')` - Fet current permissions from an existing session token. Provide tenant id for specific tenant permissions.
275
+
276
+ ### Refresh token lifecycle
227
277
 
228
278
  Descope SDK is automatically refreshes the session token when it is about to expire. This is done in the background using the refresh token, without any additional configuration.
229
279
 
@@ -264,6 +314,7 @@ See the following table for customization environment variables for the example
264
314
  | DESCOPE_FLOW_ID | Which flow ID to use in the login page | **sign-up-or-in** |
265
315
  | DESCOPE_BASE_URL | Custom Descope base URL | None |
266
316
  | DESCOPE_THEME | Flow theme | None |
317
+ | DESCOPE_LOCALE | Flow locale | Browser's locale |
267
318
  | DESCOPE_REDIRECT_URL | Flow redirect URL for OAuth/SSO/Magic Link/Enchanted Link | None |
268
319
  | DESCOPE_TENANT_ID | Flow tenant ID for SSO/SAML | None |
269
320
  | DESCOPE_DEBUG_MODE | **"true"** - Enable debugger</br>**"false"** - Disable flow debugger | None |
@@ -282,6 +333,8 @@ DESCOPE_FLOW_ID=""
282
333
  DESCOPE_BASE_URL=""
283
334
  # Set flow theme to dark
284
335
  DESCOPE_THEME=dark
336
+ # Set flow locale, default is browser's locale
337
+ DESCOPE_LOCALE=""
285
338
  # Flow Redirect URL
286
339
  DESCOPE_REDIRECT_URL=""
287
340
  # Tenant ID
@@ -294,14 +347,6 @@ DESCOPE_STEP_UP_FLOW_ID=step-up
294
347
  DESCOPE_TELEMETRY_KEY=""
295
348
  ```
296
349
 
297
- ## Helper Functions
298
-
299
- You can also use the following functions to assist with various actions managing your JWT.
300
-
301
- `refresh(token = getRefreshToken())` - Force a refresh on current session token using an existing valid refresh token.
302
- `getJwtRoles(token = getSessionToken(), tenant = '')` - Get current roles from an existing session token. Provide tenant id for specific tenant roles.
303
- `getJwtPermissions(token = getSessionToken(), tenant = '')` - Fet current permissions from an existing session token. Provide tenant id for specific tenant permissions.
304
-
305
350
  ## Learn More
306
351
 
307
352
  To learn more please see the [Descope Documentation and API reference page](https://docs.descope.com/).
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("@descope/web-js-sdk");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function s(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var o=r(e),n=r(t);const u=o.default.createContext(void 0),i=e=>(...t)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...t)},c=e=>(...t)=>{let r;try{r=e(...t)}catch(e){console.error(e)}return r},a={"x-descope-sdk-name":"react","x-descope-sdk-version":"1.0.9"},d="undefined"!=typeof window;let l;const f=e=>{const t=n.default({...e,persistTokens:d,autoRefresh:d});return l=t,t};l=f({projectId:"temp pid"});const p=()=>d?l?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),h=()=>d?l?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),m=c(((e=p(),t)=>l?.getJwtPermissions(e,t))),k=c(((e=p(),t)=>l?.getJwtRoles(e,t)));const b=({projectId:t,baseUrl:r,sessionTokenViaCookie:s,children:n})=>{const[c,d]=e.useState(),[l,p]=e.useState(),[h,m]=e.useState(!1),[k,b]=e.useState(!1),g=(({projectId:t,baseUrl:r,sessionTokenViaCookie:s})=>e.useMemo((()=>{if(t)return f({projectId:t,baseUrl:r,sessionTokenViaCookie:s,baseHeaders:a,persistToken:!0,autoRefresh:!0})}),[t,r,s]))({projectId:t,baseUrl:r,sessionTokenViaCookie:s});e.useEffect((()=>{if(g){const e=g.onSessionTokenChange(p),t=g.onUserChange(d);return()=>{e(),t()}}}),[g]);const w=e.useRef(!1),y=e.useCallback((()=>{w.current||(w.current=!0,b(!0),i(g?.refresh)().then((()=>{b(!1)})))}),[g]),S=e.useCallback((()=>{m(!0),i(g.me)().then((()=>{m(!1)}))}),[g]),v=e.useMemo((()=>({fetchUser:S,user:c,isUserLoading:h,fetchSession:y,session:l,isSessionLoading:k,isSessionFetched:w.current,projectId:t,baseUrl:r,setUser:d,setSession:p,sdk:g})),[S,c,h,y,l,k,w.current,t,r,d,p,g]);return o.default.createElement(u.Provider,{value:v},n)};b.defaultProps={baseUrl:"",children:void 0,sessionTokenViaCookie:!1};const g=e.lazy((async()=>((await Promise.resolve().then((function(){return s(require("@descope/web-component"))}))).default.sdkConfigOverrides={baseHeaders:a},{default:({projectId:e,flowId:t,baseUrl:r,innerRef:s,tenant:n,theme:u,debug:i,telemetryKey:c,redirectUrl:a,autoFocus:d})=>o.default.createElement("descope-wc",{"project-id":e,"flow-id":t,"base-url":r,ref:s,tenant:n,theme:u,debug:i,telemetryKey:c,"redirect-url":a,"auto-focus":d})}))),w=o.default.forwardRef((({flowId:t,onSuccess:r,onError:s,tenant:n,theme:i,debug:c,telemetryKey:a,redirectUrl:d,autoFocus:l},f)=>{const[p,h]=e.useState(null);e.useImperativeHandle(f,(()=>p));const{projectId:m,baseUrl:k,sdk:b}=o.default.useContext(u),w=e.useCallback((async e=>{await b.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),r&&r(e)}),[r]);return e.useEffect((()=>{const e=p;return e?.addEventListener("success",w),s&&e?.addEventListener("error",s),()=>{s&&e?.removeEventListener("error",s),e?.removeEventListener("success",w)}}),[p,s,w]),o.default.createElement("form",null,o.default.createElement(e.Suspense,{fallback:null},o.default.createElement(g,{projectId:m,flowId:t,baseUrl:k,innerRef:h,tenant:n,theme:i,debug:c,telemetryKey:a,redirectUrl:d,autoFocus:l})))}));w.defaultProps={onError:void 0,onSuccess:void 0};var y=()=>{const t=e.useContext(u);if(!t)throw Error("You can only use this hook in the context of <AuthProvider />");return t};const S=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,v={get(e,t){if("object"==typeof e[t]&&null!==e[t])return new Proxy(e[t],v);if("function"==typeof e[t])return()=>{throw Error(S("function"))};throw Error(S("attribute"))}};exports.AuthProvider=b,exports.Descope=w,exports.SignInFlow=e=>o.default.createElement(w,{...e,flowId:"sign-in"}),exports.SignUpFlow=e=>o.default.createElement(w,{...e,flowId:"sign-up"}),exports.SignUpOrInFlow=e=>o.default.createElement(w,{...e,flowId:"sign-up-or-in"}),exports.getJwtPermissions=m,exports.getJwtRoles=k,exports.getRefreshToken=h,exports.getSessionToken=p,exports.refresh=(e=h())=>l?.refresh(e),exports.useDescope=()=>{const{sdk:t}=y();return e.useMemo((()=>t||new Proxy(f({projectId:"dummy"}),v)),[t])},exports.useSession=()=>{const{session:t,isSessionLoading:r,fetchSession:s,isSessionFetched:o}=y(),n=e.useRef(r);return e.useMemo((()=>{n.current=r}),[r]),e.useMemo((()=>{o||(n.current=!0)}),[o]),e.useEffect((()=>{t||r||s()}),[s]),{isSessionLoading:n.current,sessionToken:t,isAuthenticated:!!t}},exports.useUser=()=>{const{user:t,fetchUser:r,isUserLoading:s,session:o}=y(),[n,u]=e.useState(!1),i=e.useRef(s),c=e.useMemo((()=>!t&&!s&&o&&!n),[r,o,n]);return e.useMemo((()=>{i.current=s}),[s]),e.useMemo((()=>{c&&(i.current=!0)}),[c]),e.useEffect((()=>{c&&(u(!0),r())}),[c]),{isUserLoading:i.current,user:t}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("@descope/web-js-sdk");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function s(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var o=r(e),n=r(t);const u=o.default.createContext(void 0),i=e=>(...t)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...t)},c=e=>(...t)=>{let r;try{r=e(...t)}catch(e){console.error(e)}return r},a={"x-descope-sdk-name":"react","x-descope-sdk-version":"1.0.11"},l="undefined"!=typeof window;let d;const f=e=>{const t=n.default({...e,persistTokens:l,autoRefresh:l});return d=t,t};d=f({projectId:"temp pid"});const p=()=>l?d?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),h=()=>l?d?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),m=c(((e=p(),t)=>d?.getJwtPermissions(e,t))),g=c(((e=p(),t)=>d?.getJwtRoles(e,t)));const k=e.lazy((async()=>((await Promise.resolve().then((function(){return s(require("@descope/web-component"))}))).default.sdkConfigOverrides={baseHeaders:a},{default:({projectId:e,flowId:t,baseUrl:r,innerRef:s,tenant:n,theme:u,locale:i,debug:c,telemetryKey:a,redirectUrl:l,autoFocus:d})=>o.default.createElement("descope-wc",{"project-id":e,"flow-id":t,"base-url":r,ref:s,tenant:n,theme:u,locale:i,debug:c,telemetryKey:a,"redirect-url":l,"auto-focus":d})}))),w=o.default.forwardRef((({flowId:t,onSuccess:r,onError:s,logger:n,tenant:i,theme:c,locale:a,debug:l,telemetryKey:d,redirectUrl:f,autoFocus:p,errorTransformer:h},m)=>{const[g,w]=e.useState(null);e.useImperativeHandle(m,(()=>g));const{projectId:b,baseUrl:y,sdk:S}=o.default.useContext(u),E=e.useCallback((async e=>{await S.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),r&&r(e)}),[r]);return e.useEffect((()=>{const e=g;return e?.addEventListener("success",E),s&&e?.addEventListener("error",s),()=>{s&&e?.removeEventListener("error",s),e?.removeEventListener("success",E)}}),[g,s,E]),e.useEffect((()=>{g&&(g.errorTransformer=h)}),[g,h]),e.useEffect((()=>{g&&n&&(g.logger=n)}),[g,n]),o.default.createElement("form",null,o.default.createElement(e.Suspense,{fallback:null},o.default.createElement(k,{projectId:b,flowId:t,baseUrl:y,innerRef:w,tenant:i,theme:c,locale:a,debug:l,telemetryKey:d,redirectUrl:f,autoFocus:p})))}));var b=()=>{const t=e.useContext(u);if(!t)throw Error("You can only use this hook in the context of <AuthProvider />");return t};const y=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,S={get(e,t){if("object"==typeof e[t]&&null!==e[t])return new Proxy(e[t],S);if("function"==typeof e[t])return()=>{throw Error(y("function"))};throw Error(y("attribute"))}};exports.AuthProvider=({projectId:t,baseUrl:r="",sessionTokenViaCookie:s=!1,children:n})=>{const[c,l]=e.useState(),[d,p]=e.useState(),[h,m]=e.useState(!1),[g,k]=e.useState(!1),w=(({projectId:t,baseUrl:r,sessionTokenViaCookie:s})=>e.useMemo((()=>{if(t)return f({projectId:t,baseUrl:r,sessionTokenViaCookie:s,baseHeaders:a,persistToken:!0,autoRefresh:!0})}),[t,r,s]))({projectId:t,baseUrl:r,sessionTokenViaCookie:s});e.useEffect((()=>{if(w){const e=w.onSessionTokenChange(p),t=w.onUserChange(l);return()=>{e(),t()}}}),[w]);const b=e.useRef(!1),y=e.useCallback((()=>{b.current||(b.current=!0,k(!0),i(w?.refresh)().then((()=>{k(!1)})))}),[w]),S=e.useCallback((()=>{m(!0),i(w.me)().then((()=>{m(!1)}))}),[w]),E=e.useMemo((()=>({fetchUser:S,user:c,isUserLoading:h,fetchSession:y,session:d,isSessionLoading:g,isSessionFetched:b.current,projectId:t,baseUrl:r,setUser:l,setSession:p,sdk:w})),[S,c,h,y,d,g,b.current,t,r,l,p,w]);return o.default.createElement(u.Provider,{value:E},n)},exports.Descope=w,exports.SignInFlow=e=>o.default.createElement(w,{...e,flowId:"sign-in"}),exports.SignUpFlow=e=>o.default.createElement(w,{...e,flowId:"sign-up"}),exports.SignUpOrInFlow=e=>o.default.createElement(w,{...e,flowId:"sign-up-or-in"}),exports.getJwtPermissions=m,exports.getJwtRoles=g,exports.getRefreshToken=h,exports.getSessionToken=p,exports.refresh=(e=h())=>d?.refresh(e),exports.useDescope=()=>{const{sdk:t}=b();return e.useMemo((()=>t||new Proxy(f({projectId:"dummy"}),S)),[t])},exports.useSession=()=>{const{session:t,isSessionLoading:r,fetchSession:s,isSessionFetched:o}=b(),n=e.useRef(r);return e.useMemo((()=>{n.current=r}),[r]),e.useMemo((()=>{o||(n.current=!0)}),[o]),e.useEffect((()=>{t||r||s()}),[s]),{isSessionLoading:n.current,sessionToken:t,isAuthenticated:!!t}},exports.useUser=()=>{const{user:t,fetchUser:r,isUserLoading:s,session:o}=b(),[n,u]=e.useState(!1),i=e.useRef(s),c=e.useMemo((()=>!t&&!s&&o&&!n),[r,o,n]);return e.useMemo((()=>{i.current=s}),[s]),e.useMemo((()=>{c&&(i.current=!0)}),[c]),e.useEffect((()=>{c&&(u(!0),r())}),[c]),{isUserLoading:i.current,user:t}};
2
2
  //# sourceMappingURL=index.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../../src/hooks/Context.ts","../../src/utils.ts","../../src/constants.ts","../../src/sdk.ts","../../src/components/AuthProvider/AuthProvider.tsx","../../src/components/AuthProvider/useSdk.ts","../../src/components/Descope.tsx","../../src/hooks/useContext.ts","../../src/hooks/useDescope.ts","../../src/components/DefaultFlows.tsx","../../src/hooks/useSession.ts","../../src/hooks/useUser.ts"],"sourcesContent":["import React from 'react';\nimport { IContext } from '../types';\n\nconst Context = React.createContext<IContext>(undefined);\n\nexport default Context;\n","/**\n * Wrap a function with a validation that it exists\n * @param fn The function to wrap with the validation\n * @throws if function does not exist, an error with the relevant message will be thrown\n */\nexport const withValidation =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tif (!fn) {\n\t\t\tthrow Error(\n\t\t\t\t`You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`\n\t\t\t);\n\t\t}\n\t\treturn fn(...args);\n\t};\n\nexport const wrapInTry =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tlet res: U;\n\t\ttry {\n\t\t\tres = fn(...args);\n\t\t} catch (err) {\n\t\t\tconsole.error(err); // eslint-disable-line no-console\n\t\t}\n\t\treturn res;\n\t};\n","declare const BUILD_VERSION: string;\n\n// eslint-disable-next-line import/prefer-default-export\nexport const baseHeaders = {\n\t'x-descope-sdk-name': 'react',\n\t'x-descope-sdk-version': BUILD_VERSION\n};\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n","import createSdk from '@descope/web-js-sdk';\nimport { IS_BROWSER } from './constants';\nimport { wrapInTry } from './utils';\n\ntype Sdk = ReturnType<typeof createSdkWrapper>;\nlet sdkInstance: Sdk;\n\nconst createSdkWrapper = <P extends Parameters<typeof createSdk>[0]>(\n\tconfig: P\n) => {\n\tconst sdk = createSdk({\n\t\t...config,\n\t\tpersistTokens: IS_BROWSER as true,\n\t\tautoRefresh: IS_BROWSER as true\n\t});\n\tsdkInstance = sdk;\n\n\treturn sdk;\n};\n\n/**\n * We want to make sure the getSessionToken fn is used only when persistTokens is on\n *\n * So we are keeping the SDK init in a single place,\n * and we are creating a temp instance in order to export the getSessionToken\n * even before the SDK was init\n */\nsdkInstance = createSdkWrapper({ projectId: 'temp pid' });\n\nexport const getSessionToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getSessionToken();\n\t}\n\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get session token is not supported in SSR');\n\treturn '';\n};\n\nexport const getRefreshToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getRefreshToken();\n\t}\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get refresh token is not supported in SSR');\n\treturn '';\n};\n\nexport const getJwtPermissions = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtPermissions(token, tenant)\n);\n\nexport const getJwtRoles = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtRoles(token, tenant)\n);\n\nexport const refresh = (token = getRefreshToken()) =>\n\tsdkInstance?.refresh(token);\n\nexport default createSdkWrapper;\n","import React, {\n\tFC,\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseState\n} from 'react';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport { withValidation } from '../../utils';\nimport useSdk from './useSdk';\n\ninterface IAuthProviderProps {\n\tprojectId: string;\n\tbaseUrl?: string;\n\t// If true, session token (jwt) will be stored on cookie. Otherwise, the session token will be\n\t// stored on local storage and can accessed with getSessionToken function\n\t// Use this option if session token will stay small (less than 1k)\n\t// NOTE: Session token can grow, especially in cases of using authorization, or adding custom claims\n\tsessionTokenViaCookie?: boolean;\n\tchildren?: JSX.Element;\n}\n\nconst AuthProvider: FC<IAuthProviderProps> = ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie,\n\tchildren\n}) => {\n\tconst [user, setUser] = useState<User>();\n\tconst [session, setSession] = useState<string>();\n\n\tconst [isUserLoading, setIsUserLoading] = useState(false);\n\tconst [isSessionLoading, setIsSessionLoading] = useState(false);\n\n\tconst sdk = useSdk({ projectId, baseUrl, sessionTokenViaCookie });\n\n\tuseEffect(() => {\n\t\tif (sdk) {\n\t\t\tconst unsubscribeSessionToken = sdk.onSessionTokenChange(setSession);\n\t\t\tconst unsubscribeUser = sdk.onUserChange(setUser);\n\n\t\t\treturn () => {\n\t\t\t\tunsubscribeSessionToken();\n\t\t\t\tunsubscribeUser();\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}, [sdk]);\n\n\tconst isSessionFetched = useRef(false);\n\n\tconst fetchSession = useCallback(() => {\n\t\t// We want that the session will fetched only once\n\t\tif (isSessionFetched.current) return;\n\t\tisSessionFetched.current = true;\n\n\t\tsetIsSessionLoading(true);\n\t\twithValidation(sdk?.refresh)().then(() => {\n\t\t\tsetIsSessionLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst fetchUser = useCallback(() => {\n\t\tsetIsUserLoading(true);\n\t\twithValidation(sdk.me)().then(() => {\n\t\t\tsetIsUserLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst value = useMemo<IContext>(\n\t\t() => ({\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tisSessionFetched: isSessionFetched.current,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t}),\n\t\t[\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tisSessionFetched.current,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t]\n\t);\n\treturn <Context.Provider value={value}>{children}</Context.Provider>;\n};\n\nAuthProvider.defaultProps = {\n\tbaseUrl: '',\n\tchildren: undefined,\n\tsessionTokenViaCookie: false\n};\n\nexport default AuthProvider;\n","import { useMemo } from 'react';\nimport { baseHeaders } from '../../constants';\nimport createSdk from '../../sdk';\n\ntype Config = Pick<\n\tParameters<typeof createSdk>[0],\n\t'projectId' | 'baseUrl' | 'sessionTokenViaCookie'\n>;\n\nexport default ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie\n}: Config): ReturnType<typeof createSdk> =>\n\tuseMemo(() => {\n\t\tif (!projectId) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn createSdk({\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsessionTokenViaCookie,\n\t\t\tbaseHeaders,\n\t\t\tpersistToken: true,\n\t\t\tautoRefresh: true\n\t\t});\n\t}, [projectId, baseUrl, sessionTokenViaCookie]);\n","import React, {\n\tlazy,\n\tSuspense,\n\tuseCallback,\n\tuseEffect,\n\tuseImperativeHandle,\n\tuseState\n} from 'react';\nimport { baseHeaders } from '../constants';\nimport Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\n\n// web-component code uses browser API, but can be used in SSR apps, hence the lazy loading\nconst DescopeWC = lazy(async () => {\n\tconst module = await import('@descope/web-component');\n\t// we want to override the web-component base headers so we can tell that is was used via the React SDK\n\tmodule.default.sdkConfigOverrides = { baseHeaders };\n\n\treturn {\n\t\tdefault: ({\n\t\t\tprojectId,\n\t\t\tflowId,\n\t\t\tbaseUrl,\n\t\t\tinnerRef,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t}) => (\n\t\t\t<descope-wc\n\t\t\t\tproject-id={projectId}\n\t\t\t\tflow-id={flowId}\n\t\t\t\tbase-url={baseUrl}\n\t\t\t\tref={innerRef}\n\t\t\t\ttenant={tenant}\n\t\t\t\ttheme={theme}\n\t\t\t\tdebug={debug}\n\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\tredirect-url={redirectUrl}\n\t\t\t\tauto-focus={autoFocus}\n\t\t\t/>\n\t\t)\n\t};\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n\t(\n\t\t{\n\t\t\tflowId,\n\t\t\tonSuccess,\n\t\t\tonError,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t},\n\t\tref\n\t) => {\n\t\tconst [innerRef, setInnerRef] = useState(null);\n\n\t\tuseImperativeHandle(ref, () => innerRef);\n\n\t\tconst { projectId, baseUrl, sdk } = React.useContext(Context);\n\n\t\tconst handleSuccess = useCallback(\n\t\t\tasync (e: CustomEvent) => {\n\t\t\t\t// In order to make sure all the after-hooks are running with the success response\n\t\t\t\t// we are generating a fake response with the success data and calling the http client after hook fn with it\n\t\t\t\tawait sdk.httpClient.hooks.afterRequest(\n\t\t\t\t\t{} as any,\n\t\t\t\t\tnew Response(JSON.stringify(e.detail))\n\t\t\t\t);\n\t\t\t\tif (onSuccess) {\n\t\t\t\t\tonSuccess(e);\n\t\t\t\t}\n\t\t\t},\n\t\t\t[onSuccess]\n\t\t);\n\n\t\tuseEffect(() => {\n\t\t\tconst ele = innerRef;\n\t\t\tele?.addEventListener('success', handleSuccess);\n\t\t\tif (onError) ele?.addEventListener('error', onError);\n\n\t\t\treturn () => {\n\t\t\t\tif (onError) ele?.removeEventListener('error', onError);\n\n\t\t\t\tele?.removeEventListener('success', handleSuccess);\n\t\t\t};\n\t\t}, [innerRef, onError, handleSuccess]);\n\n\t\treturn (\n\t\t\t/**\n\t\t\t * in order to avoid redundant remounting of the WC, we are wrapping it with a form element\n\t\t\t * this workaround is done in order to support webauthn passkeys\n\t\t\t * it can be removed once this issue will be solved\n\t\t\t * https://bugs.chromium.org/p/chromium/issues/detail?id=1404106#c2\n\t\t\t */\n\t\t\t<form>\n\t\t\t\t<Suspense fallback={null}>\n\t\t\t\t\t<DescopeWC\n\t\t\t\t\t\tprojectId={projectId}\n\t\t\t\t\t\tflowId={flowId}\n\t\t\t\t\t\tbaseUrl={baseUrl}\n\t\t\t\t\t\tinnerRef={setInnerRef}\n\t\t\t\t\t\ttenant={tenant}\n\t\t\t\t\t\ttheme={theme}\n\t\t\t\t\t\tdebug={debug}\n\t\t\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\t\t\tredirectUrl={redirectUrl}\n\t\t\t\t\t\tautoFocus={autoFocus}\n\t\t\t\t\t/>\n\t\t\t\t</Suspense>\n\t\t\t</form>\n\t\t);\n\t}\n);\n\nDescope.defaultProps = {\n\tonError: undefined,\n\tonSuccess: undefined\n};\n\nexport default Descope;\n","import { useContext } from 'react';\nimport Context from './Context';\n\nexport default () => {\n\tconst ctx = useContext(Context);\n\tif (!ctx) {\n\t\tthrow Error(\n\t\t\t`You can only use this hook in the context of <AuthProvider />`\n\t\t);\n\t}\n\n\treturn ctx;\n};\n","import { useMemo } from 'react';\nimport { Sdk } from '../types';\nimport useContext from './useContext';\nimport createSdk from '../sdk';\n\nconst generateErrorMsg = (entryType: string) =>\n\t`You can only use this ${entryType} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`;\n\n// handler which throw an error for every SDK function\nconst proxyThrowHandler = {\n\t// eslint-disable-next-line prefer-arrow/prefer-arrow-functions\n\tget(target: Record<string, any>, key: string) {\n\t\tif (typeof target[key] === 'object' && target[key] !== null) {\n\t\t\treturn new Proxy(target[key], proxyThrowHandler);\n\t\t}\n\n\t\tif (typeof target[key] === 'function') {\n\t\t\treturn () => {\n\t\t\t\tthrow Error(generateErrorMsg('function'));\n\t\t\t};\n\t\t}\n\n\t\tthrow Error(generateErrorMsg('attribute'));\n\t}\n};\n\nconst useDescope = (): Sdk => {\n\tconst { sdk } = useContext();\n\n\treturn useMemo(() => {\n\t\tif (!sdk) {\n\t\t\t// In case the SDK is not initialized, we want to throw an error when the SDK functions are called\n\t\t\treturn new Proxy(\n\t\t\t\tcreateSdk({ projectId: 'dummy' }),\n\t\t\t\tproxyThrowHandler\n\t\t\t) as Sdk;\n\t\t}\n\n\t\treturn sdk;\n\t}, [sdk]);\n};\n\nexport default useDescope;\n","import React from 'react';\nimport { DefaultFlowProps } from '../types';\nimport Descope from './Descope';\n\nexport const SignInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-in\" />\n);\n\nexport const SignUpFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up\" />\n);\n\nexport const SignUpOrInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up-or-in\" />\n);\n","import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n\tconst { session, isSessionLoading, fetchSession, isSessionFetched } =\n\t\tuseContext();\n\n\t// when session should be received, we want the return value of \"isSessionLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isSessionLoading);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isSessionLoading;\n\t}, [isSessionLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (!isSessionFetched) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [isSessionFetched]);\n\n\tuseEffect(() => {\n\t\tif (!session && !isSessionLoading) {\n\t\t\tfetchSession();\n\t\t}\n\t}, [fetchSession]);\n\n\treturn {\n\t\tisSessionLoading: isLoading.current,\n\t\tsessionToken: session,\n\t\tisAuthenticated: !!session\n\t};\n};\n\nexport default useSession;\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport useContext from './useContext';\n\nconst useUser = () => {\n\tconst { user, fetchUser, isUserLoading, session } = useContext();\n\tconst [isInit, setIsInit] = useState(false); // we want to get the user only in the first time we got a session\n\n\t// when session should be received, we want the return value of \"isUserLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isUserLoading);\n\n\tconst shouldFetchUser = useMemo(\n\t\t() => !user && !isUserLoading && session && !isInit,\n\t\t[fetchUser, session, isInit]\n\t);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isUserLoading;\n\t}, [isUserLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [shouldFetchUser]);\n\n\tuseEffect(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tsetIsInit(true);\n\t\t\tfetchUser();\n\t\t}\n\t}, [shouldFetchUser]);\n\n\treturn { isUserLoading: isLoading.current, user };\n};\n\nexport default useUser;\n"],"names":["Context","React","createContext","undefined","withValidation","fn","args","Error","wrapInTry","res","err","console","error","baseHeaders","IS_BROWSER","window","sdkInstance","createSdkWrapper","config","sdk","createSdk","persistTokens","autoRefresh","projectId","getSessionToken","warn","getRefreshToken","getJwtPermissions","token","tenant","getJwtRoles","AuthProvider","baseUrl","sessionTokenViaCookie","children","user","setUser","useState","session","setSession","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","useMemo","persistToken","useSdk","useEffect","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","isSessionFetched","useRef","fetchSession","useCallback","current","refresh","then","fetchUser","me","value","createElement","Provider","defaultProps","DescopeWC","lazy","async","Promise","resolve","_interopNamespace","require","default","sdkConfigOverrides","flowId","innerRef","theme","debug","telemetryKey","redirectUrl","autoFocus","ref","Descope","forwardRef","onSuccess","onError","setInnerRef","useImperativeHandle","useContext","handleSuccess","e","httpClient","hooks","afterRequest","Response","JSON","stringify","detail","ele","addEventListener","removeEventListener","Suspense","fallback","ctx","generateErrorMsg","entryType","proxyThrowHandler","get","target","key","Proxy","props","isLoading","sessionToken","isAuthenticated","isInit","setIsInit","shouldFetchUser"],"mappings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C,CAAC6D,IAEJtE,EAAAA,WAAU,KACLsE,IACHD,GAAU,GACVzD,IACA,GACC,CAAC0D,IAEG,CAAE7E,cAAewE,EAAUxD,QAASrB,OAAM"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../../src/hooks/Context.ts","../../src/utils.ts","../../src/constants.ts","../../src/sdk.ts","../../src/components/AuthProvider/AuthProvider.tsx","../../src/components/Descope.tsx","../../src/hooks/useContext.ts","../../src/hooks/useDescope.ts","../../src/components/AuthProvider/useSdk.ts","../../src/components/DefaultFlows.tsx","../../src/hooks/useSession.ts","../../src/hooks/useUser.ts"],"sourcesContent":["import React from 'react';\nimport { IContext } from '../types';\n\nconst Context = React.createContext<IContext>(undefined);\n\nexport default Context;\n","/**\n * Wrap a function with a validation that it exists\n * @param fn The function to wrap with the validation\n * @throws if function does not exist, an error with the relevant message will be thrown\n */\nexport const withValidation =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tif (!fn) {\n\t\t\tthrow Error(\n\t\t\t\t`You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`\n\t\t\t);\n\t\t}\n\t\treturn fn(...args);\n\t};\n\nexport const wrapInTry =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tlet res: U;\n\t\ttry {\n\t\t\tres = fn(...args);\n\t\t} catch (err) {\n\t\t\tconsole.error(err); // eslint-disable-line no-console\n\t\t}\n\t\treturn res;\n\t};\n","declare const BUILD_VERSION: string;\n\n// eslint-disable-next-line import/prefer-default-export\nexport const baseHeaders = {\n\t'x-descope-sdk-name': 'react',\n\t'x-descope-sdk-version': BUILD_VERSION\n};\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n","import createSdk from '@descope/web-js-sdk';\nimport { IS_BROWSER } from './constants';\nimport { wrapInTry } from './utils';\n\ntype Sdk = ReturnType<typeof createSdkWrapper>;\nlet sdkInstance: Sdk;\n\nconst createSdkWrapper = <P extends Parameters<typeof createSdk>[0]>(\n\tconfig: P\n) => {\n\tconst sdk = createSdk({\n\t\t...config,\n\t\tpersistTokens: IS_BROWSER as true,\n\t\tautoRefresh: IS_BROWSER as true\n\t});\n\tsdkInstance = sdk;\n\n\treturn sdk;\n};\n\n/**\n * We want to make sure the getSessionToken fn is used only when persistTokens is on\n *\n * So we are keeping the SDK init in a single place,\n * and we are creating a temp instance in order to export the getSessionToken\n * even before the SDK was init\n */\nsdkInstance = createSdkWrapper({ projectId: 'temp pid' });\n\nexport const getSessionToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getSessionToken();\n\t}\n\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get session token is not supported in SSR');\n\treturn '';\n};\n\nexport const getRefreshToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getRefreshToken();\n\t}\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get refresh token is not supported in SSR');\n\treturn '';\n};\n\nexport const getJwtPermissions = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtPermissions(token, tenant)\n);\n\nexport const getJwtRoles = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtRoles(token, tenant)\n);\n\nexport const refresh = (token = getRefreshToken()) =>\n\tsdkInstance?.refresh(token);\n\nexport default createSdkWrapper;\n","import React, {\n\tFC,\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseState\n} from 'react';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport { withValidation } from '../../utils';\nimport useSdk from './useSdk';\n\ninterface IAuthProviderProps {\n\tprojectId: string;\n\tbaseUrl?: string;\n\t// If true, session token (jwt) will be stored on cookie. Otherwise, the session token will be\n\t// stored on local storage and can accessed with getSessionToken function\n\t// Use this option if session token will stay small (less than 1k)\n\t// NOTE: Session token can grow, especially in cases of using authorization, or adding custom claims\n\tsessionTokenViaCookie?: boolean;\n\tchildren?: JSX.Element;\n}\n\nconst AuthProvider: FC<IAuthProviderProps> = ({\n\tprojectId,\n\tbaseUrl = '',\n\tsessionTokenViaCookie = false,\n\tchildren = undefined\n}) => {\n\tconst [user, setUser] = useState<User>();\n\tconst [session, setSession] = useState<string>();\n\n\tconst [isUserLoading, setIsUserLoading] = useState(false);\n\tconst [isSessionLoading, setIsSessionLoading] = useState(false);\n\n\tconst sdk = useSdk({ projectId, baseUrl, sessionTokenViaCookie });\n\n\tuseEffect(() => {\n\t\tif (sdk) {\n\t\t\tconst unsubscribeSessionToken = sdk.onSessionTokenChange(setSession);\n\t\t\tconst unsubscribeUser = sdk.onUserChange(setUser);\n\n\t\t\treturn () => {\n\t\t\t\tunsubscribeSessionToken();\n\t\t\t\tunsubscribeUser();\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}, [sdk]);\n\n\tconst isSessionFetched = useRef(false);\n\n\tconst fetchSession = useCallback(() => {\n\t\t// We want that the session will fetched only once\n\t\tif (isSessionFetched.current) return;\n\t\tisSessionFetched.current = true;\n\n\t\tsetIsSessionLoading(true);\n\t\twithValidation(sdk?.refresh)().then(() => {\n\t\t\tsetIsSessionLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst fetchUser = useCallback(() => {\n\t\tsetIsUserLoading(true);\n\t\twithValidation(sdk.me)().then(() => {\n\t\t\tsetIsUserLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst value = useMemo<IContext>(\n\t\t() => ({\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tisSessionFetched: isSessionFetched.current,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t}),\n\t\t[\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tisSessionFetched.current,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t]\n\t);\n\treturn <Context.Provider value={value}>{children}</Context.Provider>;\n};\n\nexport default AuthProvider;\n","import React, {\n\tlazy,\n\tSuspense,\n\tuseCallback,\n\tuseEffect,\n\tuseImperativeHandle,\n\tuseState\n} from 'react';\nimport { baseHeaders } from '../constants';\nimport Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\n\n// web-component code uses browser API, but can be used in SSR apps, hence the lazy loading\nconst DescopeWC = lazy(async () => {\n\tconst module = await import('@descope/web-component');\n\t// we want to override the web-component base headers so we can tell that is was used via the React SDK\n\tmodule.default.sdkConfigOverrides = { baseHeaders };\n\n\treturn {\n\t\tdefault: ({\n\t\t\tprojectId,\n\t\t\tflowId,\n\t\t\tbaseUrl,\n\t\t\tinnerRef,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tlocale,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t}) => (\n\t\t\t<descope-wc\n\t\t\t\tproject-id={projectId}\n\t\t\t\tflow-id={flowId}\n\t\t\t\tbase-url={baseUrl}\n\t\t\t\tref={innerRef}\n\t\t\t\ttenant={tenant}\n\t\t\t\ttheme={theme}\n\t\t\t\tlocale={locale}\n\t\t\t\tdebug={debug}\n\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\tredirect-url={redirectUrl}\n\t\t\t\tauto-focus={autoFocus}\n\t\t\t/>\n\t\t)\n\t};\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n\t(\n\t\t{\n\t\t\tflowId,\n\t\t\tonSuccess,\n\t\t\tonError,\n\t\t\tlogger,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tlocale,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus,\n\t\t\terrorTransformer\n\t\t},\n\t\tref\n\t) => {\n\t\tconst [innerRef, setInnerRef] = useState(null);\n\n\t\tuseImperativeHandle(ref, () => innerRef);\n\n\t\tconst { projectId, baseUrl, sdk } = React.useContext(Context);\n\n\t\tconst handleSuccess = useCallback(\n\t\t\tasync (e: CustomEvent) => {\n\t\t\t\t// In order to make sure all the after-hooks are running with the success response\n\t\t\t\t// we are generating a fake response with the success data and calling the http client after hook fn with it\n\t\t\t\tawait sdk.httpClient.hooks.afterRequest(\n\t\t\t\t\t{} as any,\n\t\t\t\t\tnew Response(JSON.stringify(e.detail))\n\t\t\t\t);\n\t\t\t\tif (onSuccess) {\n\t\t\t\t\tonSuccess(e);\n\t\t\t\t}\n\t\t\t},\n\t\t\t[onSuccess]\n\t\t);\n\n\t\tuseEffect(() => {\n\t\t\tconst ele = innerRef;\n\t\t\tele?.addEventListener('success', handleSuccess);\n\t\t\tif (onError) ele?.addEventListener('error', onError);\n\n\t\t\treturn () => {\n\t\t\t\tif (onError) ele?.removeEventListener('error', onError);\n\n\t\t\t\tele?.removeEventListener('success', handleSuccess);\n\t\t\t};\n\t\t}, [innerRef, onError, handleSuccess]);\n\n\t\tuseEffect(() => {\n\t\t\tif (innerRef) {\n\t\t\t\tinnerRef.errorTransformer = errorTransformer;\n\t\t\t}\n\t\t}, [innerRef, errorTransformer]);\n\n\t\tuseEffect(() => {\n\t\t\tif (innerRef && logger) {\n\t\t\t\tinnerRef.logger = logger;\n\t\t\t}\n\t\t}, [innerRef, logger]);\n\n\t\treturn (\n\t\t\t/**\n\t\t\t * in order to avoid redundant remounting of the WC, we are wrapping it with a form element\n\t\t\t * this workaround is done in order to support webauthn passkeys\n\t\t\t * it can be removed once this issue will be solved\n\t\t\t * https://bugs.chromium.org/p/chromium/issues/detail?id=1404106#c2\n\t\t\t */\n\t\t\t<form>\n\t\t\t\t<Suspense fallback={null}>\n\t\t\t\t\t<DescopeWC\n\t\t\t\t\t\tprojectId={projectId}\n\t\t\t\t\t\tflowId={flowId}\n\t\t\t\t\t\tbaseUrl={baseUrl}\n\t\t\t\t\t\tinnerRef={setInnerRef}\n\t\t\t\t\t\ttenant={tenant}\n\t\t\t\t\t\ttheme={theme}\n\t\t\t\t\t\tlocale={locale}\n\t\t\t\t\t\tdebug={debug}\n\t\t\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\t\t\tredirectUrl={redirectUrl}\n\t\t\t\t\t\tautoFocus={autoFocus}\n\t\t\t\t\t/>\n\t\t\t\t</Suspense>\n\t\t\t</form>\n\t\t);\n\t}\n);\n\nexport default Descope;\n","import { useContext } from 'react';\nimport Context from './Context';\n\nexport default () => {\n\tconst ctx = useContext(Context);\n\tif (!ctx) {\n\t\tthrow Error(\n\t\t\t`You can only use this hook in the context of <AuthProvider />`\n\t\t);\n\t}\n\n\treturn ctx;\n};\n","import { useMemo } from 'react';\nimport { Sdk } from '../types';\nimport useContext from './useContext';\nimport createSdk from '../sdk';\n\nconst generateErrorMsg = (entryType: string) =>\n\t`You can only use this ${entryType} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`;\n\n// handler which throw an error for every SDK function\nconst proxyThrowHandler = {\n\t// eslint-disable-next-line prefer-arrow/prefer-arrow-functions\n\tget(target: Record<string, any>, key: string) {\n\t\tif (typeof target[key] === 'object' && target[key] !== null) {\n\t\t\treturn new Proxy(target[key], proxyThrowHandler);\n\t\t}\n\n\t\tif (typeof target[key] === 'function') {\n\t\t\treturn () => {\n\t\t\t\tthrow Error(generateErrorMsg('function'));\n\t\t\t};\n\t\t}\n\n\t\tthrow Error(generateErrorMsg('attribute'));\n\t}\n};\n\nconst useDescope = (): Sdk => {\n\tconst { sdk } = useContext();\n\n\treturn useMemo(() => {\n\t\tif (!sdk) {\n\t\t\t// In case the SDK is not initialized, we want to throw an error when the SDK functions are called\n\t\t\treturn new Proxy(\n\t\t\t\tcreateSdk({ projectId: 'dummy' }),\n\t\t\t\tproxyThrowHandler\n\t\t\t) as Sdk;\n\t\t}\n\n\t\treturn sdk;\n\t}, [sdk]);\n};\n\nexport default useDescope;\n","import { useMemo } from 'react';\nimport { baseHeaders } from '../../constants';\nimport createSdk from '../../sdk';\n\ntype Config = Pick<\n\tParameters<typeof createSdk>[0],\n\t'projectId' | 'baseUrl' | 'sessionTokenViaCookie'\n>;\n\nexport default ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie\n}: Config): ReturnType<typeof createSdk> =>\n\tuseMemo(() => {\n\t\tif (!projectId) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn createSdk({\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsessionTokenViaCookie,\n\t\t\tbaseHeaders,\n\t\t\tpersistToken: true,\n\t\t\tautoRefresh: true\n\t\t});\n\t}, [projectId, baseUrl, sessionTokenViaCookie]);\n","import React from 'react';\nimport { DefaultFlowProps } from '../types';\nimport Descope from './Descope';\n\nexport const SignInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-in\" />\n);\n\nexport const SignUpFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up\" />\n);\n\nexport const SignUpOrInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up-or-in\" />\n);\n","import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n\tconst { session, isSessionLoading, fetchSession, isSessionFetched } =\n\t\tuseContext();\n\n\t// when session should be received, we want the return value of \"isSessionLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isSessionLoading);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isSessionLoading;\n\t}, [isSessionLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (!isSessionFetched) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [isSessionFetched]);\n\n\tuseEffect(() => {\n\t\tif (!session && !isSessionLoading) {\n\t\t\tfetchSession();\n\t\t}\n\t}, [fetchSession]);\n\n\treturn {\n\t\tisSessionLoading: isLoading.current,\n\t\tsessionToken: session,\n\t\tisAuthenticated: !!session\n\t};\n};\n\nexport default useSession;\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport useContext from './useContext';\n\nconst useUser = () => {\n\tconst { user, fetchUser, isUserLoading, session } = useContext();\n\tconst [isInit, setIsInit] = useState(false); // we want to get the user only in the first time we got a session\n\n\t// when session should be received, we want the return value of \"isUserLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isUserLoading);\n\n\tconst shouldFetchUser = useMemo(\n\t\t() => !user && !isUserLoading && session && !isInit,\n\t\t[fetchUser, session, isInit]\n\t);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isUserLoading;\n\t}, [isUserLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [shouldFetchUser]);\n\n\tuseEffect(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tsetIsInit(true);\n\t\t\tfetchUser();\n\t\t}\n\t}, [shouldFetchUser]);\n\n\treturn { isUserLoading: isLoading.current, user };\n};\n\nexport default useUser;\n"],"names":["Context","React","createContext","undefined","withValidation","fn","args","Error","wrapInTry","res","err","console","error","baseHeaders","IS_BROWSER","window","sdkInstance","createSdkWrapper","config","sdk","createSdk","persistTokens","autoRefresh","projectId","getSessionToken","warn","getRefreshToken","getJwtPermissions","token","tenant","getJwtRoles","DescopeWC","lazy","async","Promise","resolve","then","_interopNamespace","require","default","sdkConfigOverrides","flowId","baseUrl","innerRef","theme","locale","debug","telemetryKey","redirectUrl","autoFocus","ref","Descope","forwardRef","onSuccess","onError","logger","errorTransformer","setInnerRef","useState","useImperativeHandle","useContext","handleSuccess","useCallback","e","httpClient","hooks","afterRequest","Response","JSON","stringify","detail","useEffect","ele","addEventListener","removeEventListener","createElement","Suspense","fallback","ctx","generateErrorMsg","entryType","proxyThrowHandler","get","target","key","Proxy","sessionTokenViaCookie","children","user","setUser","session","setSession","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","useMemo","persistToken","useSdk","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","isSessionFetched","useRef","fetchSession","current","refresh","fetchUser","me","value","Provider","props","isLoading","sessionToken","isAuthenticated","isInit","setIsInit","shouldFetchUser"],"mappings":"qfAGA,MAAMA,EAAUC,EAAAA,QAAMC,mBAAwBC,GCEjCC,EACcC,GAC1B,IAAIC,KACH,IAAKD,EACJ,MAAME,MACL,0HAGF,OAAOF,KAAMC,EAAK,EAGPE,EACcH,GAC1B,IAAIC,KACH,IAAIG,EACJ,IACCA,EAAMJ,KAAMC,EAGZ,CAFC,MAAOI,GACRC,QAAQC,MAAMF,EACd,CACD,OAAOD,CAAG,ECtBCI,EAAc,CAC1B,qBAAsB,QACtB,wBAAyB,UAIbC,EAA+B,oBAAXC,OCJjC,IAAIC,EAEJ,MAAMC,EACLC,IAEA,MAAMC,EAAMC,EAAAA,QAAU,IAClBF,EACHG,cAAeP,EACfQ,YAAaR,IAId,OAFAE,EAAcG,EAEPA,CAAG,EAUXH,EAAcC,EAAiB,CAAEM,UAAW,aAErC,MAAMC,EAAkB,IAC1BV,EACIE,GAAaQ,mBAIrBb,QAAQc,KAAK,6CACN,IAGKC,EAAkB,IAC1BZ,EACIE,GAAaU,mBAGrBf,QAAQc,KAAK,6CACN,IAGKE,EAAoBnB,GAChC,CAACoB,EAAQJ,IAAmBK,IAC3Bb,GAAaW,kBAAkBC,EAAOC,KAG3BC,EAActB,GAC1B,CAACoB,EAAQJ,IAAmBK,IAC3Bb,GAAac,YAAYF,EAAOC,KC/BlC,MCXME,EAA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EAAAA,WAAU,KACJmB,GAAYI,GAChBW,GACA,GACC,CAACA,IAEG,CACNX,iBAAkBmB,EAAUP,QAC5BQ,aAAcxB,EACdyB,kBAAmBzB,EACnB,kBC9Bc,KACf,MAAMF,KAAEA,EAAIoB,UAAEA,EAAShB,cAAEA,EAAaF,QAAEA,GAAY9B,KAC7CwD,EAAQC,GAAa3D,EAAQA,UAAC,GAI/BuD,EAAYT,SAAOZ,GAEnB0B,EAAkBtB,EAAOA,SAC9B,KAAOR,IAASI,GAAiBF,IAAY0B,GAC7C,CAACR,EAAWlB,EAAS0B,IAsBtB,OAlBApB,EAAAA,SAAQ,KACPiB,EAAUP,QAAUd,CAAa,GAC/B,CAACA,IAGJI,EAAAA,SAAQ,KACHsB,IACHL,EAAUP,SAAU,EACpB,GACC,CAACY,IAEJ/C,EAAAA,WAAU,KACL+C,IACHD,GAAU,GACVT,IACA,GACC,CAACU,IAEG,CAAE1B,cAAeqB,EAAUP,QAASlB,OAAM"}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import React, { FC, DOMAttributes } from 'react';
2
- import DescopeWc, { ThemeOptions, AutoFocusOptions } from '@descope/web-component';
2
+ import DescopeWc, { ILogger, ThemeOptions, AutoFocusOptions } from '@descope/web-component';
3
+ export { ILogger } from '@descope/web-component';
3
4
  import * as _descope_core_js_sdk from '@descope/core-js-sdk';
4
5
 
5
6
  interface IAuthProviderProps {
@@ -55,6 +56,7 @@ declare const createSdkWrapper: <P extends Omit<{
55
56
  flow: {
56
57
  start: (flowId: string, options?: Pick<{
57
58
  redirectUrl?: string;
59
+ location?: string;
58
60
  tenant?: string;
59
61
  deviceInfo?: {
60
62
  webAuthnSupport?: boolean;
@@ -358,7 +360,7 @@ declare const createSdkWrapper: <P extends Omit<{
358
360
  maskedEmail: string;
359
361
  }>>;
360
362
  update: (loginId: string, newPassword: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
361
- replace: (loginId: string, oldPassword: string, newPassword: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
363
+ replace: (loginId: string, oldPassword: string, newPassword: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
362
364
  policy: () => Promise<_descope_core_js_sdk.SdkResponse<{
363
365
  minLength: number;
364
366
  lowercase: boolean;
@@ -372,6 +374,7 @@ declare const createSdkWrapper: <P extends Omit<{
372
374
  logoutAll: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
373
375
  me: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.UserResponse>>;
374
376
  isJwtExpired: (token: string) => boolean;
377
+ getTenants: (token: string) => string[];
375
378
  getJwtPermissions: (token: string, tenant?: string) => string[];
376
379
  getJwtRoles: (token: string, tenant?: string) => string[];
377
380
  httpClient: {
@@ -412,6 +415,7 @@ declare const createSdkWrapper: <P extends Omit<{
412
415
  flow: {
413
416
  start: (flowId: string, options?: Pick<{
414
417
  redirectUrl?: string;
418
+ location?: string;
415
419
  tenant?: string;
416
420
  deviceInfo?: {
417
421
  webAuthnSupport?: boolean;
@@ -715,7 +719,7 @@ declare const createSdkWrapper: <P extends Omit<{
715
719
  maskedEmail: string;
716
720
  }>>;
717
721
  update: (loginId: string, newPassword: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
718
- replace: (loginId: string, oldPassword: string, newPassword: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
722
+ replace: (loginId: string, oldPassword: string, newPassword: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
719
723
  policy: () => Promise<_descope_core_js_sdk.SdkResponse<{
720
724
  minLength: number;
721
725
  lowercase: boolean;
@@ -729,6 +733,7 @@ declare const createSdkWrapper: <P extends Omit<{
729
733
  logoutAll: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
730
734
  me: (token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.UserResponse>>;
731
735
  isJwtExpired: (token: string) => boolean;
736
+ getTenants: (token: string) => string[];
732
737
  getJwtPermissions: (token: string, tenant?: string) => string[];
733
738
  getJwtRoles: (token: string, tenant?: string) => string[];
734
739
  httpClient: {
@@ -801,13 +806,20 @@ interface DescopeProps {
801
806
  flowId: string;
802
807
  onSuccess?: DescopeCustomElement['onsuccess'];
803
808
  onError?: DescopeCustomElement['onerror'];
809
+ logger?: ILogger;
804
810
  tenant?: string;
805
811
  theme?: ThemeOptions;
812
+ locale?: string;
806
813
  autoFocus?: AutoFocusOptions;
807
814
  debug?: boolean;
808
815
  telemetryKey?: string;
809
816
  redirectUrl?: string;
817
+ errorTransformer?: (error: {
818
+ text: string;
819
+ type: string;
820
+ }) => string;
810
821
  }
822
+
811
823
  type DefaultFlowProps = Omit<DescopeProps, 'flowId'>;
812
824
 
813
825
  declare const SignInFlow: (props: DefaultFlowProps) => React.JSX.Element;
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import e,{useMemo as t,useState as r,useEffect as o,useRef as s,useCallback as n,lazy as i,useImperativeHandle as c,Suspense as a,useContext as u}from"react";import d from"@descope/web-js-sdk";const l=e.createContext(void 0),f=e=>(...t)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...t)},p=e=>(...t)=>{let r;try{r=e(...t)}catch(e){console.error(e)}return r},h={"x-descope-sdk-name":"react","x-descope-sdk-version":"1.0.9"},m="undefined"!=typeof window;let k;const w=e=>{const t=d({...e,persistTokens:m,autoRefresh:m});return k=t,t};k=w({projectId:"temp pid"});const y=()=>m?k?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),g=()=>m?k?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),b=p(((e=y(),t)=>k?.getJwtPermissions(e,t))),U=p(((e=y(),t)=>k?.getJwtRoles(e,t))),v=(e=g())=>k?.refresh(e);const E=({projectId:i,baseUrl:c,sessionTokenViaCookie:a,children:u})=>{const[d,p]=r(),[m,k]=r(),[y,g]=r(!1),[b,U]=r(!1),v=(({projectId:e,baseUrl:r,sessionTokenViaCookie:o})=>t((()=>{if(e)return w({projectId:e,baseUrl:r,sessionTokenViaCookie:o,baseHeaders:h,persistToken:!0,autoRefresh:!0})}),[e,r,o]))({projectId:i,baseUrl:c,sessionTokenViaCookie:a});o((()=>{if(v){const e=v.onSessionTokenChange(k),t=v.onUserChange(p);return()=>{e(),t()}}}),[v]);const E=s(!1),I=n((()=>{E.current||(E.current=!0,U(!0),f(v?.refresh)().then((()=>{U(!1)})))}),[v]),S=n((()=>{g(!0),f(v.me)().then((()=>{g(!1)}))}),[v]),j=t((()=>({fetchUser:S,user:d,isUserLoading:y,fetchSession:I,session:m,isSessionLoading:b,isSessionFetched:E.current,projectId:i,baseUrl:c,setUser:p,setSession:k,sdk:v})),[S,d,y,I,m,b,E.current,i,c,p,k,v]);return e.createElement(l.Provider,{value:j},u)};E.defaultProps={baseUrl:"",children:void 0,sessionTokenViaCookie:!1};const I=i((async()=>((await import("@descope/web-component")).default.sdkConfigOverrides={baseHeaders:h},{default:({projectId:t,flowId:r,baseUrl:o,innerRef:s,tenant:n,theme:i,debug:c,telemetryKey:a,redirectUrl:u,autoFocus:d})=>e.createElement("descope-wc",{"project-id":t,"flow-id":r,"base-url":o,ref:s,tenant:n,theme:i,debug:c,telemetryKey:a,"redirect-url":u,"auto-focus":d})}))),S=e.forwardRef((({flowId:t,onSuccess:s,onError:i,tenant:u,theme:d,debug:f,telemetryKey:p,redirectUrl:h,autoFocus:m},k)=>{const[w,y]=r(null);c(k,(()=>w));const{projectId:g,baseUrl:b,sdk:U}=e.useContext(l),v=n((async e=>{await U.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),s&&s(e)}),[s]);return o((()=>{const e=w;return e?.addEventListener("success",v),i&&e?.addEventListener("error",i),()=>{i&&e?.removeEventListener("error",i),e?.removeEventListener("success",v)}}),[w,i,v]),e.createElement("form",null,e.createElement(a,{fallback:null},e.createElement(I,{projectId:g,flowId:t,baseUrl:b,innerRef:y,tenant:u,theme:d,debug:f,telemetryKey:p,redirectUrl:h,autoFocus:m})))}));S.defaultProps={onError:void 0,onSuccess:void 0};const j=t=>e.createElement(S,{...t,flowId:"sign-in"}),C=t=>e.createElement(S,{...t,flowId:"sign-up"}),R=t=>e.createElement(S,{...t,flowId:"sign-up-or-in"});var T=()=>{const e=u(l);if(!e)throw Error("You can only use this hook in the context of <AuthProvider />");return e};const L=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,x={get(e,t){if("object"==typeof e[t]&&null!==e[t])return new Proxy(e[t],x);if("function"==typeof e[t])return()=>{throw Error(L("function"))};throw Error(L("attribute"))}},P=()=>{const{sdk:e}=T();return t((()=>e||new Proxy(w({projectId:"dummy"}),x)),[e])},F=()=>{const{session:e,isSessionLoading:r,fetchSession:n,isSessionFetched:i}=T(),c=s(r);return t((()=>{c.current=r}),[r]),t((()=>{i||(c.current=!0)}),[i]),o((()=>{e||r||n()}),[n]),{isSessionLoading:c.current,sessionToken:e,isAuthenticated:!!e}},V=()=>{const{user:e,fetchUser:n,isUserLoading:i,session:c}=T(),[a,u]=r(!1),d=s(i),l=t((()=>!e&&!i&&c&&!a),[n,c,a]);return t((()=>{d.current=i}),[i]),t((()=>{l&&(d.current=!0)}),[l]),o((()=>{l&&(u(!0),n())}),[l]),{isUserLoading:d.current,user:e}};export{E as AuthProvider,S as Descope,j as SignInFlow,C as SignUpFlow,R as SignUpOrInFlow,b as getJwtPermissions,U as getJwtRoles,g as getRefreshToken,y as getSessionToken,v as refresh,P as useDescope,F as useSession,V as useUser};
1
+ import e,{useMemo as r,useState as t,useEffect as o,useRef as n,useCallback as s,lazy as i,useImperativeHandle as c,Suspense as a,useContext as u}from"react";import d from"@descope/web-js-sdk";const l=e.createContext(void 0),f=e=>(...r)=>{if(!e)throw Error("You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component");return e(...r)},p=e=>(...r)=>{let t;try{t=e(...r)}catch(e){console.error(e)}return t},h={"x-descope-sdk-name":"react","x-descope-sdk-version":"1.0.11"},m="undefined"!=typeof window;let k;const g=e=>{const r=d({...e,persistTokens:m,autoRefresh:m});return k=r,r};k=g({projectId:"temp pid"});const w=()=>m?k?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),y=()=>m?k?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),b=p(((e=w(),r)=>k?.getJwtPermissions(e,r))),I=p(((e=w(),r)=>k?.getJwtRoles(e,r))),U=(e=y())=>k?.refresh(e);const E=({projectId:i,baseUrl:c="",sessionTokenViaCookie:a=!1,children:u})=>{const[d,p]=t(),[m,k]=t(),[w,y]=t(!1),[b,I]=t(!1),U=(({projectId:e,baseUrl:t,sessionTokenViaCookie:o})=>r((()=>{if(e)return g({projectId:e,baseUrl:t,sessionTokenViaCookie:o,baseHeaders:h,persistToken:!0,autoRefresh:!0})}),[e,t,o]))({projectId:i,baseUrl:c,sessionTokenViaCookie:a});o((()=>{if(U){const e=U.onSessionTokenChange(k),r=U.onUserChange(p);return()=>{e(),r()}}}),[U]);const E=n(!1),S=s((()=>{E.current||(E.current=!0,I(!0),f(U?.refresh)().then((()=>{I(!1)})))}),[U]),j=s((()=>{y(!0),f(U.me)().then((()=>{y(!1)}))}),[U]),v=r((()=>({fetchUser:j,user:d,isUserLoading:w,fetchSession:S,session:m,isSessionLoading:b,isSessionFetched:E.current,projectId:i,baseUrl:c,setUser:p,setSession:k,sdk:U})),[j,d,w,S,m,b,E.current,i,c,p,k,U]);return e.createElement(l.Provider,{value:v},u)},S=i((async()=>((await import("@descope/web-component")).default.sdkConfigOverrides={baseHeaders:h},{default:({projectId:r,flowId:t,baseUrl:o,innerRef:n,tenant:s,theme:i,locale:c,debug:a,telemetryKey:u,redirectUrl:d,autoFocus:l})=>e.createElement("descope-wc",{"project-id":r,"flow-id":t,"base-url":o,ref:n,tenant:s,theme:i,locale:c,debug:a,telemetryKey:u,"redirect-url":d,"auto-focus":l})}))),j=e.forwardRef((({flowId:r,onSuccess:n,onError:i,logger:u,tenant:d,theme:f,locale:p,debug:h,telemetryKey:m,redirectUrl:k,autoFocus:g,errorTransformer:w},y)=>{const[b,I]=t(null);c(y,(()=>b));const{projectId:U,baseUrl:E,sdk:j}=e.useContext(l),v=s((async e=>{await j.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),n&&n(e)}),[n]);return o((()=>{const e=b;return e?.addEventListener("success",v),i&&e?.addEventListener("error",i),()=>{i&&e?.removeEventListener("error",i),e?.removeEventListener("success",v)}}),[b,i,v]),o((()=>{b&&(b.errorTransformer=w)}),[b,w]),o((()=>{b&&u&&(b.logger=u)}),[b,u]),e.createElement("form",null,e.createElement(a,{fallback:null},e.createElement(S,{projectId:U,flowId:r,baseUrl:E,innerRef:I,tenant:d,theme:f,locale:p,debug:h,telemetryKey:m,redirectUrl:k,autoFocus:g})))})),v=r=>e.createElement(j,{...r,flowId:"sign-in"}),T=r=>e.createElement(j,{...r,flowId:"sign-up"}),C=r=>e.createElement(j,{...r,flowId:"sign-up-or-in"});var R=()=>{const e=u(l);if(!e)throw Error("You can only use this hook in the context of <AuthProvider />");return e};const L=e=>`You can only use this ${e} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`,x={get(e,r){if("object"==typeof e[r]&&null!==e[r])return new Proxy(e[r],x);if("function"==typeof e[r])return()=>{throw Error(L("function"))};throw Error(L("attribute"))}},P=()=>{const{sdk:e}=R();return r((()=>e||new Proxy(g({projectId:"dummy"}),x)),[e])},F=()=>{const{session:e,isSessionLoading:t,fetchSession:s,isSessionFetched:i}=R(),c=n(t);return r((()=>{c.current=t}),[t]),r((()=>{i||(c.current=!0)}),[i]),o((()=>{e||t||s()}),[s]),{isSessionLoading:c.current,sessionToken:e,isAuthenticated:!!e}},A=()=>{const{user:e,fetchUser:s,isUserLoading:i,session:c}=R(),[a,u]=t(!1),d=n(i),l=r((()=>!e&&!i&&c&&!a),[s,c,a]);return r((()=>{d.current=i}),[i]),r((()=>{l&&(d.current=!0)}),[l]),o((()=>{l&&(u(!0),s())}),[l]),{isUserLoading:d.current,user:e}};export{E as AuthProvider,j as Descope,v as SignInFlow,T as SignUpFlow,C as SignUpOrInFlow,b as getJwtPermissions,I as getJwtRoles,y as getRefreshToken,w as getSessionToken,U as refresh,P as useDescope,F as useSession,A as useUser};
2
2
  //# sourceMappingURL=index.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.esm.js","sources":["../src/hooks/Context.ts","../src/utils.ts","../src/constants.ts","../src/sdk.ts","../src/components/AuthProvider/AuthProvider.tsx","../src/components/AuthProvider/useSdk.ts","../src/components/Descope.tsx","../src/components/DefaultFlows.tsx","../src/hooks/useContext.ts","../src/hooks/useDescope.ts","../src/hooks/useSession.ts","../src/hooks/useUser.ts"],"sourcesContent":["import React from 'react';\nimport { IContext } from '../types';\n\nconst Context = React.createContext<IContext>(undefined);\n\nexport default Context;\n","/**\n * Wrap a function with a validation that it exists\n * @param fn The function to wrap with the validation\n * @throws if function does not exist, an error with the relevant message will be thrown\n */\nexport const withValidation =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tif (!fn) {\n\t\t\tthrow Error(\n\t\t\t\t`You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`\n\t\t\t);\n\t\t}\n\t\treturn fn(...args);\n\t};\n\nexport const wrapInTry =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tlet res: U;\n\t\ttry {\n\t\t\tres = fn(...args);\n\t\t} catch (err) {\n\t\t\tconsole.error(err); // eslint-disable-line no-console\n\t\t}\n\t\treturn res;\n\t};\n","declare const BUILD_VERSION: string;\n\n// eslint-disable-next-line import/prefer-default-export\nexport const baseHeaders = {\n\t'x-descope-sdk-name': 'react',\n\t'x-descope-sdk-version': BUILD_VERSION\n};\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n","import createSdk from '@descope/web-js-sdk';\nimport { IS_BROWSER } from './constants';\nimport { wrapInTry } from './utils';\n\ntype Sdk = ReturnType<typeof createSdkWrapper>;\nlet sdkInstance: Sdk;\n\nconst createSdkWrapper = <P extends Parameters<typeof createSdk>[0]>(\n\tconfig: P\n) => {\n\tconst sdk = createSdk({\n\t\t...config,\n\t\tpersistTokens: IS_BROWSER as true,\n\t\tautoRefresh: IS_BROWSER as true\n\t});\n\tsdkInstance = sdk;\n\n\treturn sdk;\n};\n\n/**\n * We want to make sure the getSessionToken fn is used only when persistTokens is on\n *\n * So we are keeping the SDK init in a single place,\n * and we are creating a temp instance in order to export the getSessionToken\n * even before the SDK was init\n */\nsdkInstance = createSdkWrapper({ projectId: 'temp pid' });\n\nexport const getSessionToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getSessionToken();\n\t}\n\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get session token is not supported in SSR');\n\treturn '';\n};\n\nexport const getRefreshToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getRefreshToken();\n\t}\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get refresh token is not supported in SSR');\n\treturn '';\n};\n\nexport const getJwtPermissions = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtPermissions(token, tenant)\n);\n\nexport const getJwtRoles = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtRoles(token, tenant)\n);\n\nexport const refresh = (token = getRefreshToken()) =>\n\tsdkInstance?.refresh(token);\n\nexport default createSdkWrapper;\n","import React, {\n\tFC,\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseState\n} from 'react';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport { withValidation } from '../../utils';\nimport useSdk from './useSdk';\n\ninterface IAuthProviderProps {\n\tprojectId: string;\n\tbaseUrl?: string;\n\t// If true, session token (jwt) will be stored on cookie. Otherwise, the session token will be\n\t// stored on local storage and can accessed with getSessionToken function\n\t// Use this option if session token will stay small (less than 1k)\n\t// NOTE: Session token can grow, especially in cases of using authorization, or adding custom claims\n\tsessionTokenViaCookie?: boolean;\n\tchildren?: JSX.Element;\n}\n\nconst AuthProvider: FC<IAuthProviderProps> = ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie,\n\tchildren\n}) => {\n\tconst [user, setUser] = useState<User>();\n\tconst [session, setSession] = useState<string>();\n\n\tconst [isUserLoading, setIsUserLoading] = useState(false);\n\tconst [isSessionLoading, setIsSessionLoading] = useState(false);\n\n\tconst sdk = useSdk({ projectId, baseUrl, sessionTokenViaCookie });\n\n\tuseEffect(() => {\n\t\tif (sdk) {\n\t\t\tconst unsubscribeSessionToken = sdk.onSessionTokenChange(setSession);\n\t\t\tconst unsubscribeUser = sdk.onUserChange(setUser);\n\n\t\t\treturn () => {\n\t\t\t\tunsubscribeSessionToken();\n\t\t\t\tunsubscribeUser();\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}, [sdk]);\n\n\tconst isSessionFetched = useRef(false);\n\n\tconst fetchSession = useCallback(() => {\n\t\t// We want that the session will fetched only once\n\t\tif (isSessionFetched.current) return;\n\t\tisSessionFetched.current = true;\n\n\t\tsetIsSessionLoading(true);\n\t\twithValidation(sdk?.refresh)().then(() => {\n\t\t\tsetIsSessionLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst fetchUser = useCallback(() => {\n\t\tsetIsUserLoading(true);\n\t\twithValidation(sdk.me)().then(() => {\n\t\t\tsetIsUserLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst value = useMemo<IContext>(\n\t\t() => ({\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tisSessionFetched: isSessionFetched.current,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t}),\n\t\t[\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tisSessionFetched.current,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t]\n\t);\n\treturn <Context.Provider value={value}>{children}</Context.Provider>;\n};\n\nAuthProvider.defaultProps = {\n\tbaseUrl: '',\n\tchildren: undefined,\n\tsessionTokenViaCookie: false\n};\n\nexport default AuthProvider;\n","import { useMemo } from 'react';\nimport { baseHeaders } from '../../constants';\nimport createSdk from '../../sdk';\n\ntype Config = Pick<\n\tParameters<typeof createSdk>[0],\n\t'projectId' | 'baseUrl' | 'sessionTokenViaCookie'\n>;\n\nexport default ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie\n}: Config): ReturnType<typeof createSdk> =>\n\tuseMemo(() => {\n\t\tif (!projectId) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn createSdk({\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsessionTokenViaCookie,\n\t\t\tbaseHeaders,\n\t\t\tpersistToken: true,\n\t\t\tautoRefresh: true\n\t\t});\n\t}, [projectId, baseUrl, sessionTokenViaCookie]);\n","import React, {\n\tlazy,\n\tSuspense,\n\tuseCallback,\n\tuseEffect,\n\tuseImperativeHandle,\n\tuseState\n} from 'react';\nimport { baseHeaders } from '../constants';\nimport Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\n\n// web-component code uses browser API, but can be used in SSR apps, hence the lazy loading\nconst DescopeWC = lazy(async () => {\n\tconst module = await import('@descope/web-component');\n\t// we want to override the web-component base headers so we can tell that is was used via the React SDK\n\tmodule.default.sdkConfigOverrides = { baseHeaders };\n\n\treturn {\n\t\tdefault: ({\n\t\t\tprojectId,\n\t\t\tflowId,\n\t\t\tbaseUrl,\n\t\t\tinnerRef,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t}) => (\n\t\t\t<descope-wc\n\t\t\t\tproject-id={projectId}\n\t\t\t\tflow-id={flowId}\n\t\t\t\tbase-url={baseUrl}\n\t\t\t\tref={innerRef}\n\t\t\t\ttenant={tenant}\n\t\t\t\ttheme={theme}\n\t\t\t\tdebug={debug}\n\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\tredirect-url={redirectUrl}\n\t\t\t\tauto-focus={autoFocus}\n\t\t\t/>\n\t\t)\n\t};\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n\t(\n\t\t{\n\t\t\tflowId,\n\t\t\tonSuccess,\n\t\t\tonError,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t},\n\t\tref\n\t) => {\n\t\tconst [innerRef, setInnerRef] = useState(null);\n\n\t\tuseImperativeHandle(ref, () => innerRef);\n\n\t\tconst { projectId, baseUrl, sdk } = React.useContext(Context);\n\n\t\tconst handleSuccess = useCallback(\n\t\t\tasync (e: CustomEvent) => {\n\t\t\t\t// In order to make sure all the after-hooks are running with the success response\n\t\t\t\t// we are generating a fake response with the success data and calling the http client after hook fn with it\n\t\t\t\tawait sdk.httpClient.hooks.afterRequest(\n\t\t\t\t\t{} as any,\n\t\t\t\t\tnew Response(JSON.stringify(e.detail))\n\t\t\t\t);\n\t\t\t\tif (onSuccess) {\n\t\t\t\t\tonSuccess(e);\n\t\t\t\t}\n\t\t\t},\n\t\t\t[onSuccess]\n\t\t);\n\n\t\tuseEffect(() => {\n\t\t\tconst ele = innerRef;\n\t\t\tele?.addEventListener('success', handleSuccess);\n\t\t\tif (onError) ele?.addEventListener('error', onError);\n\n\t\t\treturn () => {\n\t\t\t\tif (onError) ele?.removeEventListener('error', onError);\n\n\t\t\t\tele?.removeEventListener('success', handleSuccess);\n\t\t\t};\n\t\t}, [innerRef, onError, handleSuccess]);\n\n\t\treturn (\n\t\t\t/**\n\t\t\t * in order to avoid redundant remounting of the WC, we are wrapping it with a form element\n\t\t\t * this workaround is done in order to support webauthn passkeys\n\t\t\t * it can be removed once this issue will be solved\n\t\t\t * https://bugs.chromium.org/p/chromium/issues/detail?id=1404106#c2\n\t\t\t */\n\t\t\t<form>\n\t\t\t\t<Suspense fallback={null}>\n\t\t\t\t\t<DescopeWC\n\t\t\t\t\t\tprojectId={projectId}\n\t\t\t\t\t\tflowId={flowId}\n\t\t\t\t\t\tbaseUrl={baseUrl}\n\t\t\t\t\t\tinnerRef={setInnerRef}\n\t\t\t\t\t\ttenant={tenant}\n\t\t\t\t\t\ttheme={theme}\n\t\t\t\t\t\tdebug={debug}\n\t\t\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\t\t\tredirectUrl={redirectUrl}\n\t\t\t\t\t\tautoFocus={autoFocus}\n\t\t\t\t\t/>\n\t\t\t\t</Suspense>\n\t\t\t</form>\n\t\t);\n\t}\n);\n\nDescope.defaultProps = {\n\tonError: undefined,\n\tonSuccess: undefined\n};\n\nexport default Descope;\n","import React from 'react';\nimport { DefaultFlowProps } from '../types';\nimport Descope from './Descope';\n\nexport const SignInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-in\" />\n);\n\nexport const SignUpFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up\" />\n);\n\nexport const SignUpOrInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up-or-in\" />\n);\n","import { useContext } from 'react';\nimport Context from './Context';\n\nexport default () => {\n\tconst ctx = useContext(Context);\n\tif (!ctx) {\n\t\tthrow Error(\n\t\t\t`You can only use this hook in the context of <AuthProvider />`\n\t\t);\n\t}\n\n\treturn ctx;\n};\n","import { useMemo } from 'react';\nimport { Sdk } from '../types';\nimport useContext from './useContext';\nimport createSdk from '../sdk';\n\nconst generateErrorMsg = (entryType: string) =>\n\t`You can only use this ${entryType} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`;\n\n// handler which throw an error for every SDK function\nconst proxyThrowHandler = {\n\t// eslint-disable-next-line prefer-arrow/prefer-arrow-functions\n\tget(target: Record<string, any>, key: string) {\n\t\tif (typeof target[key] === 'object' && target[key] !== null) {\n\t\t\treturn new Proxy(target[key], proxyThrowHandler);\n\t\t}\n\n\t\tif (typeof target[key] === 'function') {\n\t\t\treturn () => {\n\t\t\t\tthrow Error(generateErrorMsg('function'));\n\t\t\t};\n\t\t}\n\n\t\tthrow Error(generateErrorMsg('attribute'));\n\t}\n};\n\nconst useDescope = (): Sdk => {\n\tconst { sdk } = useContext();\n\n\treturn useMemo(() => {\n\t\tif (!sdk) {\n\t\t\t// In case the SDK is not initialized, we want to throw an error when the SDK functions are called\n\t\t\treturn new Proxy(\n\t\t\t\tcreateSdk({ projectId: 'dummy' }),\n\t\t\t\tproxyThrowHandler\n\t\t\t) as Sdk;\n\t\t}\n\n\t\treturn sdk;\n\t}, [sdk]);\n};\n\nexport default useDescope;\n","import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n\tconst { session, isSessionLoading, fetchSession, isSessionFetched } =\n\t\tuseContext();\n\n\t// when session should be received, we want the return value of \"isSessionLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isSessionLoading);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isSessionLoading;\n\t}, [isSessionLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (!isSessionFetched) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [isSessionFetched]);\n\n\tuseEffect(() => {\n\t\tif (!session && !isSessionLoading) {\n\t\t\tfetchSession();\n\t\t}\n\t}, [fetchSession]);\n\n\treturn {\n\t\tisSessionLoading: isLoading.current,\n\t\tsessionToken: session,\n\t\tisAuthenticated: !!session\n\t};\n};\n\nexport default useSession;\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport useContext from './useContext';\n\nconst useUser = () => {\n\tconst { user, fetchUser, isUserLoading, session } = useContext();\n\tconst [isInit, setIsInit] = useState(false); // we want to get the user only in the first time we got a session\n\n\t// when session should be received, we want the return value of \"isUserLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isUserLoading);\n\n\tconst shouldFetchUser = useMemo(\n\t\t() => !user && !isUserLoading && session && !isInit,\n\t\t[fetchUser, session, isInit]\n\t);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isUserLoading;\n\t}, [isUserLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [shouldFetchUser]);\n\n\tuseEffect(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tsetIsInit(true);\n\t\t\tfetchUser();\n\t\t}\n\t}, [shouldFetchUser]);\n\n\treturn { isUserLoading: isLoading.current, user };\n};\n\nexport default useUser;\n"],"names":["Context","React","createContext","undefined","withValidation","fn","args","Error","wrapInTry","res","err","console","error","baseHeaders","IS_BROWSER","window","sdkInstance","createSdkWrapper","config","sdk","createSdk","persistTokens","autoRefresh","projectId","getSessionToken","warn","getRefreshToken","getJwtPermissions","token","tenant","getJwtRoles","refresh","AuthProvider","baseUrl","sessionTokenViaCookie","children","user","setUser","useState","session","setSession","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","useMemo","persistToken","useSdk","useEffect","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","isSessionFetched","useRef","fetchSession","useCallback","current","then","fetchUser","me","value","createElement","Provider","defaultProps","DescopeWC","lazy","async","import","default","sdkConfigOverrides","flowId","innerRef","theme","debug","telemetryKey","redirectUrl","autoFocus","ref","Descope","forwardRef","onSuccess","onError","setInnerRef","useImperativeHandle","useContext","handleSuccess","e","httpClient","hooks","afterRequest","Response","JSON","stringify","detail","ele","addEventListener","removeEventListener","Suspense","fallback","SignInFlow","props","SignUpFlow","SignUpOrInFlow","ctx","generateErrorMsg","entryType","proxyThrowHandler","get","target","key","Proxy","useDescope","useSession","isLoading","sessionToken","isAuthenticated","useUser","isInit","setIsInit","shouldFetchUser"],"mappings":"iMAGA,MAAMA,EAAUC,EAAMC,mBAAwBC,GCEjCC,EACcC,GAC1B,IAAIC,KACH,IAAKD,EACJ,MAAME,MACL,0HAGF,OAAOF,KAAMC,EAAK,EAGPE,EACcH,GAC1B,IAAIC,KACH,IAAIG,EACJ,IACCA,EAAMJ,KAAMC,EAGZ,CAFC,MAAOI,GACRC,QAAQC,MAAMF,EACd,CACD,OAAOD,CAAG,ECtBCI,EAAc,CAC1B,qBAAsB,QACtB,wBAAyB,SAIbC,EAA+B,oBAAXC,OCJjC,IAAIC,EAEJ,MAAMC,EACLC,IAEA,MAAMC,EAAMC,EAAU,IAClBF,EACHG,cAAeP,EACfQ,YAAaR,IAId,OAFAE,EAAcG,EAEPA,CAAG,EAUXH,EAAcC,EAAiB,CAAEM,UAAW,aAErC,MAAMC,EAAkB,IAC1BV,EACIE,GAAaQ,mBAIrBb,QAAQc,KAAK,6CACN,IAGKC,EAAkB,IAC1BZ,EACIE,GAAaU,mBAGrBf,QAAQc,KAAK,6CACN,IAGKE,EAAoBnB,GAChC,CAACoB,EAAQJ,IAAmBK,IAC3Bb,GAAaW,kBAAkBC,EAAOC,KAG3BC,EAActB,GAC1B,CAACoB,EAAQJ,IAAmBK,IAC3Bb,GAAac,YAAYF,EAAOC,KAGrBE,EAAU,CAACH,EAAQF,MAC/BV,GAAae,QAAQH,GCnCtB,MAA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B,KAAOT,IAASK,GAAiBF,IAAY+E,GAC7C,CAAC3D,EAAWpB,EAAS+E,IAsBtB,OAlBAzE,GAAQ,KACPqE,EAAUzD,QAAUhB,CAAa,GAC/B,CAACA,IAGJI,GAAQ,KACH2E,IACHN,EAAUzD,SAAU,EACpB,GACC,CAAC+D,IAEJxE,GAAU,KACLwE,IACHD,GAAU,GACV5D,IACA,GACC,CAAC6D,IAEG,CAAE/E,cAAeyE,EAAUzD,QAASrB,OAAM"}
1
+ {"version":3,"file":"index.esm.js","sources":["../src/hooks/Context.ts","../src/utils.ts","../src/constants.ts","../src/sdk.ts","../src/components/AuthProvider/AuthProvider.tsx","../src/components/AuthProvider/useSdk.ts","../src/components/Descope.tsx","../src/components/DefaultFlows.tsx","../src/hooks/useContext.ts","../src/hooks/useDescope.ts","../src/hooks/useSession.ts","../src/hooks/useUser.ts"],"sourcesContent":["import React from 'react';\nimport { IContext } from '../types';\n\nconst Context = React.createContext<IContext>(undefined);\n\nexport default Context;\n","/**\n * Wrap a function with a validation that it exists\n * @param fn The function to wrap with the validation\n * @throws if function does not exist, an error with the relevant message will be thrown\n */\nexport const withValidation =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tif (!fn) {\n\t\t\tthrow Error(\n\t\t\t\t`You can only use this function after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`\n\t\t\t);\n\t\t}\n\t\treturn fn(...args);\n\t};\n\nexport const wrapInTry =\n\t<T extends Array<any>, U>(fn: (...args: T) => U) =>\n\t(...args: T): U => {\n\t\tlet res: U;\n\t\ttry {\n\t\t\tres = fn(...args);\n\t\t} catch (err) {\n\t\t\tconsole.error(err); // eslint-disable-line no-console\n\t\t}\n\t\treturn res;\n\t};\n","declare const BUILD_VERSION: string;\n\n// eslint-disable-next-line import/prefer-default-export\nexport const baseHeaders = {\n\t'x-descope-sdk-name': 'react',\n\t'x-descope-sdk-version': BUILD_VERSION\n};\n\n// This sdk can be used in SSR apps\nexport const IS_BROWSER = typeof window !== 'undefined';\n","import createSdk from '@descope/web-js-sdk';\nimport { IS_BROWSER } from './constants';\nimport { wrapInTry } from './utils';\n\ntype Sdk = ReturnType<typeof createSdkWrapper>;\nlet sdkInstance: Sdk;\n\nconst createSdkWrapper = <P extends Parameters<typeof createSdk>[0]>(\n\tconfig: P\n) => {\n\tconst sdk = createSdk({\n\t\t...config,\n\t\tpersistTokens: IS_BROWSER as true,\n\t\tautoRefresh: IS_BROWSER as true\n\t});\n\tsdkInstance = sdk;\n\n\treturn sdk;\n};\n\n/**\n * We want to make sure the getSessionToken fn is used only when persistTokens is on\n *\n * So we are keeping the SDK init in a single place,\n * and we are creating a temp instance in order to export the getSessionToken\n * even before the SDK was init\n */\nsdkInstance = createSdkWrapper({ projectId: 'temp pid' });\n\nexport const getSessionToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getSessionToken();\n\t}\n\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get session token is not supported in SSR');\n\treturn '';\n};\n\nexport const getRefreshToken = () => {\n\tif (IS_BROWSER) {\n\t\treturn sdkInstance?.getRefreshToken();\n\t}\n\t// eslint-disable-next-line no-console\n\tconsole.warn('Get refresh token is not supported in SSR');\n\treturn '';\n};\n\nexport const getJwtPermissions = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtPermissions(token, tenant)\n);\n\nexport const getJwtRoles = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtRoles(token, tenant)\n);\n\nexport const refresh = (token = getRefreshToken()) =>\n\tsdkInstance?.refresh(token);\n\nexport default createSdkWrapper;\n","import React, {\n\tFC,\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseState\n} from 'react';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport { withValidation } from '../../utils';\nimport useSdk from './useSdk';\n\ninterface IAuthProviderProps {\n\tprojectId: string;\n\tbaseUrl?: string;\n\t// If true, session token (jwt) will be stored on cookie. Otherwise, the session token will be\n\t// stored on local storage and can accessed with getSessionToken function\n\t// Use this option if session token will stay small (less than 1k)\n\t// NOTE: Session token can grow, especially in cases of using authorization, or adding custom claims\n\tsessionTokenViaCookie?: boolean;\n\tchildren?: JSX.Element;\n}\n\nconst AuthProvider: FC<IAuthProviderProps> = ({\n\tprojectId,\n\tbaseUrl = '',\n\tsessionTokenViaCookie = false,\n\tchildren = undefined\n}) => {\n\tconst [user, setUser] = useState<User>();\n\tconst [session, setSession] = useState<string>();\n\n\tconst [isUserLoading, setIsUserLoading] = useState(false);\n\tconst [isSessionLoading, setIsSessionLoading] = useState(false);\n\n\tconst sdk = useSdk({ projectId, baseUrl, sessionTokenViaCookie });\n\n\tuseEffect(() => {\n\t\tif (sdk) {\n\t\t\tconst unsubscribeSessionToken = sdk.onSessionTokenChange(setSession);\n\t\t\tconst unsubscribeUser = sdk.onUserChange(setUser);\n\n\t\t\treturn () => {\n\t\t\t\tunsubscribeSessionToken();\n\t\t\t\tunsubscribeUser();\n\t\t\t};\n\t\t}\n\t\treturn undefined;\n\t}, [sdk]);\n\n\tconst isSessionFetched = useRef(false);\n\n\tconst fetchSession = useCallback(() => {\n\t\t// We want that the session will fetched only once\n\t\tif (isSessionFetched.current) return;\n\t\tisSessionFetched.current = true;\n\n\t\tsetIsSessionLoading(true);\n\t\twithValidation(sdk?.refresh)().then(() => {\n\t\t\tsetIsSessionLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst fetchUser = useCallback(() => {\n\t\tsetIsUserLoading(true);\n\t\twithValidation(sdk.me)().then(() => {\n\t\t\tsetIsUserLoading(false);\n\t\t});\n\t}, [sdk]);\n\n\tconst value = useMemo<IContext>(\n\t\t() => ({\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tisSessionFetched: isSessionFetched.current,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t}),\n\t\t[\n\t\t\tfetchUser,\n\t\t\tuser,\n\t\t\tisUserLoading,\n\t\t\tfetchSession,\n\t\t\tsession,\n\t\t\tisSessionLoading,\n\t\t\tisSessionFetched.current,\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsetUser,\n\t\t\tsetSession,\n\t\t\tsdk\n\t\t]\n\t);\n\treturn <Context.Provider value={value}>{children}</Context.Provider>;\n};\n\nexport default AuthProvider;\n","import { useMemo } from 'react';\nimport { baseHeaders } from '../../constants';\nimport createSdk from '../../sdk';\n\ntype Config = Pick<\n\tParameters<typeof createSdk>[0],\n\t'projectId' | 'baseUrl' | 'sessionTokenViaCookie'\n>;\n\nexport default ({\n\tprojectId,\n\tbaseUrl,\n\tsessionTokenViaCookie\n}: Config): ReturnType<typeof createSdk> =>\n\tuseMemo(() => {\n\t\tif (!projectId) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn createSdk({\n\t\t\tprojectId,\n\t\t\tbaseUrl,\n\t\t\tsessionTokenViaCookie,\n\t\t\tbaseHeaders,\n\t\t\tpersistToken: true,\n\t\t\tautoRefresh: true\n\t\t});\n\t}, [projectId, baseUrl, sessionTokenViaCookie]);\n","import React, {\n\tlazy,\n\tSuspense,\n\tuseCallback,\n\tuseEffect,\n\tuseImperativeHandle,\n\tuseState\n} from 'react';\nimport { baseHeaders } from '../constants';\nimport Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\n\n// web-component code uses browser API, but can be used in SSR apps, hence the lazy loading\nconst DescopeWC = lazy(async () => {\n\tconst module = await import('@descope/web-component');\n\t// we want to override the web-component base headers so we can tell that is was used via the React SDK\n\tmodule.default.sdkConfigOverrides = { baseHeaders };\n\n\treturn {\n\t\tdefault: ({\n\t\t\tprojectId,\n\t\t\tflowId,\n\t\t\tbaseUrl,\n\t\t\tinnerRef,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tlocale,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus\n\t\t}) => (\n\t\t\t<descope-wc\n\t\t\t\tproject-id={projectId}\n\t\t\t\tflow-id={flowId}\n\t\t\t\tbase-url={baseUrl}\n\t\t\t\tref={innerRef}\n\t\t\t\ttenant={tenant}\n\t\t\t\ttheme={theme}\n\t\t\t\tlocale={locale}\n\t\t\t\tdebug={debug}\n\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\tredirect-url={redirectUrl}\n\t\t\t\tauto-focus={autoFocus}\n\t\t\t/>\n\t\t)\n\t};\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n\t(\n\t\t{\n\t\t\tflowId,\n\t\t\tonSuccess,\n\t\t\tonError,\n\t\t\tlogger,\n\t\t\ttenant,\n\t\t\ttheme,\n\t\t\tlocale,\n\t\t\tdebug,\n\t\t\ttelemetryKey,\n\t\t\tredirectUrl,\n\t\t\tautoFocus,\n\t\t\terrorTransformer\n\t\t},\n\t\tref\n\t) => {\n\t\tconst [innerRef, setInnerRef] = useState(null);\n\n\t\tuseImperativeHandle(ref, () => innerRef);\n\n\t\tconst { projectId, baseUrl, sdk } = React.useContext(Context);\n\n\t\tconst handleSuccess = useCallback(\n\t\t\tasync (e: CustomEvent) => {\n\t\t\t\t// In order to make sure all the after-hooks are running with the success response\n\t\t\t\t// we are generating a fake response with the success data and calling the http client after hook fn with it\n\t\t\t\tawait sdk.httpClient.hooks.afterRequest(\n\t\t\t\t\t{} as any,\n\t\t\t\t\tnew Response(JSON.stringify(e.detail))\n\t\t\t\t);\n\t\t\t\tif (onSuccess) {\n\t\t\t\t\tonSuccess(e);\n\t\t\t\t}\n\t\t\t},\n\t\t\t[onSuccess]\n\t\t);\n\n\t\tuseEffect(() => {\n\t\t\tconst ele = innerRef;\n\t\t\tele?.addEventListener('success', handleSuccess);\n\t\t\tif (onError) ele?.addEventListener('error', onError);\n\n\t\t\treturn () => {\n\t\t\t\tif (onError) ele?.removeEventListener('error', onError);\n\n\t\t\t\tele?.removeEventListener('success', handleSuccess);\n\t\t\t};\n\t\t}, [innerRef, onError, handleSuccess]);\n\n\t\tuseEffect(() => {\n\t\t\tif (innerRef) {\n\t\t\t\tinnerRef.errorTransformer = errorTransformer;\n\t\t\t}\n\t\t}, [innerRef, errorTransformer]);\n\n\t\tuseEffect(() => {\n\t\t\tif (innerRef && logger) {\n\t\t\t\tinnerRef.logger = logger;\n\t\t\t}\n\t\t}, [innerRef, logger]);\n\n\t\treturn (\n\t\t\t/**\n\t\t\t * in order to avoid redundant remounting of the WC, we are wrapping it with a form element\n\t\t\t * this workaround is done in order to support webauthn passkeys\n\t\t\t * it can be removed once this issue will be solved\n\t\t\t * https://bugs.chromium.org/p/chromium/issues/detail?id=1404106#c2\n\t\t\t */\n\t\t\t<form>\n\t\t\t\t<Suspense fallback={null}>\n\t\t\t\t\t<DescopeWC\n\t\t\t\t\t\tprojectId={projectId}\n\t\t\t\t\t\tflowId={flowId}\n\t\t\t\t\t\tbaseUrl={baseUrl}\n\t\t\t\t\t\tinnerRef={setInnerRef}\n\t\t\t\t\t\ttenant={tenant}\n\t\t\t\t\t\ttheme={theme}\n\t\t\t\t\t\tlocale={locale}\n\t\t\t\t\t\tdebug={debug}\n\t\t\t\t\t\ttelemetryKey={telemetryKey}\n\t\t\t\t\t\tredirectUrl={redirectUrl}\n\t\t\t\t\t\tautoFocus={autoFocus}\n\t\t\t\t\t/>\n\t\t\t\t</Suspense>\n\t\t\t</form>\n\t\t);\n\t}\n);\n\nexport default Descope;\n","import React from 'react';\nimport { DefaultFlowProps } from '../types';\nimport Descope from './Descope';\n\nexport const SignInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-in\" />\n);\n\nexport const SignUpFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up\" />\n);\n\nexport const SignUpOrInFlow = (props: DefaultFlowProps) => (\n\t<Descope {...props} flowId=\"sign-up-or-in\" />\n);\n","import { useContext } from 'react';\nimport Context from './Context';\n\nexport default () => {\n\tconst ctx = useContext(Context);\n\tif (!ctx) {\n\t\tthrow Error(\n\t\t\t`You can only use this hook in the context of <AuthProvider />`\n\t\t);\n\t}\n\n\treturn ctx;\n};\n","import { useMemo } from 'react';\nimport { Sdk } from '../types';\nimport useContext from './useContext';\nimport createSdk from '../sdk';\n\nconst generateErrorMsg = (entryType: string) =>\n\t`You can only use this ${entryType} after sdk initialization. Make sure to supply 'projectId' to <AuthProvider /> component`;\n\n// handler which throw an error for every SDK function\nconst proxyThrowHandler = {\n\t// eslint-disable-next-line prefer-arrow/prefer-arrow-functions\n\tget(target: Record<string, any>, key: string) {\n\t\tif (typeof target[key] === 'object' && target[key] !== null) {\n\t\t\treturn new Proxy(target[key], proxyThrowHandler);\n\t\t}\n\n\t\tif (typeof target[key] === 'function') {\n\t\t\treturn () => {\n\t\t\t\tthrow Error(generateErrorMsg('function'));\n\t\t\t};\n\t\t}\n\n\t\tthrow Error(generateErrorMsg('attribute'));\n\t}\n};\n\nconst useDescope = (): Sdk => {\n\tconst { sdk } = useContext();\n\n\treturn useMemo(() => {\n\t\tif (!sdk) {\n\t\t\t// In case the SDK is not initialized, we want to throw an error when the SDK functions are called\n\t\t\treturn new Proxy(\n\t\t\t\tcreateSdk({ projectId: 'dummy' }),\n\t\t\t\tproxyThrowHandler\n\t\t\t) as Sdk;\n\t\t}\n\n\t\treturn sdk;\n\t}, [sdk]);\n};\n\nexport default useDescope;\n","import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n\tconst { session, isSessionLoading, fetchSession, isSessionFetched } =\n\t\tuseContext();\n\n\t// when session should be received, we want the return value of \"isSessionLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isSessionLoading);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isSessionLoading;\n\t}, [isSessionLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (!isSessionFetched) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [isSessionFetched]);\n\n\tuseEffect(() => {\n\t\tif (!session && !isSessionLoading) {\n\t\t\tfetchSession();\n\t\t}\n\t}, [fetchSession]);\n\n\treturn {\n\t\tisSessionLoading: isLoading.current,\n\t\tsessionToken: session,\n\t\tisAuthenticated: !!session\n\t};\n};\n\nexport default useSession;\n","import { useEffect, useMemo, useRef, useState } from 'react';\nimport useContext from './useContext';\n\nconst useUser = () => {\n\tconst { user, fetchUser, isUserLoading, session } = useContext();\n\tconst [isInit, setIsInit] = useState(false); // we want to get the user only in the first time we got a session\n\n\t// when session should be received, we want the return value of \"isUserLoading\" to be true starting from the first call\n\t// (and not only when receiving an update from the context)\n\tconst isLoading = useRef(isUserLoading);\n\n\tconst shouldFetchUser = useMemo(\n\t\t() => !user && !isUserLoading && session && !isInit,\n\t\t[fetchUser, session, isInit]\n\t);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tisLoading.current = isUserLoading;\n\t}, [isUserLoading]);\n\n\t// we want this to happen before returning a value so we are using \"useMemo\" and not \"useEffect\"\n\tuseMemo(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [shouldFetchUser]);\n\n\tuseEffect(() => {\n\t\tif (shouldFetchUser) {\n\t\t\tsetIsInit(true);\n\t\t\tfetchUser();\n\t\t}\n\t}, [shouldFetchUser]);\n\n\treturn { isUserLoading: isLoading.current, user };\n};\n\nexport default useUser;\n"],"names":["Context","React","createContext","undefined","withValidation","fn","args","Error","wrapInTry","res","err","console","error","baseHeaders","IS_BROWSER","window","sdkInstance","createSdkWrapper","config","sdk","createSdk","persistTokens","autoRefresh","projectId","getSessionToken","warn","getRefreshToken","getJwtPermissions","token","tenant","getJwtRoles","refresh","AuthProvider","baseUrl","sessionTokenViaCookie","children","user","setUser","useState","session","setSession","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","useMemo","persistToken","useSdk","useEffect","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","isSessionFetched","useRef","fetchSession","useCallback","current","then","fetchUser","me","value","createElement","Provider","DescopeWC","lazy","async","import","default","sdkConfigOverrides","flowId","innerRef","theme","locale","debug","telemetryKey","redirectUrl","autoFocus","ref","Descope","forwardRef","onSuccess","onError","logger","errorTransformer","setInnerRef","useImperativeHandle","useContext","handleSuccess","e","httpClient","hooks","afterRequest","Response","JSON","stringify","detail","ele","addEventListener","removeEventListener","Suspense","fallback","SignInFlow","props","SignUpFlow","SignUpOrInFlow","ctx","generateErrorMsg","entryType","proxyThrowHandler","get","target","key","Proxy","useDescope","useSession","isLoading","sessionToken","isAuthenticated","useUser","isInit","setIsInit","shouldFetchUser"],"mappings":"iMAGA,MAAMA,EAAUC,EAAMC,mBAAwBC,GCEjCC,EACcC,GAC1B,IAAIC,KACH,IAAKD,EACJ,MAAME,MACL,0HAGF,OAAOF,KAAMC,EAAK,EAGPE,EACcH,GAC1B,IAAIC,KACH,IAAIG,EACJ,IACCA,EAAMJ,KAAMC,EAGZ,CAFC,MAAOI,GACRC,QAAQC,MAAMF,EACd,CACD,OAAOD,CAAG,ECtBCI,EAAc,CAC1B,qBAAsB,QACtB,wBAAyB,UAIbC,EAA+B,oBAAXC,OCJjC,IAAIC,EAEJ,MAAMC,EACLC,IAEA,MAAMC,EAAMC,EAAU,IAClBF,EACHG,cAAeP,EACfQ,YAAaR,IAId,OAFAE,EAAcG,EAEPA,CAAG,EAUXH,EAAcC,EAAiB,CAAEM,UAAW,aAErC,MAAMC,EAAkB,IAC1BV,EACIE,GAAaQ,mBAIrBb,QAAQc,KAAK,6CACN,IAGKC,EAAkB,IAC1BZ,EACIE,GAAaU,mBAGrBf,QAAQc,KA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