@descope/react-sdk 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -0
- package/dist/cjs/index.cjs.js +1 -1
- package/dist/cjs/index.cjs.js.map +1 -1
- package/dist/index.d.ts +48 -10
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -67,6 +67,12 @@ const App = () => {
|
|
|
67
67
|
|
|
68
68
|
// debug can be set to true to enable debug mode
|
|
69
69
|
// debug={true}
|
|
70
|
+
|
|
71
|
+
// You can configure which tenant the signin/signup flow will sign the user into by providing the tenant ID
|
|
72
|
+
// tenant=<tenantId>
|
|
73
|
+
|
|
74
|
+
// You can configure the redirect URL for OAuth and SSO (will be used when redirecting back from the OAuth provider / IdP), or for "Magic Link" and "Enchanted Link" (will be used as a link in the message sent to the the user)
|
|
75
|
+
// redirectUrl=<redirectUrl>
|
|
70
76
|
/>
|
|
71
77
|
)
|
|
72
78
|
}
|
|
@@ -199,18 +205,30 @@ In order to run this app locally, do the following steps:
|
|
|
199
205
|
// .env
|
|
200
206
|
# Your project id
|
|
201
207
|
DESCOPE_PROJECT_ID=<project-id>
|
|
208
|
+
|
|
202
209
|
# Flow id to run, e.g. sign-up-or-in
|
|
203
210
|
DESCOPE_FLOW_ID=<flow-id>
|
|
211
|
+
|
|
204
212
|
# Optional - Descope base url, e.g. http://localhost:8000
|
|
205
213
|
DESCOPE_BASE_URL=<base-url>
|
|
214
|
+
|
|
206
215
|
# Optional - Debug mode
|
|
207
216
|
DESCOPE_DEBUG_MODE=<debug-mode>
|
|
217
|
+
|
|
208
218
|
# Optional - Theme, can be "light", "dark" or "os" (Auto select based on the OS theme settings). Default is "light"
|
|
209
219
|
DESCOPE_THEME=<theme>
|
|
220
|
+
|
|
210
221
|
# Optional - Telemetry key provided by Descope Inc
|
|
211
222
|
DESCOPE_TELEMETRY_KEY=<telemetry-key>
|
|
223
|
+
|
|
212
224
|
# Optional - Step-Up flow id. If exists, The home page of a logged-in user will show a step-up button
|
|
213
225
|
DESCOPE_STEP_UP_FLOW_ID=step-up
|
|
226
|
+
|
|
227
|
+
# Optional - You can configure the redirect URL for OAuth and SSO (will be used when redirecting back from the OAuth provider / IdP), or for "Magic Link" and "Enchanted Link" (will be used as a link in the message sent to the the user). Default is the browser address
|
|
228
|
+
DESCOPE_REDIRECT_URL=<redirectUrl>
|
|
229
|
+
|
|
230
|
+
# Optional - You can configure which tenant the signin/signup flow will sign the user into by providing the tenant ID
|
|
231
|
+
DESCOPE_TENANT_ID=<tenantId>
|
|
214
232
|
```
|
|
215
233
|
|
|
216
234
|
- Run `npm run start`
|
package/dist/cjs/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("@descope/web-js-sdk");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function o(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if("default"!==s){var o=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,o.get?o:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var r=s(e),n=s(t);const u=r.default.createContext(void 0),i={"x-descope-sdk-name":"react","x-descope-sdk-version":"0.1.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("@descope/web-js-sdk");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function o(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if("default"!==s){var o=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,o.get?o:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var r=s(e),n=s(t);const u=r.default.createContext(void 0),i={"x-descope-sdk-name":"react","x-descope-sdk-version":"0.1.2"},a="undefined"!=typeof window,l=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 s;try{s=e(...t)}catch(e){console.error(e)}return s};let d;const f=e=>{const t=n.default({...e,persistTokens:a,autoRefresh:a});return d=t,t};d=f({projectId:"temp pid"});const p=()=>a?d?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),g=c(((e=p(),t)=>d?.getJwtPermissions(e,t))),k=c(((e=p(),t)=>d?.getJwtRoles(e,t)));const m=({projectId:t,baseUrl:s,sessionTokenViaCookie:o,children:n})=>{const[a,c]=e.useState(),[d,p]=e.useState(),[g,k]=e.useState(!1),[m,h]=e.useState(!1),b=(({projectId:t,baseUrl:s,sessionTokenViaCookie:o})=>e.useMemo((()=>{if(t)return f({projectId:t,baseUrl:s,sessionTokenViaCookie:o,baseHeaders:i,persistToken:!0,autoRefresh:!0})}),[t,s,o]))({projectId:t,baseUrl:s,sessionTokenViaCookie:o});e.useEffect((()=>{if(b){const e=b.onSessionTokenChange(p),t=b.onUserChange(c);return()=>{e(),t()}}}),[b]);const w=e.useCallback((()=>{h(!0),l(b?.refresh)().then((()=>{h(!1)}))}),[b]),S=e.useCallback((()=>{k(!0),l(b.me)().then((()=>{k(!1)}))}),[b]),v=e.useCallback(l(b?.logoutAll),[b]),U=e.useCallback(l(b?.logout),[b]),y=e.useMemo((()=>({fetchUser:S,user:a,isUserLoading:g,fetchSession:w,session:d,isSessionLoading:m,logout:U,logoutAll:v,projectId:t,baseUrl:s,setUser:c,setSession:p,sdk:b})),[S,a,g,w,d,m,U,v,t,s,c,p,b]);return r.default.createElement(u.Provider,{value:y},n)};m.defaultProps={baseUrl:"",children:void 0,sessionTokenViaCookie:!1};const h=e.lazy((async()=>((await Promise.resolve().then((function(){return o(require("@descope/web-component"))}))).default.sdkConfigOverrides={baseHeaders:i},{default:({projectId:e,flowId:t,baseUrl:s,innerRef:o,tenant:n,theme:u,debug:i,telemetryKey:a,redirectUrl:l})=>r.default.createElement("descope-wc",{"project-id":e,"flow-id":t,"base-url":s,ref:o,tenant:n,theme:u,debug:i,telemetryKey:a,"redirect-url":l})}))),b=r.default.forwardRef((({flowId:t,onSuccess:s,onError:o,tenant:n,theme:i,debug:a,telemetryKey:l,redirectUrl:c},d)=>{const[f,p]=e.useState(null);e.useImperativeHandle(d,(()=>f));const{projectId:g,baseUrl:k,setUser:m,setSession:b,sdk:w}=r.default.useContext(u),S=e.useCallback((async e=>{m(e.detail?.user);const t=e.detail?.sessionJwt;b(t),await w.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),s&&s(e)}),[m,b,s]);return e.useEffect((()=>{const e=f;return e?.addEventListener("success",S),o&&e?.addEventListener("error",o),()=>{o&&e?.removeEventListener("error",o),e?.removeEventListener("success",S)}}),[f,o,S]),r.default.createElement("form",null,r.default.createElement(e.Suspense,{fallback:null},r.default.createElement(h,{projectId:g,flowId:t,baseUrl:k,innerRef:p,tenant:n,theme:i,debug:a,telemetryKey:l,redirectUrl:c})))}));b.defaultProps={onError:void 0,onSuccess:void 0};var w=()=>{const t=e.useContext(u);if(!t)throw Error("You can only use this hook in the context of <AuthProvider />");return t};exports.AuthProvider=m,exports.Descope=b,exports.SignInFlow=e=>r.default.createElement(b,{...e,flowId:"sign-in"}),exports.SignUpFlow=e=>r.default.createElement(b,{...e,flowId:"sign-up"}),exports.SignUpOrInFlow=e=>r.default.createElement(b,{...e,flowId:"sign-up-or-in"}),exports.getJwtPermissions=g,exports.getJwtRoles=k,exports.getRefreshToken=()=>a?d?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),exports.getSessionToken=p,exports.useDescope=()=>{const{logout:t,logoutAll:s}=w();return e.useMemo((()=>({logoutAll:s,logout:t})),[s,t])},exports.useSession=()=>{const{session:t,isSessionLoading:s,fetchSession:o}=w(),r=e.useRef(s);return e.useMemo((()=>{r.current=s}),[s]),e.useMemo((()=>{t||s||(r.current=!0)}),[o]),e.useEffect((()=>{t||s||o()}),[o]),{isSessionLoading:r.current,sessionToken:t,isAuthenticated:!!t}},exports.useUser=()=>{const{user:t,fetchUser:s,isUserLoading:o,session:r}=w(),[n,u]=e.useState(!1),i=e.useRef(o),a=e.useMemo((()=>!t&&!o&&r&&!n),[s,r,n]);return e.useMemo((()=>{i.current=o}),[o]),e.useMemo((()=>{a&&(i.current=!0)}),[a]),e.useEffect((()=>{a&&(u(!0),s())}),[a]),{isUserLoading:i.current,user:t}};
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../../src/lib/hooks/Context.ts","../../src/lib/constants.ts","../../src/lib/utils.ts","../../src/lib/sdk.ts","../../src/lib/components/AuthProvider/AuthProvider.tsx","../../src/lib/components/AuthProvider/useSdk.ts","../../src/lib/components/Descope.tsx","../../src/lib/hooks/useContext.ts","../../src/lib/components/DefaultFlows.tsx","../../src/lib/hooks/useDescope.ts","../../src/lib/hooks/useSession.ts","../../src/lib/hooks/useUser.ts"],"sourcesContent":["import React from 'react';\nimport { IContext } from '../types';\n\nconst Context = React.createContext<IContext>(undefined);\n\nexport default Context;\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 * 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","import createSdk from '@descope/web-js-sdk';\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: true,\n\t\tautoRefresh: 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 = () => sdkInstance?.getSessionToken();\nexport const getJwtPermissions = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtPermissions(token, tenant)\n);\nexport const getJwtRoles = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtRoles(token, tenant)\n);\nexport const getRefreshToken = () => sdkInstance?.getRefreshToken();\n\nexport default createSdkWrapper;\n","import React, { FC, useCallback, useEffect, useMemo, useState } from 'react';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport useSdk from './useSdk';\nimport { withValidation } from '../../utils';\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 fetchSession = useCallback(() => {\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 logoutAll = useCallback(withValidation(sdk?.logoutAll), [sdk]);\n\n\tconst logout = useCallback(withValidation(sdk?.logout), [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\tlogout,\n\t\t\tlogoutAll,\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\tlogout,\n\t\t\tlogoutAll,\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 Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\nimport { baseHeaders } from '../constants';\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}) => (\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/>\n\t\t)\n\t};\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n\t({ flowId, onSuccess, onError, tenant, theme, debug, telemetryKey }, ref) => {\n\t\tconst [innerRef, setInnerRef] = useState(null);\n\n\t\tuseImperativeHandle(ref, () => innerRef);\n\n\t\tconst { projectId, baseUrl, setUser, setSession, sdk } =\n\t\t\tReact.useContext(Context);\n\n\t\tconst handleSuccess = useCallback(\n\t\t\tasync (e: CustomEvent) => {\n\t\t\t\tsetUser(e.detail?.user);\n\t\t\t\tconst sessionJwt = e.detail?.sessionJwt;\n\t\t\t\tsetSession(sessionJwt);\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[setUser, setSession, 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/>\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 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 { useMemo } from 'react';\nimport { IAuth } from '../types';\nimport useContext from './useContext';\n\nconst useDescope = (): IAuth => {\n\tconst { logout, logoutAll } = useContext();\n\n\treturn useMemo(\n\t\t() => ({\n\t\t\tlogoutAll,\n\t\t\tlogout\n\t\t}),\n\t\t[logoutAll, logout]\n\t);\n};\n\nexport default useDescope;\n","import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n\tconst { session, isSessionLoading, fetchSession } = useContext();\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 (!session && !isSessionLoading) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [fetchSession]);\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","baseHeaders","withValidation","fn","args","Error","wrapInTry","res","err","console","error","sdkInstance","createSdkWrapper","config","sdk","createSdk","persistTokens","autoRefresh","projectId","getSessionToken","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","fetchSession","useCallback","refresh","then","fetchUser","me","logoutAll","logout","value","createElement","Provider","defaultProps","DescopeWC","lazy","async","Promise","resolve","_interopNamespace","require","default","sdkConfigOverrides","flowId","innerRef","theme","debug","telemetryKey","ref","Descope","forwardRef","onSuccess","onError","setInnerRef","useImperativeHandle","useContext","handleSuccess","e","detail","sessionJwt","httpClient","hooks","afterRequest","Response","JSON","stringify","ele","addEventListener","removeEventListener","Suspense","fallback","ctx","props","getRefreshToken","isLoading","useRef","current","sessionToken","isAuthenticated","isInit","setIsInit","shouldFetchUser"],"mappings":"qfAGA,MAAMA,EAAUC,EAAAA,QAAMC,mBAAwBC,GCAjCC,EAAc,CAC1B,qBAAsB,QACtB,wBAAyB,SCAbC,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,ECrBZ,IAAII,EAEJ,MAAMC,EACLC,IAEA,MAAMC,EAAMC,EAAAA,QAAU,IAClBF,EACHG,eAAe,EACfC,aAAa,IAId,OAFAN,EAAcG,EAEPA,CAAG,EAUXH,EAAcC,EAAiB,CAAEM,UAAW,aAE/B,MAAAC,EAAkB,IAAMR,GAAaQ,kBACrCC,EAAoBd,GAChC,CAACe,EAAQF,IAAmBG,IAC3BX,GAAaS,kBAAkBC,EAAOC,KAE3BC,EAAcjB,GAC1B,CAACe,EAAQF,IAAmBG,IAC3BX,GAAaY,YAAYF,EAAOC,KClBlC,MAAME,EAAuC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9B,KAAOT,IAASK,GAAiBF,IAAYuE,GAC7C,CAACrD,EAAWlB,EAASuE,IAsBtB,OAlBAjE,EAAAA,SAAQ,KACP4D,EAAUE,QAAUlE,CAAa,GAC/B,CAACA,IAGJI,EAAAA,SAAQ,KACHmE,IACHP,EAAUE,SAAU,EACpB,GACC,CAACK,IAEJhE,EAAAA,WAAU,KACLgE,IACHD,GAAU,GACVtD,IACA,GACC,CAACuD,IAEG,CAAEvE,cAAegE,EAAUE,QAASvE,OAAM"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../../src/lib/hooks/Context.ts","../../src/lib/constants.ts","../../src/lib/utils.ts","../../src/lib/sdk.ts","../../src/lib/components/AuthProvider/AuthProvider.tsx","../../src/lib/components/AuthProvider/useSdk.ts","../../src/lib/components/Descope.tsx","../../src/lib/hooks/useContext.ts","../../src/lib/components/DefaultFlows.tsx","../../src/lib/hooks/useDescope.ts","../../src/lib/hooks/useSession.ts","../../src/lib/hooks/useUser.ts"],"sourcesContent":["import React from 'react';\nimport { IContext } from '../types';\n\nconst Context = React.createContext<IContext>(undefined);\n\nexport default Context;\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","/**\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","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 default createSdkWrapper;\n","import React, { FC, useCallback, useEffect, useMemo, useState } from 'react';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport useSdk from './useSdk';\nimport { withValidation } from '../../utils';\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 fetchSession = useCallback(() => {\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 logoutAll = useCallback(withValidation(sdk?.logoutAll), [sdk]);\n\n\tconst logout = useCallback(withValidation(sdk?.logout), [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\tlogout,\n\t\t\tlogoutAll,\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\tlogout,\n\t\t\tlogoutAll,\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 Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\nimport { baseHeaders } from '../constants';\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}) => (\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/>\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},\n\t\tref\n\t) => {\n\t\tconst [innerRef, setInnerRef] = useState(null);\n\n\t\tuseImperativeHandle(ref, () => innerRef);\n\n\t\tconst { projectId, baseUrl, setUser, setSession, sdk } =\n\t\t\tReact.useContext(Context);\n\n\t\tconst handleSuccess = useCallback(\n\t\t\tasync (e: CustomEvent) => {\n\t\t\t\tsetUser(e.detail?.user);\n\t\t\t\tconst sessionJwt = e.detail?.sessionJwt;\n\t\t\t\tsetSession(sessionJwt);\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[setUser, setSession, 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/>\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 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 { useMemo } from 'react';\nimport { IAuth } from '../types';\nimport useContext from './useContext';\n\nconst useDescope = (): IAuth => {\n\tconst { logout, logoutAll } = useContext();\n\n\treturn useMemo(\n\t\t() => ({\n\t\t\tlogoutAll,\n\t\t\tlogout\n\t\t}),\n\t\t[logoutAll, logout]\n\t);\n};\n\nexport default useDescope;\n","import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n\tconst { session, isSessionLoading, fetchSession } = useContext();\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 (!session && !isSessionLoading) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [fetchSession]);\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","baseHeaders","IS_BROWSER","window","withValidation","fn","args","Error","wrapInTry","res","err","console","error","sdkInstance","createSdkWrapper","config","sdk","createSdk","persistTokens","autoRefresh","projectId","getSessionToken","warn","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","fetchSession","useCallback","refresh","then","fetchUser","me","logoutAll","logout","value","createElement","Provider","defaultProps","DescopeWC","lazy","async","Promise","resolve","_interopNamespace","require","default","sdkConfigOverrides","flowId","innerRef","theme","debug","telemetryKey","redirectUrl","ref","Descope","forwardRef","onSuccess","onError","setInnerRef","useImperativeHandle","useContext","handleSuccess","e","detail","sessionJwt","httpClient","hooks","afterRequest","Response","JSON","stringify","ele","addEventListener","removeEventListener","Suspense","fallback","ctx","props","getRefreshToken","isLoading","useRef","current","sessionToken","isAuthenticated","isInit","setIsInit","shouldFetchUser"],"mappings":"qfAGA,MAAMA,EAAUC,EAAAA,QAAMC,mBAAwBC,GCAjCC,EAAc,CAC1B,qBAAsB,QACtB,wBAAyB,SAIbC,EAA+B,oBAAXC,OCJpBC,EACcC,GAC1B,IAAIC,KACH,IAAKD,EACJ,MAAME,MACL,0HAGF,OAAOF,KAAMC,EAAK,EAGPE,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IAE9B,OAAO1C,EAAOA,SACb,KAAO,CACNc,YACAC,YAED,CAACD,EAAWC,GACZ,qBCViB,KAClB,MAAMrB,QAAEA,EAAOI,iBAAEA,EAAgBU,aAAEA,GAAiBkC,IAI9CmB,EAAYC,SAAOhE,GAoBzB,OAjBAE,EAAAA,SAAQ,KACP6D,EAAUE,QAAUjE,CAAgB,GAClC,CAACA,IAGJE,EAAAA,SAAQ,KACFN,GAAYI,IAChB+D,EAAUE,SAAU,EACpB,GACC,CAACvD,IAEJL,EAAAA,WAAU,KACJT,GAAYI,GAChBU,GACA,GACC,CAACA,IAEG,CACNV,iBAAkB+D,EAAUE,QAC5BC,aAActE,EACduE,kBAAmBvE,EACnB,kBC7Bc,KACf,MAAMH,KAAEA,EAAIqB,UAAEA,EAAShB,cAAEA,EAAaF,QAAEA,GAAYgD,KAC7CwB,EAAQC,GAAa1E,EAAQA,UAAC,GAI/BoE,EAAYC,SAAOlE,GAEnBwE,EAAkBpE,EAAOA,SAC9B,KAAOT,IAASK,GAAiBF,IAAYwE,GAC7C,CAACtD,EAAWlB,EAASwE,IAsBtB,OAlBAlE,EAAAA,SAAQ,KACP6D,EAAUE,QAAUnE,CAAa,GAC/B,CAACA,IAGJI,EAAAA,SAAQ,KACHoE,IACHP,EAAUE,SAAU,EACpB,GACC,CAACK,IAEJjE,EAAAA,WAAU,KACLiE,IACHD,GAAU,GACVvD,IACA,GACC,CAACwD,IAEG,CAAExE,cAAeiE,EAAUE,QAASxE,OAAM"}
|
package/dist/index.d.ts
CHANGED
|
@@ -51,11 +51,28 @@ declare const createSdkWrapper: <P extends Omit<{
|
|
|
51
51
|
} & {
|
|
52
52
|
persistTokens?: boolean;
|
|
53
53
|
sessionTokenViaCookie?: boolean;
|
|
54
|
-
}>(config: P) => (({
|
|
54
|
+
}>(config: P) => ((({
|
|
55
55
|
flow: {
|
|
56
|
-
start: (flowId: string, options?: {
|
|
56
|
+
start: (flowId: string, options?: Pick<{
|
|
57
|
+
redirectUrl?: string;
|
|
57
58
|
tenant?: string;
|
|
58
|
-
|
|
59
|
+
deviceInfo?: {
|
|
60
|
+
webAuthnSupport?: boolean;
|
|
61
|
+
};
|
|
62
|
+
lastAuth?: {
|
|
63
|
+
authMethod?: "webauthn" | "otp" | "oauth" | "saml" | "totp" | "magiclink" | "enchantedlink";
|
|
64
|
+
oauthProvider?: string;
|
|
65
|
+
name?: string;
|
|
66
|
+
loginId?: string;
|
|
67
|
+
};
|
|
68
|
+
}, "tenant" | "redirectUrl"> & {
|
|
69
|
+
lastAuth?: Omit<{
|
|
70
|
+
authMethod?: "webauthn" | "otp" | "oauth" | "saml" | "totp" | "magiclink" | "enchantedlink";
|
|
71
|
+
oauthProvider?: string;
|
|
72
|
+
name?: string;
|
|
73
|
+
loginId?: string;
|
|
74
|
+
}, "loginId" | "name">;
|
|
75
|
+
}, conditionInteractionId?: string, interactionId?: string, input?: {
|
|
59
76
|
[x: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | any[])[])[])[])[])[])[])[])[])[])[];
|
|
60
77
|
}) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.FlowResponse>>;
|
|
61
78
|
next: (executionId: string, stepId: string, interactionId: string, input?: {
|
|
@@ -180,7 +197,7 @@ declare const createSdkWrapper: <P extends Omit<{
|
|
|
180
197
|
whatsapp: (loginId: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
181
198
|
};
|
|
182
199
|
update: {
|
|
183
|
-
email: (loginId: string, email: string,
|
|
200
|
+
email: (loginId: string, email: string, URI?: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
184
201
|
phone: {
|
|
185
202
|
email: (loginId: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
186
203
|
sms: (loginId: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
@@ -202,7 +219,7 @@ declare const createSdkWrapper: <P extends Omit<{
|
|
|
202
219
|
timeoutMs: number;
|
|
203
220
|
}) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
204
221
|
update: {
|
|
205
|
-
email: (loginId: string, email: string,
|
|
222
|
+
email: (loginId: string, email: string, URI?: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.EnchantedLinkResponse>>;
|
|
206
223
|
};
|
|
207
224
|
};
|
|
208
225
|
oauth: {
|
|
@@ -314,9 +331,26 @@ declare const createSdkWrapper: <P extends Omit<{
|
|
|
314
331
|
};
|
|
315
332
|
} | {
|
|
316
333
|
flow: {
|
|
317
|
-
start: (flowId: string, options?: {
|
|
334
|
+
start: (flowId: string, options?: Pick<{
|
|
335
|
+
redirectUrl?: string;
|
|
318
336
|
tenant?: string;
|
|
319
|
-
|
|
337
|
+
deviceInfo?: {
|
|
338
|
+
webAuthnSupport?: boolean;
|
|
339
|
+
};
|
|
340
|
+
lastAuth?: {
|
|
341
|
+
authMethod?: "webauthn" | "otp" | "oauth" | "saml" | "totp" | "magiclink" | "enchantedlink";
|
|
342
|
+
oauthProvider?: string;
|
|
343
|
+
name?: string;
|
|
344
|
+
loginId?: string;
|
|
345
|
+
};
|
|
346
|
+
}, "tenant" | "redirectUrl"> & {
|
|
347
|
+
lastAuth?: Omit<{
|
|
348
|
+
authMethod?: "webauthn" | "otp" | "oauth" | "saml" | "totp" | "magiclink" | "enchantedlink";
|
|
349
|
+
oauthProvider?: string;
|
|
350
|
+
name?: string;
|
|
351
|
+
loginId?: string;
|
|
352
|
+
}, "loginId" | "name">;
|
|
353
|
+
}, conditionInteractionId?: string, interactionId?: string, input?: {
|
|
320
354
|
[x: string]: string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | (string | number | boolean | any[])[])[])[])[])[])[])[])[])[])[];
|
|
321
355
|
}) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.FlowResponse>>;
|
|
322
356
|
next: (executionId: string, stepId: string, interactionId: string, input?: {
|
|
@@ -441,7 +475,7 @@ declare const createSdkWrapper: <P extends Omit<{
|
|
|
441
475
|
whatsapp: (loginId: string, uri: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
442
476
|
};
|
|
443
477
|
update: {
|
|
444
|
-
email: (loginId: string, email: string,
|
|
478
|
+
email: (loginId: string, email: string, URI?: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
445
479
|
phone: {
|
|
446
480
|
email: (loginId: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
447
481
|
sms: (loginId: string, phone: string) => Promise<_descope_core_js_sdk.SdkResponse<never>>;
|
|
@@ -463,7 +497,7 @@ declare const createSdkWrapper: <P extends Omit<{
|
|
|
463
497
|
timeoutMs: number;
|
|
464
498
|
}) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.JWTResponse>>;
|
|
465
499
|
update: {
|
|
466
|
-
email: (loginId: string, email: string,
|
|
500
|
+
email: (loginId: string, email: string, URI?: string, token?: string) => Promise<_descope_core_js_sdk.SdkResponse<_descope_core_js_sdk.EnchantedLinkResponse>>;
|
|
467
501
|
};
|
|
468
502
|
};
|
|
469
503
|
oauth: {
|
|
@@ -576,14 +610,17 @@ declare const createSdkWrapper: <P extends Omit<{
|
|
|
576
610
|
}) & {
|
|
577
611
|
onSessionTokenChange: (cb: (data: string) => void) => () => any[];
|
|
578
612
|
onUserChange: (cb: (data: _descope_core_js_sdk.UserResponse) => void) => () => any[];
|
|
613
|
+
}) & {
|
|
614
|
+
getLastUserLoginId: () => string;
|
|
615
|
+
getLastUserDisplayName: () => string;
|
|
579
616
|
}) & {
|
|
580
617
|
getRefreshToken: () => string;
|
|
581
618
|
getSessionToken: () => string;
|
|
582
619
|
};
|
|
583
620
|
declare const getSessionToken: () => string;
|
|
621
|
+
declare const getRefreshToken: () => string;
|
|
584
622
|
declare const getJwtPermissions: (token?: any, tenant?: string) => string[];
|
|
585
623
|
declare const getJwtRoles: (token?: any, tenant?: string) => string[];
|
|
586
|
-
declare const getRefreshToken: () => string;
|
|
587
624
|
|
|
588
625
|
declare global {
|
|
589
626
|
namespace JSX {
|
|
@@ -614,6 +651,7 @@ interface DescopeProps {
|
|
|
614
651
|
theme?: DescopeTheme;
|
|
615
652
|
debug?: boolean;
|
|
616
653
|
telemetryKey?: string;
|
|
654
|
+
redirectUrl?: string;
|
|
617
655
|
}
|
|
618
656
|
type DefaultFlowProps = Omit<DescopeProps, 'flowId'>;
|
|
619
657
|
|
package/dist/index.esm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e,{useMemo as t,useState as o,useEffect as s,useCallback as r,lazy as n,useImperativeHandle as i,Suspense as c,useContext as
|
|
1
|
+
import e,{useMemo as t,useState as o,useEffect as s,useCallback as r,lazy as n,useImperativeHandle as i,Suspense as c,useContext as l,useRef as a}from"react";import d from"@descope/web-js-sdk";const u=e.createContext(void 0),f={"x-descope-sdk-name":"react","x-descope-sdk-version":"0.1.2"},p="undefined"!=typeof window,h=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)},m=e=>(...t)=>{let o;try{o=e(...t)}catch(e){console.error(e)}return o};let g;const k=e=>{const t=d({...e,persistTokens:p,autoRefresh:p});return g=t,t};g=k({projectId:"temp pid"});const w=()=>p?g?.getSessionToken():(console.warn("Get session token is not supported in SSR"),""),U=()=>p?g?.getRefreshToken():(console.warn("Get refresh token is not supported in SSR"),""),b=m(((e=w(),t)=>g?.getJwtPermissions(e,t))),v=m(((e=w(),t)=>g?.getJwtRoles(e,t)));const y=({projectId:n,baseUrl:i,sessionTokenViaCookie:c,children:l})=>{const[a,d]=o(),[p,m]=o(),[g,w]=o(!1),[U,b]=o(!1),v=(({projectId:e,baseUrl:o,sessionTokenViaCookie:s})=>t((()=>{if(e)return k({projectId:e,baseUrl:o,sessionTokenViaCookie:s,baseHeaders:f,persistToken:!0,autoRefresh:!0})}),[e,o,s]))({projectId:n,baseUrl:i,sessionTokenViaCookie:c});s((()=>{if(v){const e=v.onSessionTokenChange(m),t=v.onUserChange(d);return()=>{e(),t()}}}),[v]);const y=r((()=>{b(!0),h(v?.refresh)().then((()=>{b(!1)}))}),[v]),E=r((()=>{w(!0),h(v.me)().then((()=>{w(!1)}))}),[v]),I=r(h(v?.logoutAll),[v]),S=r(h(v?.logout),[v]),j=t((()=>({fetchUser:E,user:a,isUserLoading:g,fetchSession:y,session:p,isSessionLoading:U,logout:S,logoutAll:I,projectId:n,baseUrl:i,setUser:d,setSession:m,sdk:v})),[E,a,g,y,p,U,S,I,n,i,d,m,v]);return e.createElement(u.Provider,{value:j},l)};y.defaultProps={baseUrl:"",children:void 0,sessionTokenViaCookie:!1};const E=n((async()=>((await import("@descope/web-component")).default.sdkConfigOverrides={baseHeaders:f},{default:({projectId:t,flowId:o,baseUrl:s,innerRef:r,tenant:n,theme:i,debug:c,telemetryKey:l,redirectUrl:a})=>e.createElement("descope-wc",{"project-id":t,"flow-id":o,"base-url":s,ref:r,tenant:n,theme:i,debug:c,telemetryKey:l,"redirect-url":a})}))),I=e.forwardRef((({flowId:t,onSuccess:n,onError:l,tenant:a,theme:d,debug:f,telemetryKey:p,redirectUrl:h},m)=>{const[g,k]=o(null);i(m,(()=>g));const{projectId:w,baseUrl:U,setUser:b,setSession:v,sdk:y}=e.useContext(u),I=r((async e=>{b(e.detail?.user);const t=e.detail?.sessionJwt;v(t),await y.httpClient.hooks.afterRequest({},new Response(JSON.stringify(e.detail))),n&&n(e)}),[b,v,n]);return s((()=>{const e=g;return e?.addEventListener("success",I),l&&e?.addEventListener("error",l),()=>{l&&e?.removeEventListener("error",l),e?.removeEventListener("success",I)}}),[g,l,I]),e.createElement("form",null,e.createElement(c,{fallback:null},e.createElement(E,{projectId:w,flowId:t,baseUrl:U,innerRef:k,tenant:a,theme:d,debug:f,telemetryKey:p,redirectUrl:h})))}));I.defaultProps={onError:void 0,onSuccess:void 0};const S=t=>e.createElement(I,{...t,flowId:"sign-in"}),j=t=>e.createElement(I,{...t,flowId:"sign-up"}),C=t=>e.createElement(I,{...t,flowId:"sign-up-or-in"});var R=()=>{const e=l(u);if(!e)throw Error("You can only use this hook in the context of <AuthProvider />");return e};const T=()=>{const{logout:e,logoutAll:o}=R();return t((()=>({logoutAll:o,logout:e})),[o,e])},L=()=>{const{session:e,isSessionLoading:o,fetchSession:r}=R(),n=a(o);return t((()=>{n.current=o}),[o]),t((()=>{e||o||(n.current=!0)}),[r]),s((()=>{e||o||r()}),[r]),{isSessionLoading:n.current,sessionToken:e,isAuthenticated:!!e}},x=()=>{const{user:e,fetchUser:r,isUserLoading:n,session:i}=R(),[c,l]=o(!1),d=a(n),u=t((()=>!e&&!n&&i&&!c),[r,i,c]);return t((()=>{d.current=n}),[n]),t((()=>{u&&(d.current=!0)}),[u]),s((()=>{u&&(l(!0),r())}),[u]),{isUserLoading:d.current,user:e}};export{y as AuthProvider,I as Descope,S as SignInFlow,j as SignUpFlow,C as SignUpOrInFlow,b as getJwtPermissions,v as getJwtRoles,U as getRefreshToken,w as getSessionToken,T as useDescope,L as useSession,x as useUser};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.js","sources":["../src/lib/hooks/Context.ts","../src/lib/constants.ts","../src/lib/utils.ts","../src/lib/sdk.ts","../src/lib/components/AuthProvider/AuthProvider.tsx","../src/lib/components/AuthProvider/useSdk.ts","../src/lib/components/Descope.tsx","../src/lib/components/DefaultFlows.tsx","../src/lib/hooks/useContext.ts","../src/lib/hooks/useDescope.ts","../src/lib/hooks/useSession.ts","../src/lib/hooks/useUser.ts"],"sourcesContent":["import React from 'react';\nimport { IContext } from '../types';\n\nconst Context = React.createContext<IContext>(undefined);\n\nexport default Context;\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 * 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","import createSdk from '@descope/web-js-sdk';\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: true,\n\t\tautoRefresh: 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 = () => sdkInstance?.getSessionToken();\nexport const getJwtPermissions = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtPermissions(token, tenant)\n);\nexport const getJwtRoles = wrapInTry(\n\t(token = getSessionToken(), tenant?: string) =>\n\t\tsdkInstance?.getJwtRoles(token, tenant)\n);\nexport const getRefreshToken = () => sdkInstance?.getRefreshToken();\n\nexport default createSdkWrapper;\n","import React, { FC, useCallback, useEffect, useMemo, useState } from 'react';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport useSdk from './useSdk';\nimport { withValidation } from '../../utils';\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 fetchSession = useCallback(() => {\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 logoutAll = useCallback(withValidation(sdk?.logoutAll), [sdk]);\n\n\tconst logout = useCallback(withValidation(sdk?.logout), [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\tlogout,\n\t\t\tlogoutAll,\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\tlogout,\n\t\t\tlogoutAll,\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 Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\nimport { baseHeaders } from '../constants';\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}) => (\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/>\n\t\t)\n\t};\n});\n\nconst Descope = React.forwardRef<HTMLElement, DescopeProps>(\n\t({ flowId, onSuccess, onError, tenant, theme, debug, telemetryKey }, ref) => {\n\t\tconst [innerRef, setInnerRef] = useState(null);\n\n\t\tuseImperativeHandle(ref, () => innerRef);\n\n\t\tconst { projectId, baseUrl, setUser, setSession, sdk } =\n\t\t\tReact.useContext(Context);\n\n\t\tconst handleSuccess = useCallback(\n\t\t\tasync (e: CustomEvent) => {\n\t\t\t\tsetUser(e.detail?.user);\n\t\t\t\tconst sessionJwt = e.detail?.sessionJwt;\n\t\t\t\tsetSession(sessionJwt);\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[setUser, setSession, 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/>\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 { IAuth } from '../types';\nimport useContext from './useContext';\n\nconst useDescope = (): IAuth => {\n\tconst { logout, logoutAll } = useContext();\n\n\treturn useMemo(\n\t\t() => ({\n\t\t\tlogoutAll,\n\t\t\tlogout\n\t\t}),\n\t\t[logoutAll, logout]\n\t);\n};\n\nexport default useDescope;\n","import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n\tconst { session, isSessionLoading, fetchSession } = useContext();\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 (!session && !isSessionLoading) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [fetchSession]);\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","baseHeaders","withValidation","fn","args","Error","wrapInTry","res","err","console","error","sdkInstance","createSdkWrapper","config","sdk","createSdk","persistTokens","autoRefresh","projectId","getSessionToken","getJwtPermissions","token","tenant","getJwtRoles","getRefreshToken","AuthProvider","baseUrl","sessionTokenViaCookie","children","user","setUser","useState","session","setSession","isUserLoading","setIsUserLoading","isSessionLoading","setIsSessionLoading","useMemo","persistToken","useSdk","useEffect","unsubscribeSessionToken","onSessionTokenChange","unsubscribeUser","onUserChange","fetchSession","useCallback","refresh","then","fetchUser","me","logoutAll","logout","value","createElement","Provider","defaultProps","DescopeWC","lazy","async","import","default","sdkConfigOverrides","flowId","innerRef","theme","debug","telemetryKey","ref","Descope","forwardRef","onSuccess","onError","setInnerRef","useImperativeHandle","useContext","handleSuccess","e","detail","sessionJwt","httpClient","hooks","afterRequest","Response","JSON","stringify","ele","addEventListener","removeEventListener","Suspense","fallback","SignInFlow","props","SignUpFlow","SignUpOrInFlow","ctx","useDescope","useSession","isLoading","useRef","current","sessionToken","isAuthenticated","useUser","isInit","setIsInit","shouldFetchUser"],"mappings":"iMAGA,MAAMA,EAAUC,EAAMC,mBAAwBC,GCAjCC,EAAc,CAC1B,qBAAsB,QACtB,wBAAyB,SCAbC,EACcC,GAC1B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EAAUE,QAAUjE,CAAgB,GAClC,CAACA,IAGJE,GAAQ,KACFN,GAAYI,IAChB+D,EAAUE,SAAU,EACpB,GACC,CAACvD,IAEJL,GAAU,KACJT,GAAYI,GAChBU,GACA,GACC,CAACA,IAEG,CACNV,iBAAkB+D,EAAUE,QAC5BC,aAActE,EACduE,kBAAmBvE,EACnB,EC7BIwE,EAAU,KACf,MAAM3E,KAAEA,EAAIqB,UAAEA,EAAShB,cAAEA,EAAaF,QAAEA,GAAY4C,KAC7C6B,EAAQC,GAAa3E,GAAS,GAI/BoE,EAAYC,EAAOlE,GAEnByE,EAAkBrE,GACvB,KAAOT,IAASK,GAAiBF,IAAYyE,GAC7C,CAACvD,EAAWlB,EAASyE,IAsBtB,OAlBAnE,GAAQ,KACP6D,EAAUE,QAAUnE,CAAa,GAC/B,CAACA,IAGJI,GAAQ,KACHqE,IACHR,EAAUE,SAAU,EACpB,GACC,CAACM,IAEJlE,GAAU,KACLkE,IACHD,GAAU,GACVxD,IACA,GACC,CAACyD,IAEG,CAAEzE,cAAeiE,EAAUE,QAASxE,OAAM"}
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":["../src/lib/hooks/Context.ts","../src/lib/constants.ts","../src/lib/utils.ts","../src/lib/sdk.ts","../src/lib/components/AuthProvider/AuthProvider.tsx","../src/lib/components/AuthProvider/useSdk.ts","../src/lib/components/Descope.tsx","../src/lib/components/DefaultFlows.tsx","../src/lib/hooks/useContext.ts","../src/lib/hooks/useDescope.ts","../src/lib/hooks/useSession.ts","../src/lib/hooks/useUser.ts"],"sourcesContent":["import React from 'react';\nimport { IContext } from '../types';\n\nconst Context = React.createContext<IContext>(undefined);\n\nexport default Context;\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","/**\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","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 default createSdkWrapper;\n","import React, { FC, useCallback, useEffect, useMemo, useState } from 'react';\nimport Context from '../../hooks/Context';\nimport { IContext, User } from '../../types';\nimport useSdk from './useSdk';\nimport { withValidation } from '../../utils';\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 fetchSession = useCallback(() => {\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 logoutAll = useCallback(withValidation(sdk?.logoutAll), [sdk]);\n\n\tconst logout = useCallback(withValidation(sdk?.logout), [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\tlogout,\n\t\t\tlogoutAll,\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\tlogout,\n\t\t\tlogoutAll,\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 Context from '../hooks/Context';\nimport { DescopeProps } from '../types';\nimport { baseHeaders } from '../constants';\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}) => (\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/>\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},\n\t\tref\n\t) => {\n\t\tconst [innerRef, setInnerRef] = useState(null);\n\n\t\tuseImperativeHandle(ref, () => innerRef);\n\n\t\tconst { projectId, baseUrl, setUser, setSession, sdk } =\n\t\t\tReact.useContext(Context);\n\n\t\tconst handleSuccess = useCallback(\n\t\t\tasync (e: CustomEvent) => {\n\t\t\t\tsetUser(e.detail?.user);\n\t\t\t\tconst sessionJwt = e.detail?.sessionJwt;\n\t\t\t\tsetSession(sessionJwt);\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[setUser, setSession, 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/>\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 { IAuth } from '../types';\nimport useContext from './useContext';\n\nconst useDescope = (): IAuth => {\n\tconst { logout, logoutAll } = useContext();\n\n\treturn useMemo(\n\t\t() => ({\n\t\t\tlogoutAll,\n\t\t\tlogout\n\t\t}),\n\t\t[logoutAll, logout]\n\t);\n};\n\nexport default useDescope;\n","import { useEffect, useMemo, useRef } from 'react';\nimport useContext from './useContext';\n\nconst useSession = () => {\n\tconst { session, isSessionLoading, fetchSession } = useContext();\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 (!session && !isSessionLoading) {\n\t\t\tisLoading.current = true;\n\t\t}\n\t}, [fetchSession]);\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","baseHeaders","IS_BROWSER","window","withValidation","fn","args","Error","wrapInTry","res","err","console","error","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","fetchSession","useCallback","refresh","then","fetchUser","me","logoutAll","logout","value","createElement","Provider","defaultProps","DescopeWC","lazy","async","import","default","sdkConfigOverrides","flowId","innerRef","theme","debug","telemetryKey","redirectUrl","ref","Descope","forwardRef","onSuccess","onError","setInnerRef","useImperativeHandle","useContext","handleSuccess","e","detail","sessionJwt","httpClient","hooks","afterRequest","Response","JSON","stringify","ele","addEventListener","removeEventListener","Suspense","fallback","SignInFlow","props","SignUpFlow","SignUpOrInFlow","ctx","useDescope","useSession","isLoading","useRef","current","sessionToken","isAuthenticated","useUser","isInit","setIsInit","shouldFetchUser"],"mappings":"iMAGA,MAAMA,EAAUC,EAAMC,mBAAwBC,GCAjCC,EAAc,CAC1B,qBAAsB,QACtB,wBAAyB,SAIbC,EAA+B,oBAAXC,OCJpBC,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,ECpBZ,IAAII,EAEJ,MAAMC,EACLC,IAEA,MAAMC,EAAMC,EAAU,IAClBF,EACHG,cAAehB,EACfiB,YAAajB,IAId,OAFAW,EAAcG,EAEPA,CAAG,EAUXH,EAAcC,EAAiB,CAAEM,UAAW,aAErC,MAAMC,EAAkB,IAC1BnB,EACIW,GAAaQ,mBAIrBV,QAAQW,KAAK,6CACN,IAGKC,EAAkB,IAC1BrB,EACIW,GAAaU,mBAGrBZ,QAAQW,KAAK,6CACN,IAGKE,EAAoBhB,GAChC,CAACiB,EAAQJ,IAAmBK,IAC3Bb,GAAaW,kBAAkBC,EAAOC,KAG3BC,EAAcnB,GAC1B,CAACiB,EAAQJ,IAAmBK,IAC3Bb,GAAac,YAAYF,EAAOC,KCtClC,MAAME,EAAuC,EAC5CR,YACAS,UACAC,wBACAC,eAEA,MAAOC,EAAMC,GAAWC,KACjBC,EAASC,GAAcF,KAEvBG,EAAeC,GAAoBJ,GAAS,IAC5CK,EAAkBC,GAAuBN,GAAS,GAEnDlB,ECpBQ,GACdI,YACAS,UACAC,2BAEAW,GAAQ,KACP,GAAKrB,EAGL,OAAOH,EAAU,CAChBG,YACAS,UACAC,wBACA7B,cACAy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,IAAKuB,EAAO9B,OAAO,kBCV5B,IAAAa,EAAe,KACd,MAAMoB,EAAMpB,EAAWnF,GACvB,IAAKuG,EACJ,MAAM7F,MACL,iEAIF,OAAO6F,CAAG,ECPL,MAAAC,EAAa,KAClB,MAAM7C,OAAEA,EAAMD,UAAEA,GAAcyB,IAE9B,OAAOvC,GACN,KAAO,CACNc,YACAC,YAED,CAACD,EAAWC,GACZ,ECVI8C,EAAa,KAClB,MAAMnE,QAAEA,EAAOI,iBAAEA,EAAgBU,aAAEA,GAAiB+B,IAI9CuB,EAAYC,EAAOjE,GAoBzB,OAjBAE,GAAQ,KACP8D,EAAUE,QAAUlE,CAAgB,GAClC,CAACA,IAGJE,GAAQ,KACFN,GAAYI,IAChBgE,EAAUE,SAAU,EACpB,GACC,CAACxD,IAEJL,GAAU,KACJT,GAAYI,GAChBU,GACA,GACC,CAACA,IAEG,CACNV,iBAAkBgE,EAAUE,QAC5BC,aAAcvE,EACdwE,kBAAmBxE,EACnB,EC7BIyE,EAAU,KACf,MAAM5E,KAAEA,EAAIqB,UAAEA,EAAShB,cAAEA,EAAaF,QAAEA,GAAY6C,KAC7C6B,EAAQC,GAAa5E,GAAS,GAI/BqE,EAAYC,EAAOnE,GAEnB0E,EAAkBtE,GACvB,KAAOT,IAASK,GAAiBF,IAAY0E,GAC7C,CAACxD,EAAWlB,EAAS0E,IAsBtB,OAlBApE,GAAQ,KACP8D,EAAUE,QAAUpE,CAAa,GAC/B,CAACA,IAGJI,GAAQ,KACHsE,IACHR,EAAUE,SAAU,EACpB,GACC,CAACM,IAEJnE,GAAU,KACLmE,IACHD,GAAU,GACVzD,IACA,GACC,CAAC0D,IAEG,CAAE1E,cAAekE,EAAUE,QAASzE,OAAM"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@descope/react-sdk",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Descope React SDK",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
]
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
|
-
"@descope/web-component": "0.1.
|
|
39
|
+
"@descope/web-component": "0.1.3",
|
|
40
40
|
"react-router-dom": "6.8.0"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
@@ -98,7 +98,7 @@
|
|
|
98
98
|
"typescript": "^4.5.3"
|
|
99
99
|
},
|
|
100
100
|
"peerDependencies": {
|
|
101
|
-
"@descope/web-js-sdk": "0.1.
|
|
101
|
+
"@descope/web-js-sdk": "0.1.2",
|
|
102
102
|
"@types/react": ">=16",
|
|
103
103
|
"react": ">=16"
|
|
104
104
|
}
|