@descope/core-js-sdk 2.12.1 → 2.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  type JSONSerializable = string | number | boolean | null | Array<JSONSerializable>;
2
2
  type FlowInput = Record<string, JSONSerializable>;
3
3
 
4
+ type NOTPResponse = {
5
+ pendingRef: string;
6
+ redirectUrl: string;
7
+ QRCode: string;
8
+ };
9
+
4
10
  type DeviceInfo = {
5
11
  webAuthnSupport?: boolean;
6
12
  };
@@ -248,6 +254,11 @@ type DeliveriesPhone<T extends Record<DeliveryPhone, SdkFn$1> | SdkFn$1> = {
248
254
  };
249
255
  /** Logger type that supports the given levels (debug, log, error) */
250
256
  type Logger = Pick<Console, 'debug' | 'log' | 'error' | 'warn'>;
257
+ /** Polling configuration for session waiting */
258
+ type WaitForSessionConfig = {
259
+ pollingIntervalMs: number;
260
+ timeoutMs: number;
261
+ };
251
262
  type UpdateOptions<T extends boolean> = {
252
263
  addToLoginIDs?: T;
253
264
  onMergeUseExisting?: T extends true ? boolean : never;
@@ -268,12 +279,6 @@ declare enum OAuthProviders {
268
279
  type StartFn = (redirectURL?: string, loginOptions?: LoginOptions, token?: string) => Promise<SdkResponse<URLResponse>>;
269
280
  type Providers<T> = Record<keyof typeof OAuthProviders, T>;
270
281
 
271
- /** Polling configuration for session waiting */
272
- type WaitForSessionConfig = {
273
- pollingIntervalMs: number;
274
- timeoutMs: number;
275
- };
276
-
277
282
  /** Request configuration including headers, query params and token */
278
283
  type HttpClientReqConfig = {
279
284
  headers?: HeadersInit;
@@ -378,6 +383,15 @@ type SdkFnWrapper<Z extends ResponseData> = <A extends any[], R extends Response
378
383
  */
379
384
  declare const wrapWith: <Obj extends object, Paths extends readonly SdkFnsPaths<Obj>[], WrapperData extends ResponseData>(obj: Obj, paths: Paths, wrapper: SdkFnWrapper<WrapperData>) => ReplacePaths<Obj, Paths, WrapperData>;
380
385
 
386
+ /** Polling configuration with defaults and normalizing checks */
387
+ declare const normalizeWaitForSessionConfig: ({ pollingIntervalMs, timeoutMs, }?: {
388
+ pollingIntervalMs?: number;
389
+ timeoutMs?: number;
390
+ }) => {
391
+ pollingIntervalMs: number;
392
+ timeoutMs: number;
393
+ };
394
+
381
395
  declare const _default$1: {
382
396
  TOO_MANY_REQUESTS: number;
383
397
  };
@@ -495,6 +509,12 @@ declare const _default: ((config: Omit<{
495
509
  verify: (loginId: string, code: string, loginOptions?: LoginOptions, token?: string) => Promise<SdkResponse<JWTResponse>>;
496
510
  update: (loginId: string, token?: string) => Promise<SdkResponse<TOTPResponse>>;
497
511
  };
512
+ notp: {
513
+ signUpOrIn: (loginId?: string, signUpOptions?: SignUpOptions) => Promise<SdkResponse<NOTPResponse>>;
514
+ signUp: (loginId?: string, user?: User, signUpOptions?: SignUpOptions) => Promise<SdkResponse<NOTPResponse>>;
515
+ signIn: (loginId?: string, loginOptions?: LoginOptions, token?: string) => Promise<SdkResponse<NOTPResponse>>;
516
+ waitForSession: (pendingRef: string, config?: WaitForSessionConfig) => Promise<SdkResponse<JWTResponse>>;
517
+ };
498
518
  webauthn: {
499
519
  signUp: {
500
520
  start: (loginId: string, origin: string, name: string) => Promise<SdkResponse<WebAuthnStartResponse>>;
@@ -549,4 +569,4 @@ type DeliveryMethod = keyof typeof DeliveryMethods;
549
569
  /** Type to restrict to valid OAuth providers */
550
570
  type OAuthProvider = keyof typeof OAuthProviders;
551
571
 
552
- export { type AccessKeyLoginOptions, type DeliveryMethod, type EnchantedLinkResponse, type ExchangeAccessKeyResponse, type FlowAction, type FlowResponse, FlowStatus, HTTPMethods, _default$1 as HttpStatusCodes, type JWTResponse, type LoginOptions, type OAuthProvider, type RequestConfig, type ResponseData, type SdkFnWrapper, type SdkResponse, type TOTPResponse, type URLResponse, type UserHistoryResponse, type UserResponse, _default as default, transformResponse, wrapWith };
572
+ export { type AccessKeyLoginOptions, type DeliveryMethod, type EnchantedLinkResponse, type ExchangeAccessKeyResponse, type FlowAction, type FlowResponse, FlowStatus, HTTPMethods, _default$1 as HttpStatusCodes, type JWTResponse, type LoginOptions, type OAuthProvider, type RequestConfig, type ResponseData, type SdkFnWrapper, type SdkResponse, type TOTPResponse, type URLResponse, type UserHistoryResponse, type UserResponse, _default as default, normalizeWaitForSessionConfig, transformResponse, wrapWith };
package/dist/index.esm.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"jwt-decode";var t={exchange:"/v1/auth/accesskey/exchange"},n={verify:"/v1/auth/otp/verify",signIn:"/v1/auth/otp/signin",signUp:"/v1/auth/otp/signup",update:{email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},signUpOrIn:"/v1/auth/otp/signup-in"},s={verify:"/v1/auth/magiclink/verify",signIn:"/v1/auth/magiclink/signin",signUp:"/v1/auth/magiclink/signup",update:{email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},signUpOrIn:"/v1/auth/magiclink/signup-in"},i={verify:"/v1/auth/enchantedlink/verify",signIn:"/v1/auth/enchantedlink/signin",signUp:"/v1/auth/enchantedlink/signup",session:"/v1/auth/enchantedlink/pending-session",update:{email:"/v1/auth/enchantedlink/update/email"},signUpOrIn:"/v1/auth/enchantedlink/signup-in"},o={start:"/v1/auth/oauth/authorize",exchange:"/v1/auth/oauth/exchange",startNative:"v1/auth/oauth/native/start",finishNative:"v1/auth/oauth/native/finish"},a={start:"/v1/auth/saml/authorize",exchange:"/v1/auth/saml/exchange"},r={verify:"/v1/auth/totp/verify",signUp:"/v1/auth/totp/signup",update:"/v1/auth/totp/update"},d={signUp:{start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},signIn:{start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},signUpOrIn:{start:"/v1/auth/webauthn/signup-in/start"},update:{start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"}},l={signUp:"/v1/auth/password/signup",signIn:"/v1/auth/password/signin",sendReset:"/v1/auth/password/reset",update:"/v1/auth/password/update",replace:"/v1/auth/password/replace",policy:"/v1/auth/password/policy"},u="/v1/auth/refresh",p="/v1/auth/tenant/select",c="/v1/auth/logout",g="/v1/auth/logoutall",h="/v1/auth/me",v="/v1/auth/me/history",f={start:"/v1/flow/start",next:"/v1/flow/next"};const m="<region>",I=`https://api.${m}descope.com`,b=1e3,y=6e5,k=()=>{const e={};return{headers(t){const n="function"==typeof t.entries?Object.fromEntries(t.entries()):t;return e.Headers=JSON.stringify(n),this},body(t){return e.Body=t,this},url(t){return e.Url=t.toString(),this},method(t){return e.Method=t,this},title(t){return e.Title=t,this},status(t){return e.Status=t,this},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}},O=(e,t)=>{const n=(e=>async(...t)=>{const n=await e(...t),s=await n.text();return n.text=()=>Promise.resolve(s),n.json=()=>Promise.resolve(JSON.parse(s)),n.clone=()=>n,n})(t||fetch);return n||null==e||e.warn("Fetch is not defined, you will not be able to send http requests, if you are running in a test, make sure fetch is defined globally"),e?async(...t)=>{if(!n)throw Error("Cannot send http request, fetch is not defined, if you are running in a test, make sure fetch is defined globally");e.log((e=>k().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const s=await n(...t);return e[s.ok?"log":"error"](await(async e=>{const t=await e.text();return k().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(s)),s}:n};var w;!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}(w||(w={}));var j={TOO_MANY_REQUESTS:429};function U(e,t,n){var s;let i=R(e);t&&(i=null===(s=null==i?void 0:i.tenants)||void 0===s?void 0:s[t]);const o=null==i?void 0:i[n];return Array.isArray(o)?o:[]}function R(t){if("string"!=typeof t||!t)throw new Error("Invalid token provided");return e(t)}function P(e){const{exp:t}=R(e);return(new Date).getTime()/1e3>t}function x(e){let t=R(e);const n=Object.keys(null==t?void 0:t.tenants);return Array.isArray(n)?n:[]}function q(e,t){return U(e,t,"permissions")}function $(e,t){return U(e,t,"roles")}const E=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function A(e,t){var n;const s=await e,i={code:s.status,ok:s.ok,response:s},o=await s.clone().json();return s.ok?i.data=t?t(o):o:(i.error=o,s.status===j.TOO_MANY_REQUESTS&&Object.assign(i.error,{retryAfter:Number.parseInt(null===(n=s.headers)||void 0===n?void 0:n.get("retry-after"))||0})),i}const S=(...e)=>new Headers(e.reduce(((e,t)=>{const n=(e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t);return n.reduce(((t,[n,s])=>(e[n]=s,e)),e),e}),{})),T=e=>void 0===e?void 0:JSON.stringify(e),M=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},N=({baseUrl:e,projectId:t,baseConfig:n,logger:s,hooks:i,cookiePolicy:o,fetch:a})=>{const r=O(s,a),d=async s=>{const a=(null==i?void 0:i.beforeRequest)?i.beforeRequest(s):s,{path:d,body:l,headers:u,queryParams:p,method:c,token:g}=a,h={headers:S(M(t,g),{"x-descope-sdk-name":"core-js","x-descope-sdk-version":"2.12.1"},(null==n?void 0:n.baseHeaders)||{},u),method:c,body:T(l)};null!==o&&(h.credentials=o||"include");const v=await r((({path:e,baseUrl:t,queryParams:n,projectId:s})=>{const i=s.slice(1,-27);t=t.replace(m,i?i+".":"");const o=new URL(t);return o.pathname=E(o.pathname,e),n&&(o.search=new URLSearchParams(n).toString()),o})({path:d,baseUrl:e,queryParams:p,projectId:t}),h);return(null==i?void 0:i.afterRequest)&&await i.afterRequest(s,null==v?void 0:v.clone()),v};return{get:(e,{headers:t,queryParams:n,token:s}={})=>d({path:e,headers:t,queryParams:n,body:void 0,method:w.get,token:s}),post:(e,t,{headers:n,queryParams:s,token:i}={})=>d({path:e,headers:n,queryParams:s,body:t,method:w.post,token:i}),put:(e,t,{headers:n,queryParams:s,token:i}={})=>d({path:e,headers:n,queryParams:s,body:t,method:w.put,token:i}),delete:(e,{headers:t,queryParams:n,token:s}={})=>d({path:e,headers:t,queryParams:n,body:void 0,method:w.delete,token:s}),hooks:i}},L=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),z=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),H=e=>t=>e.test(t),J=H(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),C=H(/^\+[1-9]{1}[0-9]{3,14}$/),_=(e,t)=>n=>z(...t).validate(((e,t,n)=>{const s=(Array.isArray(t)?t.join("."):String(t)).replace(/\[\\?("|')?(\w|d)+\\?("|')?\]/g,((e,t,n)=>"."+n)).split("."),i=s.length;let o=0,a=e===Object(e)?e:void 0;for(;null!=a&&o<i;)a=a[s[o++]];return o&&o===i&&void 0!==a?a:n})(n,e)),D=L(J,'"{val}" is not a valid email'),Z=L(C,'"{val}" is not a valid phone number'),B=L((F=1,e=>e.length>=F),"Minimum length is 1");var F;const K=L((e=>"string"==typeof e),"Input is not a string"),Q=L((e=>void 0===e),"Input is defined"),V=(Y=[K(),Q()],G="Input is not a string or undefined",(e=G)=>t=>{const n=Y.filter((e=>e(t)));return!(n.length<Y.length)&&(e?e.replace("{val}",t):n.join(" OR "))});var Y,G;const W=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>z(...e).validate(n[t]))),t(...n)),X=e=>[K(`"${e}" must be a string`),B(`"${e}" must not be empty`)],ee=e=>[K(`"${e}" must be a string`),D()],te=e=>[K(`"${e}" must be a string`),Z()],ne=W(X("accessKey")),se=e=>({exchange:ne(((n,s)=>A(e.post(t.exchange,{loginOptions:s},{token:n}))))});var ie,oe;!function(e){e.sms="sms",e.voice="voice",e.whatsapp="whatsapp"}(ie||(ie={})),function(e){e.email="email"}(oe||(oe={}));const ae=Object.assign(Object.assign({},ie),oe);var re;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(re||(re={}));const de=X("loginId"),le=W(X("token")),ue=W(de),pe=W(X("pendingRef")),ce=W(de,ee("email")),ge=e=>({verify:le((t=>A(e.post(i.verify,{token:t})))),signIn:ue(((t,n,s,o)=>A(e.post(E(i.signIn,ae.email),{loginId:t,URI:n,loginOptions:s},{token:o})))),signUpOrIn:ue(((t,n,s)=>A(e.post(E(i.signUpOrIn,ae.email),{loginId:t,URI:n,loginOptions:s})))),signUp:ue(((t,n,s,o)=>A(e.post(E(i.signUp,ae.email),{loginId:t,URI:n,user:s,loginOptions:o})))),waitForSession:pe(((t,n)=>new Promise((s=>{const{pollingIntervalMs:o,timeoutMs:a}=(({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||b,b),timeoutMs:Math.min(t||y,y)}))(n);let r;const d=setInterval((async()=>{const n=await e.post(i.session,{pendingRef:t});n.ok&&(clearInterval(d),r&&clearTimeout(r),s(A(Promise.resolve(n))))}),o);r=setTimeout((()=>{s({error:{errorDescription:`Session polling timeout exceeded: ${a}ms`,errorCode:"0"},ok:!1}),clearInterval(d)}),a)})))),update:{email:ce(((t,n,s,o,a)=>A(e.post(i.update.email,Object.assign({loginId:t,email:n,URI:s},a),{token:o}))))}}),he=W(X("flowId")),ve=W(X("executionId"),X("stepId"),X("interactionId")),fe=e=>({start:he(((t,n,s,i,o,a,r)=>A(e.post(f.start,{flowId:t,options:n,conditionInteractionId:s,interactionId:i,version:o,componentsVersion:a,input:r})))),next:ve(((t,n,s,i,o,a)=>A(e.post(f.next,{executionId:t,stepId:n,interactionId:s,version:i,componentsVersion:o,input:a}))))}),me=X("loginId"),Ie=W(X("token")),be=W(me),ye=W(me,te("phone")),ke=W(me,ee("email")),Oe=Object.keys(ae).filter((e=>e!==ie.voice)),we=e=>({verify:Ie((t=>A(e.post(s.verify,{token:t})))),signIn:Oe.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:be(((t,i,o,a)=>A(e.post(E(s.signIn,n),{loginId:t,URI:i,loginOptions:o},{token:a}))))})),{}),signUp:Oe.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:be(((t,i,o,a)=>A(e.post(E(s.signUp,n),{loginId:t,URI:i,user:o,loginOptions:a}))))})),{}),signUpOrIn:Oe.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:be(((t,i,o)=>A(e.post(E(s.signUpOrIn,n),{loginId:t,URI:i,loginOptions:o}))))})),{}),update:{email:ke(((t,n,i,o,a)=>A(e.post(s.update.email,Object.assign({loginId:t,email:n,URI:i},a),{token:o})))),phone:Object.keys(ie).filter((e=>e!==ie.voice)).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ye(((t,i,o,a,r)=>A(e.post(E(s.update.phone,n),Object.assign({loginId:t,phone:i,URI:o},r),{token:a}))))})),{})}});var je;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple",e.discord="discord",e.linkedin="linkedin",e.slack="slack"}(je||(je={}));const Ue=W(X("code")),Re=e=>({start:Object.assign(((t,n,s,i)=>A(e.post(o.start,s||{},{queryParams:Object.assign({provider:t},n&&{redirectURL:n}),token:i}))),Object.keys(je).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,s,i)=>A(e.post(o.start,s||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:i}))})),{})),exchange:Ue((t=>A(e.post(o.exchange,{code:t})))),startNative:(t,n)=>A(e.post(o.startNative,{provider:t,loginOptions:n})),finishNative:(t,n,s,i,a)=>A(e.post(o.finishNative,{provider:t,stateId:n,user:s,code:i,idToken:a}))}),Pe=X("loginId"),xe=W(Pe,X("code")),qe=W(Pe),$e=W(Pe,te("phone")),Ee=W(Pe,ee("email")),Ae=e=>({verify:Object.keys(ae).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:xe(((t,i)=>A(e.post(E(n.verify,s),{code:i,loginId:t}))))})),{}),signIn:Object.keys(ae).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:qe(((t,i,o)=>A(e.post(E(n.signIn,s),{loginId:t,loginOptions:i},{token:o}))))})),{}),signUp:Object.keys(ae).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:qe(((t,i,o)=>A(e.post(E(n.signUp,s),{loginId:t,user:i,loginOptions:o}))))})),{}),signUpOrIn:Object.keys(ae).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:qe(((t,i)=>A(e.post(E(n.signUpOrIn,s),{loginId:t,loginOptions:i}))))})),{}),update:{email:Ee(((t,s,i,o)=>A(e.post(n.update.email,Object.assign({loginId:t,email:s},o),{token:i})))),phone:Object.keys(ie).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:$e(((t,i,o,a)=>A(e.post(E(n.update.phone,s),Object.assign({loginId:t,phone:i},a),{token:o}))))})),{})}}),Se=W(X("tenant")),Te=W(X("code")),Me=e=>({start:Se(((t,n,s,i)=>A(e.post(a.start,s||{},{queryParams:{tenant:t,redirectURL:n},token:i})))),exchange:Te((t=>A(e.post(a.exchange,{code:t}))))}),Ne=X("loginId"),Le=W(Ne,X("code")),ze=W(Ne),He=W(Ne),Je=e=>({signUp:ze(((t,n)=>A(e.post(r.signUp,{loginId:t,user:n})))),verify:Le(((t,n,s,i)=>A(e.post(r.verify,{loginId:t,code:n,loginOptions:s},{token:i})))),update:He(((t,n)=>A(e.post(r.update,{loginId:t},{token:n}))))}),Ce=X("loginId"),_e=X("newPassword"),De=W(Ce,X("password")),Ze=W(Ce),Be=W(Ce,_e),Fe=W(Ce,X("oldPassword"),_e),Ke=e=>({signUp:De(((t,n,s)=>A(e.post(l.signUp,{loginId:t,password:n,user:s})))),signIn:De(((t,n)=>A(e.post(l.signIn,{loginId:t,password:n})))),sendReset:Ze(((t,n,s)=>A(e.post(l.sendReset,{loginId:t,redirectUrl:n,templateOptions:s})))),update:Be(((t,n,s)=>A(e.post(l.update,{loginId:t,newPassword:n},{token:s})))),replace:Fe(((t,n,s)=>A(e.post(l.replace,{loginId:t,oldPassword:n,newPassword:s})))),policy:()=>A(e.get(l.policy))}),Qe=[K(`"${"loginId"}" must be a string`)];const Ve=X("loginId"),Ye=X("origin"),Ge=W(Ve,Ye,X("name")),We=W(Ve,Ye),Xe=W(Qe,Ye),et=W(Ve,Ye,X("token")),tt=W(X("transactionId"),X("response")),nt=e=>({signUp:{start:Ge(((t,n,s)=>A(e.post(d.signUp.start,{user:{loginId:t,name:s},origin:n})))),finish:tt(((t,n)=>A(e.post(d.signUp.finish,{transactionId:t,response:n}))))},signIn:{start:Xe(((t,n,s,i)=>A(e.post(d.signIn.start,{loginId:t,origin:n,loginOptions:s},{token:i})))),finish:tt(((t,n)=>A(e.post(d.signIn.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:We(((t,n)=>A(e.post(d.signUpOrIn.start,{loginId:t,origin:n}))))},update:{start:et(((t,n,s)=>A(e.post(d.update.start,{loginId:t,origin:n},{token:s})))),finish:tt(((t,n)=>A(e.post(d.update.finish,{transactionId:t,response:n}))))}}),st=W(X("token")),it=W((e=>[V(`"${e}" must be string or undefined`)])("token"));var ot,at;var rt=W([(ot="projectId",at=X("projectId"),L(_(ot,at))())])((e=>t=>e(Object.assign(Object.assign({},t),{hooks:{beforeRequest:e=>{var n;const s=[].concat((null===(n=t.hooks)||void 0===n?void 0:n.beforeRequest)||[]);return null==s?void 0:s.reduce(((e,t)=>t(e)),e)},afterRequest:async(e,n)=>{var s;const i=[].concat((null===(s=t.hooks)||void 0===s?void 0:s.afterRequest)||[]);(await Promise.allSettled(null==i?void 0:i.map((t=>t(e,null==n?void 0:n.clone()))))).forEach((e=>{var n;return"rejected"===e.status&&(null===(n=t.logger)||void 0===n?void 0:n.error(e.reason))}))}}})))((({projectId:e,logger:t,baseUrl:n,hooks:s,cookiePolicy:i,baseHeaders:o={},fetch:a})=>{return r=N({baseUrl:n||I,projectId:e,logger:t,hooks:s,cookiePolicy:i,baseConfig:{baseHeaders:o},fetch:a}),{accessKey:se(r),otp:Ae(r),magicLink:we(r),enchantedLink:ge(r),oauth:Re(r),saml:Me(r),totp:Je(r),webauthn:nt(r),password:Ke(r),flow:fe(r),refresh:it((e=>A(r.post(u,{},{token:e})))),selectTenant:W([K("tenantId")],[V('"token" must be string or undefined')])(((e,t)=>A(r.post(p,{tenant:e},{token:t})))),logout:it((e=>A(r.post(c,{},{token:e})))),logoutAll:it((e=>A(r.post(g,{},{token:e})))),me:it((e=>A(r.get(h,{token:e})))),history:it((e=>A(r.get(v,{token:e})))),isJwtExpired:st(P),getTenants:st(x),getJwtPermissions:st(q),getJwtRoles:st($),httpClient:r};var r})));const dt=(e,t,n)=>(t.forEach((t=>{const s=t.split(".");let i=s.shift(),o=e;for(;s.length>0;){if(o=o[i],!i||!o)throw Error(`Invalid path "${t}", "${i}" is missing or has no value`);i=s.shift()}if("function"!=typeof o[i])throw Error(`"${t}" is not a function`);const a=o[i];o[i]=n(a)})),e);var lt=Object.assign(rt,{DeliveryMethods:ae});export{j as HttpStatusCodes,lt as default,A as transformResponse,dt as wrapWith};
1
+ import e from"jwt-decode";var t={exchange:"/v1/auth/accesskey/exchange"},n={verify:"/v1/auth/otp/verify",signIn:"/v1/auth/otp/signin",signUp:"/v1/auth/otp/signup",update:{email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},signUpOrIn:"/v1/auth/otp/signup-in"},s={verify:"/v1/auth/magiclink/verify",signIn:"/v1/auth/magiclink/signin",signUp:"/v1/auth/magiclink/signup",update:{email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},signUpOrIn:"/v1/auth/magiclink/signup-in"},i={verify:"/v1/auth/enchantedlink/verify",signIn:"/v1/auth/enchantedlink/signin",signUp:"/v1/auth/enchantedlink/signup",session:"/v1/auth/enchantedlink/pending-session",update:{email:"/v1/auth/enchantedlink/update/email"},signUpOrIn:"/v1/auth/enchantedlink/signup-in"},o={start:"/v1/auth/oauth/authorize",exchange:"/v1/auth/oauth/exchange",startNative:"v1/auth/oauth/native/start",finishNative:"v1/auth/oauth/native/finish"},a={start:"/v1/auth/saml/authorize",exchange:"/v1/auth/saml/exchange"},r={verify:"/v1/auth/totp/verify",signUp:"/v1/auth/totp/signup",update:"/v1/auth/totp/update"},p={signIn:"/v1/auth/notp/whatsapp/signin",signUp:"/v1/auth/notp/whatsapp/signup",signUpOrIn:"/v1/auth/notp/whatsapp/signup-in",session:"/v1/auth/notp/pending-session"},d={signUp:{start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},signIn:{start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},signUpOrIn:{start:"/v1/auth/webauthn/signup-in/start"},update:{start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"}},l={signUp:"/v1/auth/password/signup",signIn:"/v1/auth/password/signin",sendReset:"/v1/auth/password/reset",update:"/v1/auth/password/update",replace:"/v1/auth/password/replace",policy:"/v1/auth/password/policy"},u="/v1/auth/refresh",g="/v1/auth/tenant/select",c="/v1/auth/logout",h="/v1/auth/logoutall",v="/v1/auth/me",f="/v1/auth/me/history",I={start:"/v1/flow/start",next:"/v1/flow/next"};const m="<region>",b=`https://api.${m}descope.com`,k=1e3,y=6e5,O=()=>{const e={};return{headers(t){const n="function"==typeof t.entries?Object.fromEntries(t.entries()):t;return e.Headers=JSON.stringify(n),this},body(t){return e.Body=t,this},url(t){return e.Url=t.toString(),this},method(t){return e.Method=t,this},title(t){return e.Title=t,this},status(t){return e.Status=t,this},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}},w=(e,t)=>{const n=(e=>async(...t)=>{const n=await e(...t),s=await n.text();return n.text=()=>Promise.resolve(s),n.json=()=>Promise.resolve(JSON.parse(s)),n.clone=()=>n,n})(t||fetch);return n||null==e||e.warn("Fetch is not defined, you will not be able to send http requests, if you are running in a test, make sure fetch is defined globally"),e?async(...t)=>{if(!n)throw Error("Cannot send http request, fetch is not defined, if you are running in a test, make sure fetch is defined globally");e.log((e=>O().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const s=await n(...t);return e[s.ok?"log":"error"](await(async e=>{const t=await e.text();return O().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(s)),s}:n};var j;!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}(j||(j={}));var U={TOO_MANY_REQUESTS:429};function R(e,t,n){var s;let i=P(e);t&&(i=null===(s=null==i?void 0:i.tenants)||void 0===s?void 0:s[t]);const o=null==i?void 0:i[n];return Array.isArray(o)?o:[]}function P(t){if("string"!=typeof t||!t)throw new Error("Invalid token provided");return e(t)}function x(e){const{exp:t}=P(e);return(new Date).getTime()/1e3>t}function q(e){let t=P(e);const n=Object.keys(null==t?void 0:t.tenants);return Array.isArray(n)?n:[]}function $(e,t){return R(e,t,"permissions")}function E(e,t){return R(e,t,"roles")}const S=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function T(e,t){var n;const s=await e,i={code:s.status,ok:s.ok,response:s},o=await s.clone().json();return s.ok?i.data=t?t(o):o:(i.error=o,s.status===U.TOO_MANY_REQUESTS&&Object.assign(i.error,{retryAfter:Number.parseInt(null===(n=s.headers)||void 0===n?void 0:n.get("retry-after"))||0})),i}const A=(...e)=>new Headers(e.reduce(((e,t)=>{const n=(e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t);return n.reduce(((t,[n,s])=>(e[n]=s,e)),e),e}),{})),M=e=>void 0===e?void 0:JSON.stringify(e),N=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},L=({baseUrl:e,projectId:t,baseConfig:n,logger:s,hooks:i,cookiePolicy:o,fetch:a})=>{const r=w(s,a),p=async s=>{const a=(null==i?void 0:i.beforeRequest)?i.beforeRequest(s):s,{path:p,body:d,headers:l,queryParams:u,method:g,token:c}=a,h={headers:A(N(t,c),{"x-descope-sdk-name":"core-js","x-descope-sdk-version":"2.13.0"},(null==n?void 0:n.baseHeaders)||{},l),method:g,body:M(d)};null!==o&&(h.credentials=o||"include");const v=await r((({path:e,baseUrl:t,queryParams:n,projectId:s})=>{const i=s.slice(1,-27);t=t.replace(m,i?i+".":"");const o=new URL(t);return o.pathname=S(o.pathname,e),n&&(o.search=new URLSearchParams(n).toString()),o})({path:p,baseUrl:e,queryParams:u,projectId:t}),h);return(null==i?void 0:i.afterRequest)&&await i.afterRequest(s,null==v?void 0:v.clone()),v};return{get:(e,{headers:t,queryParams:n,token:s}={})=>p({path:e,headers:t,queryParams:n,body:void 0,method:j.get,token:s}),post:(e,t,{headers:n,queryParams:s,token:i}={})=>p({path:e,headers:n,queryParams:s,body:t,method:j.post,token:i}),put:(e,t,{headers:n,queryParams:s,token:i}={})=>p({path:e,headers:n,queryParams:s,body:t,method:j.put,token:i}),delete:(e,{headers:t,queryParams:n,token:s}={})=>p({path:e,headers:t,queryParams:n,body:void 0,method:j.delete,token:s}),hooks:i}},z=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),C=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),H=e=>t=>e.test(t),J=H(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),D=H(/^\+[1-9]{1}[0-9]{3,14}$/),_=(e,t)=>n=>C(...t).validate(((e,t,n)=>{const s=(Array.isArray(t)?t.join("."):String(t)).replace(/\[\\?("|')?(\w|d)+\\?("|')?\]/g,((e,t,n)=>"."+n)).split("."),i=s.length;let o=0,a=e===Object(e)?e:void 0;for(;null!=a&&o<i;)a=a[s[o++]];return o&&o===i&&void 0!==a?a:n})(n,e)),F=z(J,'"{val}" is not a valid email'),Z=z(D,'"{val}" is not a valid phone number'),B=z((K=1,e=>e.length>=K),"Minimum length is 1");var K;const Q=z((e=>"string"==typeof e),"Input is not a string"),V=z((e=>void 0===e),"Input is defined"),Y=(G=[Q(),V()],W="Input is not a string or undefined",(e=W)=>t=>{const n=G.filter((e=>e(t)));return!(n.length<G.length)&&(e?e.replace("{val}",t):n.join(" OR "))});var G,W;const X=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>C(...e).validate(n[t]))),t(...n)),ee=e=>[Q(`"${e}" must be a string`)],te=e=>[Q(`"${e}" must be a string`),B(`"${e}" must not be empty`)],ne=e=>[Q(`"${e}" must be a string`),F()],se=e=>[Q(`"${e}" must be a string`),Z()],ie=X(te("accessKey")),oe=e=>({exchange:ie(((n,s)=>T(e.post(t.exchange,{loginOptions:s},{token:n}))))}),ae=(e,t,n)=>(t.forEach((t=>{const s=t.split(".");let i=s.shift(),o=e;for(;s.length>0;){if(o=o[i],!i||!o)throw Error(`Invalid path "${t}", "${i}" is missing or has no value`);i=s.shift()}if("function"!=typeof o[i])throw Error(`"${t}" is not a function`);const a=o[i];o[i]=n(a)})),e),re=({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||k,k),timeoutMs:Math.min(t||y,y)});var pe,de;!function(e){e.sms="sms",e.voice="voice",e.whatsapp="whatsapp"}(pe||(pe={})),function(e){e.email="email"}(de||(de={}));const le=Object.assign(Object.assign({},pe),de);var ue;!function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(ue||(ue={}));const ge=te("loginId"),ce=X(te("token")),he=X(ge),ve=X(te("pendingRef")),fe=X(ge,ne("email")),Ie=e=>({verify:ce((t=>T(e.post(i.verify,{token:t})))),signIn:he(((t,n,s,o)=>T(e.post(S(i.signIn,le.email),{loginId:t,URI:n,loginOptions:s},{token:o})))),signUpOrIn:he(((t,n,s)=>T(e.post(S(i.signUpOrIn,le.email),{loginId:t,URI:n,loginOptions:s})))),signUp:he(((t,n,s,o)=>T(e.post(S(i.signUp,le.email),{loginId:t,URI:n,user:s,loginOptions:o})))),waitForSession:ve(((t,n)=>new Promise((s=>{const{pollingIntervalMs:o,timeoutMs:a}=re(n);let r;const p=setInterval((async()=>{const n=await e.post(i.session,{pendingRef:t});n.ok&&(clearInterval(p),r&&clearTimeout(r),s(T(Promise.resolve(n))))}),o);r=setTimeout((()=>{s({error:{errorDescription:`Session polling timeout exceeded: ${a}ms`,errorCode:"0"},ok:!1}),clearInterval(p)}),a)})))),update:{email:fe(((t,n,s,o,a)=>T(e.post(i.update.email,Object.assign({loginId:t,email:n,URI:s},a),{token:o}))))}}),me=X(te("flowId")),be=X(te("executionId"),te("stepId"),te("interactionId")),ke=e=>({start:me(((t,n,s,i,o,a,r)=>T(e.post(I.start,{flowId:t,options:n,conditionInteractionId:s,interactionId:i,version:o,componentsVersion:a,input:r})))),next:be(((t,n,s,i,o,a)=>T(e.post(I.next,{executionId:t,stepId:n,interactionId:s,version:i,componentsVersion:o,input:a}))))}),ye=te("loginId"),Oe=X(te("token")),we=X(ye),je=X(ye,se("phone")),Ue=X(ye,ne("email")),Re=Object.keys(le).filter((e=>e!==pe.voice)),Pe=e=>({verify:Oe((t=>T(e.post(s.verify,{token:t})))),signIn:Re.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:we(((t,i,o,a)=>T(e.post(S(s.signIn,n),{loginId:t,URI:i,loginOptions:o},{token:a}))))})),{}),signUp:Re.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:we(((t,i,o,a)=>T(e.post(S(s.signUp,n),{loginId:t,URI:i,user:o,loginOptions:a}))))})),{}),signUpOrIn:Re.reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:we(((t,i,o)=>T(e.post(S(s.signUpOrIn,n),{loginId:t,URI:i,loginOptions:o}))))})),{}),update:{email:Ue(((t,n,i,o,a)=>T(e.post(s.update.email,Object.assign({loginId:t,email:n,URI:i},a),{token:o})))),phone:Object.keys(pe).filter((e=>e!==pe.voice)).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:je(((t,i,o,a,r)=>T(e.post(S(s.update.phone,n),Object.assign({loginId:t,phone:i,URI:o},r),{token:a}))))})),{})}});var xe;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple",e.discord="discord",e.linkedin="linkedin",e.slack="slack"}(xe||(xe={}));const qe=X(te("code")),$e=e=>({start:Object.assign(((t,n,s,i)=>T(e.post(o.start,s||{},{queryParams:Object.assign({provider:t},n&&{redirectURL:n}),token:i}))),Object.keys(xe).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:(t,s,i)=>T(e.post(o.start,s||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:i}))})),{})),exchange:qe((t=>T(e.post(o.exchange,{code:t})))),startNative:(t,n)=>T(e.post(o.startNative,{provider:t,loginOptions:n})),finishNative:(t,n,s,i,a)=>T(e.post(o.finishNative,{provider:t,stateId:n,user:s,code:i,idToken:a}))}),Ee=te("loginId"),Se=X(Ee,te("code")),Te=X(Ee),Ae=X(Ee,se("phone")),Me=X(Ee,ne("email")),Ne=e=>({verify:Object.keys(le).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:Se(((t,i)=>T(e.post(S(n.verify,s),{code:i,loginId:t}))))})),{}),signIn:Object.keys(le).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:Te(((t,i,o)=>T(e.post(S(n.signIn,s),{loginId:t,loginOptions:i},{token:o}))))})),{}),signUp:Object.keys(le).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:Te(((t,i,o)=>T(e.post(S(n.signUp,s),{loginId:t,user:i,loginOptions:o}))))})),{}),signUpOrIn:Object.keys(le).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:Te(((t,i)=>T(e.post(S(n.signUpOrIn,s),{loginId:t,loginOptions:i}))))})),{}),update:{email:Me(((t,s,i,o)=>T(e.post(n.update.email,Object.assign({loginId:t,email:s},o),{token:i})))),phone:Object.keys(pe).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:Ae(((t,i,o,a)=>T(e.post(S(n.update.phone,s),Object.assign({loginId:t,phone:i},a),{token:o}))))})),{})}}),Le=X(te("tenant")),ze=X(te("code")),Ce=e=>({start:Le(((t,n,s,i)=>T(e.post(a.start,s||{},{queryParams:{tenant:t,redirectURL:n},token:i})))),exchange:ze((t=>T(e.post(a.exchange,{code:t}))))}),He=te("loginId"),Je=X(He,te("code")),De=X(He),_e=X(He),Fe=e=>({signUp:De(((t,n)=>T(e.post(r.signUp,{loginId:t,user:n})))),verify:Je(((t,n,s,i)=>T(e.post(r.verify,{loginId:t,code:n,loginOptions:s},{token:i})))),update:_e(((t,n)=>T(e.post(r.update,{loginId:t},{token:n}))))}),Ze=te("loginId"),Be=te("newPassword"),Ke=X(Ze,te("password")),Qe=X(Ze),Ve=X(Ze,Be),Ye=X(Ze,te("oldPassword"),Be),Ge=e=>({signUp:Ke(((t,n,s)=>T(e.post(l.signUp,{loginId:t,password:n,user:s})))),signIn:Ke(((t,n)=>T(e.post(l.signIn,{loginId:t,password:n})))),sendReset:Qe(((t,n,s)=>T(e.post(l.sendReset,{loginId:t,redirectUrl:n,templateOptions:s})))),update:Ve(((t,n,s)=>T(e.post(l.update,{loginId:t,newPassword:n},{token:s})))),replace:Ye(((t,n,s)=>T(e.post(l.replace,{loginId:t,oldPassword:n,newPassword:s})))),policy:()=>T(e.get(l.policy))}),We=ee("loginId"),Xe=te("loginId"),et=te("origin"),tt=X(Xe,et,te("name")),nt=X(Xe,et),st=X(We,et),it=X(Xe,et,te("token")),ot=X(te("transactionId"),te("response")),at=e=>({signUp:{start:tt(((t,n,s)=>T(e.post(d.signUp.start,{user:{loginId:t,name:s},origin:n})))),finish:ot(((t,n)=>T(e.post(d.signUp.finish,{transactionId:t,response:n}))))},signIn:{start:st(((t,n,s,i)=>T(e.post(d.signIn.start,{loginId:t,origin:n,loginOptions:s},{token:i})))),finish:ot(((t,n)=>T(e.post(d.signIn.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:nt(((t,n)=>T(e.post(d.signUpOrIn.start,{loginId:t,origin:n}))))},update:{start:it(((t,n,s)=>T(e.post(d.update.start,{loginId:t,origin:n},{token:s})))),finish:ot(((t,n)=>T(e.post(d.update.finish,{transactionId:t,response:n}))))}}),rt=ee("loginId"),pt=X(rt),dt=X(te("pendingRef")),lt=e=>({signUpOrIn:pt(((t,n)=>T(e.post(p.signUpOrIn,{loginId:t,loginOptions:n})))),signUp:pt(((t,n,s)=>T(e.post(p.signUp,{loginId:t,user:n,loginOptions:s})))),signIn:pt(((t,n,s)=>T(e.post(p.signIn,{loginId:t,loginOptions:n},{token:s})))),waitForSession:dt(((t,n)=>new Promise((s=>{const{pollingIntervalMs:i,timeoutMs:o}=re(n);let a;const r=setInterval((async()=>{const n=await e.post(p.session,{pendingRef:t});n.ok&&(clearInterval(r),a&&clearTimeout(a),s(T(Promise.resolve(n))))}),i);a=setTimeout((()=>{s({error:{errorDescription:`Session polling timeout exceeded: ${o}ms`,errorCode:"0"},ok:!1}),clearInterval(r)}),o)}))))}),ut=X(te("token")),gt=X([Y(`"${"token"}" must be string or undefined`)]);var ct,ht;var vt=X([(ct="projectId",ht=te("projectId"),z(_(ct,ht))())])((e=>t=>e(Object.assign(Object.assign({},t),{hooks:{beforeRequest:e=>{var n;const s=[].concat((null===(n=t.hooks)||void 0===n?void 0:n.beforeRequest)||[]);return null==s?void 0:s.reduce(((e,t)=>t(e)),e)},afterRequest:async(e,n)=>{var s;const i=[].concat((null===(s=t.hooks)||void 0===s?void 0:s.afterRequest)||[]);(await Promise.allSettled(null==i?void 0:i.map((t=>t(e,null==n?void 0:n.clone()))))).forEach((e=>{var n;return"rejected"===e.status&&(null===(n=t.logger)||void 0===n?void 0:n.error(e.reason))}))}}})))((({projectId:e,logger:t,baseUrl:n,hooks:s,cookiePolicy:i,baseHeaders:o={},fetch:a})=>{return r=L({baseUrl:n||b,projectId:e,logger:t,hooks:s,cookiePolicy:i,baseConfig:{baseHeaders:o},fetch:a}),{accessKey:oe(r),otp:Ne(r),magicLink:Pe(r),enchantedLink:Ie(r),oauth:$e(r),saml:Ce(r),totp:Fe(r),notp:lt(r),webauthn:at(r),password:Ge(r),flow:ke(r),refresh:gt((e=>T(r.post(u,{},{token:e})))),selectTenant:X([Q("tenantId")],[Y('"token" must be string or undefined')])(((e,t)=>T(r.post(g,{tenant:e},{token:t})))),logout:gt((e=>T(r.post(c,{},{token:e})))),logoutAll:gt((e=>T(r.post(h,{},{token:e})))),me:gt((e=>T(r.get(v,{token:e})))),history:gt((e=>T(r.get(f,{token:e})))),isJwtExpired:ut(x),getTenants:ut(q),getJwtPermissions:ut($),getJwtRoles:ut(E),httpClient:r};var r}))),ft=Object.assign(vt,{DeliveryMethods:le});export{U as HttpStatusCodes,ft as default,re as normalizeWaitForSessionConfig,T as transformResponse,ae as wrapWith};
2
2
  //# sourceMappingURL=index.esm.js.map