@authorizerdev/authorizer-js 2.0.0-beta.3 → 2.0.1
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 +7 -3
- package/lib/authorizer.min.js +2 -2
- package/lib/index.js +8 -8
- package/lib/index.mjs +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,9 +7,13 @@ It supports:
|
|
|
7
7
|
- [CommonJS(cjs)](https://flaviocopes.com/commonjs/) build for NodeJS version that don't support ES Modules
|
|
8
8
|
- [ESM (ES Modules)](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/) build for modern javascript standard, i.e. ES Modules
|
|
9
9
|
|
|
10
|
-
# Migration from 1.x -> 2.x
|
|
10
|
+
# Migration Guide from 1.x -> 2.x
|
|
11
11
|
|
|
12
|
-
`2.x` version of `@authorizerdev/authorizer-js` has a uniform response structure that will help your applications to get right error codes and success response. Methods here have `{data, errors}` as response
|
|
12
|
+
`2.x` version of `@authorizerdev/authorizer-js` has a uniform response structure that will help your applications to get right error codes and success response. Methods here have `{data, errors}` as response objects for methods of this library.
|
|
13
|
+
|
|
14
|
+
For `1.x` version of this library you can get only data in response and error would be thrown so you had to handle that in catch.
|
|
15
|
+
|
|
16
|
+
---
|
|
13
17
|
|
|
14
18
|
All the above versions require `Authorizer` instance to be instantiated and used. Instance constructor requires an object with the following keys
|
|
15
19
|
|
|
@@ -59,7 +63,7 @@ const authRef = new Authorizer({
|
|
|
59
63
|
});
|
|
60
64
|
if (data && data.access_token) {
|
|
61
65
|
// get user profile using the access token
|
|
62
|
-
const user = await authorizerRef.getProfile({
|
|
66
|
+
const { data: user, errors } = await authorizerRef.getProfile({
|
|
63
67
|
Authorization: `Bearer ${res.access_token}`,
|
|
64
68
|
});
|
|
65
69
|
|
package/lib/authorizer.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var authorizerdev=(()=>{var ye=Object.create;var k=Object.defineProperty,_e=Object.defineProperties,me=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyDescriptors,we=Object.getOwnPropertyNames,G=Object.getOwnPropertySymbols,be=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty,Re=Object.prototype.propertyIsEnumerable;var P=(n,e,o)=>e in n?k(n,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):n[e]=o,I=(n,e)=>{for(var o in e||(e={}))W.call(e,o)&&P(n,o,e[o]);if(G)for(var o of G(e))Re.call(e,o)&&P(n,o,e[o]);return n},Z=(n,e)=>_e(n,ge(e)),a=(n,e)=>k(n,"name",{value:e,configurable:!0});var ve=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ee=(n,e)=>{for(var o in e)k(n,o,{get:e[o],enumerable:!0})},X=(n,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of we(e))!W.call(n,r)&&r!==o&&k(n,r,{get:()=>e[r],enumerable:!(s=me(e,r))||s.enumerable});return n};var Te=(n,e,o)=>(o=n!=null?ye(be(n)):{},X(e||!n||!n.__esModule?k(o,"default",{value:n,enumerable:!0}):o,n)),Ue=n=>X(k({},"__esModule",{value:!0}),n);var u=(n,e,o)=>(P(n,typeof e!="symbol"?e+"":e,o),o);var l=(n,e,o)=>new Promise((s,r)=>{var c=m=>{try{w(o.next(m))}catch(_){r(_)}},g=m=>{try{w(o.throw(m))}catch(_){r(_)}},w=m=>m.done?s(m.value):Promise.resolve(m.value).then(c,g);w((o=o.apply(n,e)).next())});var ee=ve((R,Y)=>{var K=typeof self!="undefined"?self:R,$=function(){function n(){this.fetch=!1,this.DOMException=K.DOMException}return a(n,"F"),n.prototype=K,new n}();(function(n){var e=function(o){var s={searchParams:"URLSearchParams"in n,iterable:"Symbol"in n&&"iterator"in Symbol,blob:"FileReader"in n&&"Blob"in n&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in n,arrayBuffer:"ArrayBuffer"in n};function r(t){return t&&DataView.prototype.isPrototypeOf(t)}if(a(r,"isDataView"),s.arrayBuffer)var c=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],g=ArrayBuffer.isView||function(t){return t&&c.indexOf(Object.prototype.toString.call(t))>-1};function w(t){if(typeof t!="string"&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}a(w,"normalizeName");function m(t){return typeof t!="string"&&(t=String(t)),t}a(m,"normalizeValue");function _(t){var i={next:function(){var h=t.shift();return{done:h===void 0,value:h}}};return s.iterable&&(i[Symbol.iterator]=function(){return i}),i}a(_,"iteratorFor");function p(t){this.map={},t instanceof p?t.forEach(function(i,h){this.append(h,i)},this):Array.isArray(t)?t.forEach(function(i){this.append(i[0],i[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(i){this.append(i,t[i])},this)}a(p,"Headers"),p.prototype.append=function(t,i){t=w(t),i=m(i);var h=this.map[t];this.map[t]=h?h+", "+i:i},p.prototype.delete=function(t){delete this.map[w(t)]},p.prototype.get=function(t){return t=w(t),this.has(t)?this.map[t]:null},p.prototype.has=function(t){return this.map.hasOwnProperty(w(t))},p.prototype.set=function(t,i){this.map[w(t)]=m(i)},p.prototype.forEach=function(t,i){for(var h in this.map)this.map.hasOwnProperty(h)&&t.call(i,this.map[h],h,this)},p.prototype.keys=function(){var t=[];return this.forEach(function(i,h){t.push(h)}),_(t)},p.prototype.values=function(){var t=[];return this.forEach(function(i){t.push(i)}),_(t)},p.prototype.entries=function(){var t=[];return this.forEach(function(i,h){t.push([h,i])}),_(t)},s.iterable&&(p.prototype[Symbol.iterator]=p.prototype.entries);function B(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}a(B,"consumed");function Q(t){return new Promise(function(i,h){t.onload=function(){i(t.result)},t.onerror=function(){h(t.error)}})}a(Q,"fileReaderReady");function ae(t){var i=new FileReader,h=Q(i);return i.readAsArrayBuffer(t),h}a(ae,"readBlobAsArrayBuffer");function ce(t){var i=new FileReader,h=Q(i);return i.readAsText(t),h}a(ce,"readBlobAsText");function he(t){for(var i=new Uint8Array(t),h=new Array(i.length),y=0;y<i.length;y++)h[y]=String.fromCharCode(i[y]);return h.join("")}a(he,"readArrayBufferAsText");function V(t){if(t.slice)return t.slice(0);var i=new Uint8Array(t.byteLength);return i.set(new Uint8Array(t)),i.buffer}a(V,"bufferClone");function J(){return this.bodyUsed=!1,this._initBody=function(t){this._bodyInit=t,t?typeof t=="string"?this._bodyText=t:s.blob&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:s.formData&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:s.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():s.arrayBuffer&&s.blob&&r(t)?(this._bodyArrayBuffer=V(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(t)||g(t))?this._bodyArrayBuffer=V(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||(typeof t=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):s.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},s.blob&&(this.blob=function(){var t=B(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?B(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(ae)}),this.text=function(){var t=B(this);if(t)return t;if(this._bodyBlob)return ce(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(he(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},s.formData&&(this.formData=function(){return this.text().then(le)}),this.json=function(){return this.text().then(JSON.parse)},this}a(J,"Body");var ue=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function de(t){var i=t.toUpperCase();return ue.indexOf(i)>-1?i:t}a(de,"normalizeMethod");function E(t,i){i=i||{};var h=i.body;if(t instanceof E){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,i.headers||(this.headers=new p(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,!h&&t._bodyInit!=null&&(h=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=i.credentials||this.credentials||"same-origin",(i.headers||!this.headers)&&(this.headers=new p(i.headers)),this.method=de(i.method||this.method||"GET"),this.mode=i.mode||this.mode||null,this.signal=i.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&h)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(h)}a(E,"Request"),E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function le(t){var i=new FormData;return t.trim().split("&").forEach(function(h){if(h){var y=h.split("="),f=y.shift().replace(/\+/g," "),d=y.join("=").replace(/\+/g," ");i.append(decodeURIComponent(f),decodeURIComponent(d))}}),i}a(le,"decode");function pe(t){var i=new p,h=t.replace(/\r?\n[\t ]+/g," ");return h.split(/\r?\n/).forEach(function(y){var f=y.split(":"),d=f.shift().trim();if(d){var x=f.join(":").trim();i.append(d,x)}}),i}a(pe,"parseHeaders"),J.call(E.prototype);function b(t,i){i||(i={}),this.type="default",this.status=i.status===void 0?200:i.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in i?i.statusText:"OK",this.headers=new p(i.headers),this.url=i.url||"",this._initBody(t)}a(b,"Response"),J.call(b.prototype),b.prototype.clone=function(){return new b(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},b.error=function(){var t=new b(null,{status:0,statusText:""});return t.type="error",t};var fe=[301,302,303,307,308];b.redirect=function(t,i){if(fe.indexOf(i)===-1)throw new RangeError("Invalid status code");return new b(null,{status:i,headers:{location:t}})},o.DOMException=n.DOMException;try{new o.DOMException}catch(t){o.DOMException=function(i,h){this.message=i,this.name=h;var y=Error(i);this.stack=y.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function D(t,i){return new Promise(function(h,y){var f=new E(t,i);if(f.signal&&f.signal.aborted)return y(new o.DOMException("Aborted","AbortError"));var d=new XMLHttpRequest;function x(){d.abort()}a(x,"abortXhr"),d.onload=function(){var O={status:d.status,statusText:d.statusText,headers:pe(d.getAllResponseHeaders()||"")};O.url="responseURL"in d?d.responseURL:O.headers.get("X-Request-URL");var C="response"in d?d.response:d.responseText;h(new b(C,O))},d.onerror=function(){y(new TypeError("Network request failed"))},d.ontimeout=function(){y(new TypeError("Network request failed"))},d.onabort=function(){y(new o.DOMException("Aborted","AbortError"))},d.open(f.method,f.url,!0),f.credentials==="include"?d.withCredentials=!0:f.credentials==="omit"&&(d.withCredentials=!1),"responseType"in d&&s.blob&&(d.responseType="blob"),f.headers.forEach(function(O,C){d.setRequestHeader(C,O)}),f.signal&&(f.signal.addEventListener("abort",x),d.onreadystatechange=function(){d.readyState===4&&f.signal.removeEventListener("abort",x)}),d.send(typeof f._bodyInit=="undefined"?null:f._bodyInit)})}return a(D,"fetch"),D.polyfill=!0,n.fetch||(n.fetch=D,n.Headers=p,n.Request=E,n.Response=b),o.Headers=p,o.Request=E,o.Response=b,o.fetch=D,Object.defineProperty(o,"__esModule",{value:!0}),o}({})})($);$.fetch.ponyfill=!0;delete $.fetch.polyfill;var A=$;R=A.fetch;R.default=A.fetch;R.fetch=A.fetch;R.Headers=A.Headers;R.Request=A.Request;R.Response=A.Response;Y.exports=R});var Oe={};Ee(Oe,{Authorizer:()=>H,OAuthProviders:()=>q,ResponseTypes:()=>L});var ie=Te(ee());var q;(function(n){n.Apple="apple",n.Github="github",n.Google="google",n.Facebook="facebook",n.LinkedIn="linkedin",n.Twitter="twitter",n.Microsoft="microsoft",n.Twitch="twitch"})(q||(q={}));var L;(function(n){n.Code="code",n.Token="token"})(L||(L={}));var T=a(()=>typeof window!="undefined","hasWindow"),j=a(n=>{let e=n.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),re=a(()=>T()?window.crypto||window.msCrypto:null,"getCrypto"),Ae=a(()=>{let n=re();return n&&n.subtle||n.webkitSubtle},"getCryptoSubtle"),U=a(()=>{let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",o=re();return o&&Array.from(o.getRandomValues(new Uint8Array(43))).forEach(r=>e+=n[r%n.length]),e},"createRandomString"),v=a(n=>T()?btoa(n):Buffer.from(n).toString("base64"),"encode");var te=a(n=>Object.keys(n).filter(e=>typeof n[e]!="undefined").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(n[e])}`).join("&"),"createQueryParams"),oe=a(n=>l(void 0,null,function*(){let e=Ae().digest({name:"SHA-256"},new TextEncoder().encode(n));return window.msCrypto?new Promise((o,s)=>{e.oncomplete=r=>{o(r.target.result)},e.onerror=r=>{s(r.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):yield e}),"sha256"),Le=a(n=>{let e={"+":"-","/":"_","=":""};return n.replace(/[+/=]/g,o=>e[o])},"urlEncodeB64");var se=a(n=>{let e=new Uint8Array(n);return Le(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),ne=a((n,e,o=60)=>new Promise((s,r)=>{let c=window.document.createElement("iframe");c.setAttribute("id","authorizer-iframe"),c.setAttribute("width","0"),c.setAttribute("height","0"),c.style.display="none";let g=a(()=>{window.document.body.contains(c)&&(window.document.body.removeChild(c),window.removeEventListener("message",m,!1))},"removeIframe"),w=setTimeout(()=>{g()},o*1e3),m=a(function(_){if(_.origin!==e||!_.data||!_.data.response)return;let p=_.source;p&&p.close(),_.data.response.error?r(_.data.response):s(_.data.response),clearTimeout(w),window.removeEventListener("message",m,!1),setTimeout(g,2*1e3)},"iframeEventHandler");window.addEventListener("message",m,!1),window.document.body.appendChild(c),c.setAttribute("src",n)}),"executeIframe");var z="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",S=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen should_show_totp_screen authenticator_scanner_image authenticator_secret authenticator_recovery_codes user { ${z} }`,M=a(()=>T()?window.fetch:ie.default,"getFetcher"),N=class N{constructor(e){u(this,"config");u(this,"codeVerifier");u(this,"authorize",a(e=>l(this,null,function*(){if(!T())return this.errorResponse([new Error("this feature is only supported in browser")]);let o=["openid","profile","email"];e.use_refresh_token&&o.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:v(U()),nonce:v(U()),response_type:e.response_type,scope:o.join(" "),client_id:this.config.clientID};if(e.response_type===L.Code){this.codeVerifier=U();let c=yield oe(this.codeVerifier),g=se(c);s.code_challenge=g}let r=`${this.config.authorizerURL}/authorize?${te(s)}`;if(s.response_mode!=="web_message")return window.location.replace(r),this.okResponse(void 0);try{let c=yield ne(r,this.config.authorizerURL,60);if(e.response_type===L.Code){let g=yield this.getToken({code:c.code});return g.errors.length?this.errorResponse(g.errors):this.okResponse(g.data)}return this.okResponse(c)}catch(c){return c.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(c)}}),"authorize"));u(this,"browserLogin",a(()=>l(this,null,function*(){try{let e=yield this.getSession();return e.errors.length?this.errorResponse(e.errors):this.okResponse(e.data)}catch(e){return T()?(window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}}),"browserLogin"));u(this,"forgotPassword",a(e=>l(this,null,function*(){var o;e.state||(e.state=v(U())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let s=yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message should_show_mobile_otp_screen } }",variables:{data:e}});return(o=s==null?void 0:s.errors)!=null&&o.length?this.errorResponse(s.errors):this.okResponse(s==null?void 0:s.data.forgot_password)}catch(s){return this.errorResponse([s])}}),"forgotPassword"));u(this,"getMetaData",a(()=>l(this,null,function*(){var e;try{let o=yield this.graphqlQuery({query:"query { meta { version client_id is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_twitch_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled is_multi_factor_auth_enabled is_mobile_basic_authentication_enabled is_phone_verification_enabled } }"});return(e=o==null?void 0:o.errors)!=null&&e.length?this.errorResponse(o.errors):this.okResponse(o.data.meta)}catch(o){return this.errorResponse([o])}}),"getMetaData"));u(this,"getProfile",a(e=>l(this,null,function*(){var o;try{let s=yield this.graphqlQuery({query:`query { profile { ${z} } }`,headers:e});return(o=s==null?void 0:s.errors)!=null&&o.length?this.errorResponse(s.errors):this.okResponse(s.data.profile)}catch(s){return this.errorResponse([s])}}),"getProfile"));u(this,"getSession",a((e,o)=>l(this,null,function*(){var s,r;try{let c=yield this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${S} } }`,headers:e,variables:{params:o}});return(s=c==null?void 0:c.errors)!=null&&s.length?this.errorResponse(c.errors):this.okResponse((r=c.data)==null?void 0:r.session)}catch(c){return this.errorResponse(c)}}),"getSession"));u(this,"getToken",a(e=>l(this,null,function*(){if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let o={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let r=yield M()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(o),headers:I({},this.config.extraHeaders),credentials:"include"}),c=yield r.json();return r.status>=400?this.errorResponse([new Error(c.error_description||c.error)]):this.okResponse(c)}catch(s){return this.errorResponse(s)}}),"getToken"));u(this,"login",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
|
|
1
|
+
var authorizerdev=(()=>{var ye=Object.create;var k=Object.defineProperty,_e=Object.defineProperties,me=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyDescriptors,we=Object.getOwnPropertyNames,G=Object.getOwnPropertySymbols,be=Object.getPrototypeOf,W=Object.prototype.hasOwnProperty,Re=Object.prototype.propertyIsEnumerable;var P=(n,e,o)=>e in n?k(n,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):n[e]=o,I=(n,e)=>{for(var o in e||(e={}))W.call(e,o)&&P(n,o,e[o]);if(G)for(var o of G(e))Re.call(e,o)&&P(n,o,e[o]);return n},Z=(n,e)=>_e(n,ge(e)),a=(n,e)=>k(n,"name",{value:e,configurable:!0});var ve=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ee=(n,e)=>{for(var o in e)k(n,o,{get:e[o],enumerable:!0})},X=(n,e,o,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of we(e))!W.call(n,r)&&r!==o&&k(n,r,{get:()=>e[r],enumerable:!(s=me(e,r))||s.enumerable});return n};var Te=(n,e,o)=>(o=n!=null?ye(be(n)):{},X(e||!n||!n.__esModule?k(o,"default",{value:n,enumerable:!0}):o,n)),Ue=n=>X(k({},"__esModule",{value:!0}),n);var u=(n,e,o)=>(P(n,typeof e!="symbol"?e+"":e,o),o);var l=(n,e,o)=>new Promise((s,r)=>{var c=m=>{try{w(o.next(m))}catch(_){r(_)}},g=m=>{try{w(o.throw(m))}catch(_){r(_)}},w=m=>m.done?s(m.value):Promise.resolve(m.value).then(c,g);w((o=o.apply(n,e)).next())});var ee=ve((R,Y)=>{var K=typeof self!="undefined"?self:R,$=function(){function n(){this.fetch=!1,this.DOMException=K.DOMException}return a(n,"F"),n.prototype=K,new n}();(function(n){var e=function(o){var s={searchParams:"URLSearchParams"in n,iterable:"Symbol"in n&&"iterator"in Symbol,blob:"FileReader"in n&&"Blob"in n&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in n,arrayBuffer:"ArrayBuffer"in n};function r(t){return t&&DataView.prototype.isPrototypeOf(t)}if(a(r,"isDataView"),s.arrayBuffer)var c=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],g=ArrayBuffer.isView||function(t){return t&&c.indexOf(Object.prototype.toString.call(t))>-1};function w(t){if(typeof t!="string"&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}a(w,"normalizeName");function m(t){return typeof t!="string"&&(t=String(t)),t}a(m,"normalizeValue");function _(t){var i={next:function(){var h=t.shift();return{done:h===void 0,value:h}}};return s.iterable&&(i[Symbol.iterator]=function(){return i}),i}a(_,"iteratorFor");function p(t){this.map={},t instanceof p?t.forEach(function(i,h){this.append(h,i)},this):Array.isArray(t)?t.forEach(function(i){this.append(i[0],i[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(i){this.append(i,t[i])},this)}a(p,"Headers"),p.prototype.append=function(t,i){t=w(t),i=m(i);var h=this.map[t];this.map[t]=h?h+", "+i:i},p.prototype.delete=function(t){delete this.map[w(t)]},p.prototype.get=function(t){return t=w(t),this.has(t)?this.map[t]:null},p.prototype.has=function(t){return this.map.hasOwnProperty(w(t))},p.prototype.set=function(t,i){this.map[w(t)]=m(i)},p.prototype.forEach=function(t,i){for(var h in this.map)this.map.hasOwnProperty(h)&&t.call(i,this.map[h],h,this)},p.prototype.keys=function(){var t=[];return this.forEach(function(i,h){t.push(h)}),_(t)},p.prototype.values=function(){var t=[];return this.forEach(function(i){t.push(i)}),_(t)},p.prototype.entries=function(){var t=[];return this.forEach(function(i,h){t.push([h,i])}),_(t)},s.iterable&&(p.prototype[Symbol.iterator]=p.prototype.entries);function D(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}a(D,"consumed");function Q(t){return new Promise(function(i,h){t.onload=function(){i(t.result)},t.onerror=function(){h(t.error)}})}a(Q,"fileReaderReady");function ae(t){var i=new FileReader,h=Q(i);return i.readAsArrayBuffer(t),h}a(ae,"readBlobAsArrayBuffer");function ce(t){var i=new FileReader,h=Q(i);return i.readAsText(t),h}a(ce,"readBlobAsText");function he(t){for(var i=new Uint8Array(t),h=new Array(i.length),y=0;y<i.length;y++)h[y]=String.fromCharCode(i[y]);return h.join("")}a(he,"readArrayBufferAsText");function V(t){if(t.slice)return t.slice(0);var i=new Uint8Array(t.byteLength);return i.set(new Uint8Array(t)),i.buffer}a(V,"bufferClone");function J(){return this.bodyUsed=!1,this._initBody=function(t){this._bodyInit=t,t?typeof t=="string"?this._bodyText=t:s.blob&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:s.formData&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:s.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():s.arrayBuffer&&s.blob&&r(t)?(this._bodyArrayBuffer=V(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(t)||g(t))?this._bodyArrayBuffer=V(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||(typeof t=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):s.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},s.blob&&(this.blob=function(){var t=D(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?D(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(ae)}),this.text=function(){var t=D(this);if(t)return t;if(this._bodyBlob)return ce(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(he(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},s.formData&&(this.formData=function(){return this.text().then(le)}),this.json=function(){return this.text().then(JSON.parse)},this}a(J,"Body");var ue=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function de(t){var i=t.toUpperCase();return ue.indexOf(i)>-1?i:t}a(de,"normalizeMethod");function E(t,i){i=i||{};var h=i.body;if(t instanceof E){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,i.headers||(this.headers=new p(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,!h&&t._bodyInit!=null&&(h=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=i.credentials||this.credentials||"same-origin",(i.headers||!this.headers)&&(this.headers=new p(i.headers)),this.method=de(i.method||this.method||"GET"),this.mode=i.mode||this.mode||null,this.signal=i.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&h)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(h)}a(E,"Request"),E.prototype.clone=function(){return new E(this,{body:this._bodyInit})};function le(t){var i=new FormData;return t.trim().split("&").forEach(function(h){if(h){var y=h.split("="),f=y.shift().replace(/\+/g," "),d=y.join("=").replace(/\+/g," ");i.append(decodeURIComponent(f),decodeURIComponent(d))}}),i}a(le,"decode");function pe(t){var i=new p,h=t.replace(/\r?\n[\t ]+/g," ");return h.split(/\r?\n/).forEach(function(y){var f=y.split(":"),d=f.shift().trim();if(d){var x=f.join(":").trim();i.append(d,x)}}),i}a(pe,"parseHeaders"),J.call(E.prototype);function b(t,i){i||(i={}),this.type="default",this.status=i.status===void 0?200:i.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in i?i.statusText:"OK",this.headers=new p(i.headers),this.url=i.url||"",this._initBody(t)}a(b,"Response"),J.call(b.prototype),b.prototype.clone=function(){return new b(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},b.error=function(){var t=new b(null,{status:0,statusText:""});return t.type="error",t};var fe=[301,302,303,307,308];b.redirect=function(t,i){if(fe.indexOf(i)===-1)throw new RangeError("Invalid status code");return new b(null,{status:i,headers:{location:t}})},o.DOMException=n.DOMException;try{new o.DOMException}catch(t){o.DOMException=function(i,h){this.message=i,this.name=h;var y=Error(i);this.stack=y.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function B(t,i){return new Promise(function(h,y){var f=new E(t,i);if(f.signal&&f.signal.aborted)return y(new o.DOMException("Aborted","AbortError"));var d=new XMLHttpRequest;function x(){d.abort()}a(x,"abortXhr"),d.onload=function(){var O={status:d.status,statusText:d.statusText,headers:pe(d.getAllResponseHeaders()||"")};O.url="responseURL"in d?d.responseURL:O.headers.get("X-Request-URL");var C="response"in d?d.response:d.responseText;h(new b(C,O))},d.onerror=function(){y(new TypeError("Network request failed"))},d.ontimeout=function(){y(new TypeError("Network request failed"))},d.onabort=function(){y(new o.DOMException("Aborted","AbortError"))},d.open(f.method,f.url,!0),f.credentials==="include"?d.withCredentials=!0:f.credentials==="omit"&&(d.withCredentials=!1),"responseType"in d&&s.blob&&(d.responseType="blob"),f.headers.forEach(function(O,C){d.setRequestHeader(C,O)}),f.signal&&(f.signal.addEventListener("abort",x),d.onreadystatechange=function(){d.readyState===4&&f.signal.removeEventListener("abort",x)}),d.send(typeof f._bodyInit=="undefined"?null:f._bodyInit)})}return a(B,"fetch"),B.polyfill=!0,n.fetch||(n.fetch=B,n.Headers=p,n.Request=E,n.Response=b),o.Headers=p,o.Request=E,o.Response=b,o.fetch=B,Object.defineProperty(o,"__esModule",{value:!0}),o}({})})($);$.fetch.ponyfill=!0;delete $.fetch.polyfill;var A=$;R=A.fetch;R.default=A.fetch;R.fetch=A.fetch;R.Headers=A.Headers;R.Request=A.Request;R.Response=A.Response;Y.exports=R});var Oe={};Ee(Oe,{Authorizer:()=>H,OAuthProviders:()=>q,ResponseTypes:()=>L});var ie=Te(ee());var q;(function(n){n.Apple="apple",n.Github="github",n.Google="google",n.Facebook="facebook",n.LinkedIn="linkedin",n.Twitter="twitter",n.Microsoft="microsoft",n.Twitch="twitch"})(q||(q={}));var L;(function(n){n.Code="code",n.Token="token"})(L||(L={}));var T=a(()=>typeof window!="undefined","hasWindow"),j=a(n=>{let e=n.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),re=a(()=>T()?window.crypto||window.msCrypto:null,"getCrypto"),Ae=a(()=>{let n=re();return n&&n.subtle||n.webkitSubtle},"getCryptoSubtle"),U=a(()=>{let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",o=re();return o&&Array.from(o.getRandomValues(new Uint8Array(43))).forEach(r=>e+=n[r%n.length]),e},"createRandomString"),v=a(n=>T()?btoa(n):Buffer.from(n).toString("base64"),"encode");var te=a(n=>Object.keys(n).filter(e=>typeof n[e]!="undefined").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(n[e])}`).join("&"),"createQueryParams"),oe=a(n=>l(void 0,null,function*(){let e=Ae().digest({name:"SHA-256"},new TextEncoder().encode(n));return window.msCrypto?new Promise((o,s)=>{e.oncomplete=r=>{o(r.target.result)},e.onerror=r=>{s(r.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):yield e}),"sha256"),Le=a(n=>{let e={"+":"-","/":"_","=":""};return n.replace(/[+/=]/g,o=>e[o])},"urlEncodeB64");var se=a(n=>{let e=new Uint8Array(n);return Le(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),ne=a((n,e,o=60)=>new Promise((s,r)=>{let c=window.document.createElement("iframe");c.setAttribute("id","authorizer-iframe"),c.setAttribute("width","0"),c.setAttribute("height","0"),c.style.display="none";let g=a(()=>{window.document.body.contains(c)&&(window.document.body.removeChild(c),window.removeEventListener("message",m,!1))},"removeIframe"),w=setTimeout(()=>{g()},o*1e3),m=a(function(_){if(_.origin!==e||!_.data||!_.data.response)return;let p=_.source;p&&p.close(),_.data.response.error?r(_.data.response):s(_.data.response),clearTimeout(w),window.removeEventListener("message",m,!1),setTimeout(g,2*1e3)},"iframeEventHandler");window.addEventListener("message",m,!1),window.document.body.appendChild(c),c.setAttribute("src",n)}),"executeIframe");var z="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",S=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen should_show_totp_screen authenticator_scanner_image authenticator_secret authenticator_recovery_codes user { ${z} }`,M=a(()=>T()?window.fetch:ie.default,"getFetcher"),N=class N{constructor(e){u(this,"config");u(this,"codeVerifier");u(this,"authorize",a(e=>l(this,null,function*(){if(!T())return this.errorResponse([new Error("this feature is only supported in browser")]);let o=["openid","profile","email"];e.use_refresh_token&&o.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:v(U()),nonce:v(U()),response_type:e.response_type,scope:o.join(" "),client_id:this.config.clientID};if(e.response_type===L.Code){this.codeVerifier=U();let c=yield oe(this.codeVerifier),g=se(c);s.code_challenge=g}let r=`${this.config.authorizerURL}/authorize?${te(s)}`;if(s.response_mode!=="web_message")return window.location.replace(r),this.okResponse(void 0);try{let c=yield ne(r,this.config.authorizerURL,60);if(e.response_type===L.Code){let g=yield this.getToken({code:c.code});return g.errors.length?this.errorResponse(g.errors):this.okResponse(g.data)}return this.okResponse(c)}catch(c){return c.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(c)}}),"authorize"));u(this,"browserLogin",a(()=>l(this,null,function*(){try{let e=yield this.getSession();return e.errors.length?this.errorResponse(e.errors):this.okResponse(e.data)}catch(e){return T()?(window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}}),"browserLogin"));u(this,"forgotPassword",a(e=>l(this,null,function*(){var o;e.state||(e.state=v(U())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let s=yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message should_show_mobile_otp_screen } }",variables:{data:e}});return(o=s==null?void 0:s.errors)!=null&&o.length?this.errorResponse(s.errors):this.okResponse(s==null?void 0:s.data.forgot_password)}catch(s){return this.errorResponse([s])}}),"forgotPassword"));u(this,"getMetaData",a(()=>l(this,null,function*(){var e;try{let o=yield this.graphqlQuery({query:"query { meta { version client_id is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_twitch_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled is_multi_factor_auth_enabled is_mobile_basic_authentication_enabled is_phone_verification_enabled } }"});return(e=o==null?void 0:o.errors)!=null&&e.length?this.errorResponse(o.errors):this.okResponse(o.data.meta)}catch(o){return this.errorResponse([o])}}),"getMetaData"));u(this,"getProfile",a(e=>l(this,null,function*(){var o;try{let s=yield this.graphqlQuery({query:`query { profile { ${z} } }`,headers:e});return(o=s==null?void 0:s.errors)!=null&&o.length?this.errorResponse(s.errors):this.okResponse(s.data.profile)}catch(s){return this.errorResponse([s])}}),"getProfile"));u(this,"getSession",a((e,o)=>l(this,null,function*(){var s,r;try{let c=yield this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${S} } }`,headers:e,variables:{params:o}});return(s=c==null?void 0:c.errors)!=null&&s.length?this.errorResponse(c.errors):this.okResponse((r=c.data)==null?void 0:r.session)}catch(c){return this.errorResponse(c)}}),"getSession"));u(this,"getToken",a(e=>l(this,null,function*(){if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let o={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let r=yield M()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(o),headers:I({},this.config.extraHeaders),credentials:"include"}),c=yield r.json();return r.status>=400?this.errorResponse([new Error(c.error_description||c.error)]):this.okResponse(c)}catch(s){return this.errorResponse(s)}}),"getToken"));u(this,"login",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
|
|
2
2
|
mutation login($data: LoginInput!) { login(params: $data) { ${S}}}
|
|
3
3
|
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.login)}catch(r){return this.errorResponse([new Error(r)])}}),"login"));u(this,"logout",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.response)}catch(r){return this.errorResponse([r])}}),"logout"));u(this,"magicLinkLogin",a(e=>l(this,null,function*(){var o,s;try{e.state||(e.state=v(U())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let r=yield this.graphqlQuery({query:`
|
|
4
4
|
mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }}
|
|
@@ -12,5 +12,5 @@ var authorizerdev=(()=>{var ye=Object.create;var k=Object.defineProperty,_e=Obje
|
|
|
12
12
|
mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }}
|
|
13
13
|
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_email)}catch(r){return this.errorResponse([r])}}),"resendVerifyEmail"));u(this,"verifyOtp",a(e=>l(this,null,function*(){var o,s;try{let r=yield this.graphqlQuery({query:`
|
|
14
14
|
mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${S}}}
|
|
15
|
-
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_otp)}catch(r){return this.errorResponse([r])}}),"verifyOtp"));u(this,"graphqlQuery",a(e=>l(this,null,function*(){var c;let r=yield(yield M()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:I(I({},this.config.extraHeaders),e.headers||{}),credentials:"include"})).json();return(c=r==null?void 0:r.errors)!=null&&c.length?{data:void 0,errors:r.errors}:{data:r.data,errors:[]}}),"graphqlQuery"));u(this,"errorResponse",a(e=>({data:void 0,errors:e}),"errorResponse"));u(this,"okResponse",a(e=>({data:e,errors:[]}),"okResponse"));if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(e.authorizerURL&&(this.config.authorizerURL=j(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=j(e.redirectURL),this.config.extraHeaders=Z(I({},e.extraHeaders||{}),{"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"}),this.config.clientID=e.clientID.trim()}};a(N,"Authorizer");var H=N;return Ue(Oe);})();
|
|
15
|
+
`,variables:{data:e}});return(o=r==null?void 0:r.errors)!=null&&o.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_otp)}catch(r){return this.errorResponse([r])}}),"verifyOtp"));u(this,"graphqlQuery",a(e=>l(this,null,function*(){var c;let r=yield(yield M()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:I(I({},this.config.extraHeaders),e.headers||{}),credentials:"include"})).json();return(c=r==null?void 0:r.errors)!=null&&c.length?{data:void 0,errors:r.errors}:{data:r.data,errors:[]}}),"graphqlQuery"));u(this,"errorResponse",a(e=>({data:void 0,errors:e}),"errorResponse"));u(this,"okResponse",a(e=>({data:e,errors:[]}),"okResponse"));if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(!e.clientID&&!e.clientID.trim())throw new Error("Invalid clientID");if(e.authorizerURL&&(this.config.authorizerURL=j(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=j(e.redirectURL),this.config.extraHeaders=Z(I({},e.extraHeaders||{}),{"x-authorizer-url":this.config.authorizerURL,"x-authorizer-client-id":this.config.clientID,"Content-Type":"application/json"}),this.config.clientID=e.clientID.trim()}};a(N,"Authorizer");var H=N;return Ue(Oe);})();
|
|
16
16
|
window.__TAURI__ = authorizerdev
|
package/lib/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
var x=Object.create;var l=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var
|
|
1
|
+
var x=Object.create;var l=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var i=(o,e)=>l(o,"name",{value:e,configurable:!0});var Q=(o,e)=>{for(var t in e)l(o,t,{get:e[t],enumerable:!0})},$=(o,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of O(e))!z.call(o,r)&&r!==t&&l(o,r,{get:()=>e[r],enumerable:!(s=C(e,r))||s.enumerable});return o};var A=(o,e,t)=>(t=o!=null?x(D(o)):{},$(e||!o||!o.__esModule?l(t,"default",{value:o,enumerable:!0}):t,o)),N=o=>$(l({},"__esModule",{value:!0}),o);var H={};Q(H,{Authorizer:()=>b,OAuthProviders:()=>_,ResponseTypes:()=>d});module.exports=N(H);var q=A(require("cross-fetch"));var _;(function(o){o.Apple="apple",o.Github="github",o.Google="google",o.Facebook="facebook",o.LinkedIn="linkedin",o.Twitter="twitter",o.Microsoft="microsoft",o.Twitch="twitch"})(_||(_={}));var d;(function(o){o.Code="code",o.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),y=i(o=>{let e=o.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),E=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),F=i(()=>{let o=E();return o&&o.subtle||o.webkitSubtle},"getCryptoSubtle"),u=i(()=>{let o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",t=E();return t&&Array.from(t.getRandomValues(new Uint8Array(43))).forEach(r=>e+=o[r%o.length]),e},"createRandomString"),c=i(o=>p()?btoa(o):Buffer.from(o).toString("base64"),"encode");var I=i(o=>Object.keys(o).filter(e=>typeof o[e]<"u").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(o[e])}`).join("&"),"createQueryParams"),U=i(async o=>{let e=F().digest({name:"SHA-256"},new TextEncoder().encode(o));return window.msCrypto?new Promise((t,s)=>{e.oncomplete=r=>{t(r.target.result)},e.onerror=r=>{s(r.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):await e},"sha256"),M=i(o=>{let e={"+":"-","/":"_","=":""};return o.replace(/[+/=]/g,t=>e[t])},"urlEncodeB64");var T=i(o=>{let e=new Uint8Array(o);return M(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),L=i((o,e,t=60)=>new Promise((s,r)=>{let n=window.document.createElement("iframe");n.setAttribute("id","authorizer-iframe"),n.setAttribute("width","0"),n.setAttribute("height","0"),n.style.display="none";let a=i(()=>{window.document.body.contains(n)&&(window.document.body.removeChild(n),window.removeEventListener("message",f,!1))},"removeIframe"),S=setTimeout(()=>{a()},t*1e3),f=i(function(h){if(h.origin!==e||!h.data||!h.data.response)return;let v=h.source;v&&v.close(),h.data.response.error?r(h.data.response):s(h.data.response),clearTimeout(S),window.removeEventListener("message",f,!1),setTimeout(a,2*1e3)},"iframeEventHandler");window.addEventListener("message",f,!1),window.document.body.appendChild(n),n.setAttribute("src",o)}),"executeIframe");var R="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",g=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen should_show_totp_screen authenticator_scanner_image authenticator_secret authenticator_recovery_codes user { ${R} }`,w=i(()=>p()?window.fetch:q.default,"getFetcher"),k=class k{config;codeVerifier;constructor(e){if(!e)throw new Error("Configuration is required");if(this.config=e,!e.authorizerURL&&!e.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(!e.clientID&&!e.clientID.trim())throw new Error("Invalid clientID");if(e.authorizerURL&&(this.config.authorizerURL=y(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=y(e.redirectURL),this.config.extraHeaders={...e.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"x-authorizer-client-id":this.config.clientID,"Content-Type":"application/json"},this.config.clientID=e.clientID.trim()}authorize=async e=>{if(!p())return this.errorResponse([new Error("this feature is only supported in browser")]);let t=["openid","profile","email"];e.use_refresh_token&&t.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:c(u()),nonce:c(u()),response_type:e.response_type,scope:t.join(" "),client_id:this.config.clientID};if(e.response_type===d.Code){this.codeVerifier=u();let n=await U(this.codeVerifier),a=T(n);s.code_challenge=a}let r=`${this.config.authorizerURL}/authorize?${I(s)}`;if(s.response_mode!=="web_message")return window.location.replace(r),this.okResponse(void 0);try{let n=await L(r,this.config.authorizerURL,60);if(e.response_type===d.Code){let a=await this.getToken({code:n.code});return a.errors.length?this.errorResponse(a.errors):this.okResponse(a.data)}return this.okResponse(n)}catch(n){return n.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(n)}};browserLogin=async()=>{try{let e=await this.getSession();return e.errors.length?this.errorResponse(e.errors):this.okResponse(e.data)}catch(e){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(e)):{data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}};forgotPassword=async e=>{var t;e.state||(e.state=c(u())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{let s=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message should_show_mobile_otp_screen } }",variables:{data:e}});return(t=s==null?void 0:s.errors)!=null&&t.length?this.errorResponse(s.errors):this.okResponse(s==null?void 0:s.data.forgot_password)}catch(s){return this.errorResponse([s])}};getMetaData=async()=>{var e;try{let t=await this.graphqlQuery({query:"query { meta { version client_id is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_twitch_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled is_multi_factor_auth_enabled is_mobile_basic_authentication_enabled is_phone_verification_enabled } }"});return(e=t==null?void 0:t.errors)!=null&&e.length?this.errorResponse(t.errors):this.okResponse(t.data.meta)}catch(t){return this.errorResponse([t])}};getProfile=async e=>{var t;try{let s=await this.graphqlQuery({query:`query { profile { ${R} } }`,headers:e});return(t=s==null?void 0:s.errors)!=null&&t.length?this.errorResponse(s.errors):this.okResponse(s.data.profile)}catch(s){return this.errorResponse([s])}};getSession=async(e,t)=>{var s,r;try{let n=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${g} } }`,headers:e,variables:{params:t}});return(s=n==null?void 0:n.errors)!=null&&s.length?this.errorResponse(n.errors):this.okResponse((r=n.data)==null?void 0:r.session)}catch(n){return this.errorResponse(n)}};getToken=async e=>{if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(e.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let t={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let r=await w()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:{...this.config.extraHeaders},credentials:"include"}),n=await r.json();return r.status>=400?this.errorResponse([new Error(n.error_description||n.error)]):this.okResponse(n)}catch(s){return this.errorResponse(s)}};login=async e=>{var t,s;try{let r=await this.graphqlQuery({query:`
|
|
2
2
|
mutation login($data: LoginInput!) { login(params: $data) { ${g}}}
|
|
3
|
-
`,variables:{data:
|
|
3
|
+
`,variables:{data:e}});return(t=r==null?void 0:r.errors)!=null&&t.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.login)}catch(r){return this.errorResponse([new Error(r)])}};logout=async e=>{var t,s;try{let r=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:e});return(t=r==null?void 0:r.errors)!=null&&t.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.response)}catch(r){return this.errorResponse([r])}};magicLinkLogin=async e=>{var t,s;try{e.state||(e.state=c(u())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);let r=await this.graphqlQuery({query:`
|
|
4
4
|
mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }}
|
|
5
|
-
`,variables:{data:
|
|
5
|
+
`,variables:{data:e}});return(t=r==null?void 0:r.errors)!=null&&t.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.magic_link_login)}catch(r){return this.errorResponse([r])}};oauthLogin=async(e,t,s,r)=>{let n=r;if(n||(n=c(u())),!Object.values(_).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!p())throw new Error("oauthLogin is only supported for browsers");t&&t.length&&(n+=`&roles=${t.join(",")}`),window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${s||this.config.redirectURL}&state=${n}`)};resendOtp=async e=>{var t,s;try{let r=await this.graphqlQuery({query:`
|
|
6
6
|
mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}
|
|
7
|
-
`,variables:{data:
|
|
7
|
+
`,variables:{data:e}});return(t=r==null?void 0:r.errors)!=null&&t.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.resend_otp)}catch(r){return this.errorResponse([r])}};resetPassword=async e=>{var t,s;try{let r=await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}});return(t=r==null?void 0:r.errors)!=null&&t.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.reset_password)}catch(r){return this.errorResponse([r])}};revokeToken=async e=>{if(!e.refresh_token&&!e.refresh_token.trim())return this.errorResponse([new Error("Invalid refresh_token")]);let r=await(await w()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:{...this.config.extraHeaders},body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json();return this.okResponse(r)};signup=async e=>{var t,s;try{let r=await this.graphqlQuery({query:`
|
|
8
8
|
mutation signup($data: SignUpInput!) { signup(params: $data) { ${g}}}
|
|
9
|
-
`,variables:{data:
|
|
9
|
+
`,variables:{data:e}});return(t=r==null?void 0:r.errors)!=null&&t.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.signup)}catch(r){return this.errorResponse([r])}};updateProfile=async(e,t)=>{var s,r;try{let n=await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:t,variables:{data:e}});return(s=n==null?void 0:n.errors)!=null&&s.length?this.errorResponse(n.errors):this.okResponse((r=n.data)==null?void 0:r.update_profile)}catch(n){return this.errorResponse([n])}};deactivateAccount=async e=>{var t,s;try{let r=await this.graphqlQuery({query:"mutation deactivateAccount { deactivate_account { message } }",headers:e});return(t=r==null?void 0:r.errors)!=null&&t.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.deactivate_account)}catch(r){return this.errorResponse([r])}};validateJWTToken=async e=>{var t,s;try{let r=await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}});return(t=r==null?void 0:r.errors)!=null&&t.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.validate_jwt_token)}catch(r){return this.errorResponse([r])}};validateSession=async e=>{var t,s;try{let r=await this.graphqlQuery({query:`query validateSession($params: ValidateSessionInput){validate_session(params: $params) { is_valid user { ${R} } } }`,variables:{params:e}});return(t=r==null?void 0:r.errors)!=null&&t.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.validate_session)}catch(r){return this.errorResponse([r])}};verifyEmail=async e=>{var t,s;try{let r=await this.graphqlQuery({query:`
|
|
10
10
|
mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${g}}}
|
|
11
|
-
`,variables:{data:
|
|
11
|
+
`,variables:{data:e}});return(t=r==null?void 0:r.errors)!=null&&t.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_email)}catch(r){return this.errorResponse([r])}};resendVerifyEmail=async e=>{var t,s;try{let r=await this.graphqlQuery({query:`
|
|
12
12
|
mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }}
|
|
13
|
-
`,variables:{data:
|
|
13
|
+
`,variables:{data:e}});return(t=r==null?void 0:r.errors)!=null&&t.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_email)}catch(r){return this.errorResponse([r])}};verifyOtp=async e=>{var t,s;try{let r=await this.graphqlQuery({query:`
|
|
14
14
|
mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${g}}}
|
|
15
|
-
`,variables:{data:
|
|
15
|
+
`,variables:{data:e}});return(t=r==null?void 0:r.errors)!=null&&t.length?this.errorResponse(r.errors):this.okResponse((s=r.data)==null?void 0:s.verify_otp)}catch(r){return this.errorResponse([r])}};graphqlQuery=async e=>{var n;let r=await(await w()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:{...this.config.extraHeaders,...e.headers||{}},credentials:"include"})).json();return(n=r==null?void 0:r.errors)!=null&&n.length?{data:void 0,errors:r.errors}:{data:r.data,errors:[]}};errorResponse=e=>({data:void 0,errors:e});okResponse=e=>({data:e,errors:[]})};i(k,"Authorizer");var b=k;0&&(module.exports={Authorizer,OAuthProviders,ResponseTypes});
|
package/lib/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var L=Object.defineProperty;var i=(n,r)=>L(n,"name",{value:r,configurable:!0});import O from"cross-fetch";var _;(function(n){n.Apple="apple",n.Github="github",n.Google="google",n.Facebook="facebook",n.LinkedIn="linkedin",n.Twitter="twitter",n.Microsoft="microsoft",n.Twitch="twitch"})(_||(_={}));var d;(function(n){n.Code="code",n.Token="token"})(d||(d={}));var p=i(()=>typeof window<"u","hasWindow"),m=i(n=>{let r=n.trim();return r[r.length-1]==="/"&&(r=r.slice(0,-1)),r},"trimURL"),k=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),x=i(()=>{let n=k();return n&&n.subtle||n.webkitSubtle},"getCryptoSubtle"),u=i(()=>{let n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",r="",s=k();return s&&Array.from(s.getRandomValues(new Uint8Array(43))).forEach(e=>r+=n[e%n.length]),r},"createRandomString"),c=i(n=>p()?btoa(n):Buffer.from(n).toString("base64"),"encode");var v=i(n=>Object.keys(n).filter(r=>typeof n[r]<"u").map(r=>`${encodeURIComponent(r)}=${encodeURIComponent(n[r])}`).join("&"),"createQueryParams"),$=i(async n=>{let r=x().digest({name:"SHA-256"},new TextEncoder().encode(n));return window.msCrypto?new Promise((s,t)=>{r.oncomplete=e=>{s(e.target.result)},r.onerror=e=>{t(e.error)},r.onabort=()=>{t(new Error("The digest operation was aborted"))}}):await r},"sha256"),C=i(n=>{let r={"+":"-","/":"_","=":""};return n.replace(/[+/=]/g,s=>r[s])},"urlEncodeB64");var E=i(n=>{let r=new Uint8Array(n);return C(window.btoa(String.fromCharCode(...Array.from(r))))},"bufferToBase64UrlEncoded"),I=i((n,r,s=60)=>new Promise((t,e)=>{let o=window.document.createElement("iframe");o.setAttribute("id","authorizer-iframe"),o.setAttribute("width","0"),o.setAttribute("height","0"),o.style.display="none";let a=i(()=>{window.document.body.contains(o)&&(window.document.body.removeChild(o),window.removeEventListener("message",g,!1))},"removeIframe"),T=setTimeout(()=>{a()},s*1e3),g=i(function(h){if(h.origin!==r||!h.data||!h.data.response)return;let b=h.source;b&&b.close(),h.data.response.error?e(h.data.response):t(h.data.response),clearTimeout(T),window.removeEventListener("message",g,!1),setTimeout(a,2*1e3)},"iframeEventHandler");window.addEventListener("message",g,!1),window.document.body.appendChild(o),o.setAttribute("src",n)}),"executeIframe");var w="id email email_verified given_name family_name middle_name nickname preferred_username picture signup_methods gender birthdate phone_number phone_number_verified roles created_at updated_at is_multi_factor_auth_enabled app_data",l=`message access_token expires_in refresh_token id_token should_show_email_otp_screen should_show_mobile_otp_screen should_show_totp_screen authenticator_scanner_image authenticator_secret authenticator_recovery_codes user { ${w} }`,y=i(()=>p()?window.fetch:O,"getFetcher"),R=class R{config;codeVerifier;constructor(r){if(!r)throw new Error("Configuration is required");if(this.config=r,!r.authorizerURL&&!r.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(!r.clientID&&!r.clientID.trim())throw new Error("Invalid clientID");if(r.authorizerURL&&(this.config.authorizerURL=m(r.authorizerURL)),!r.redirectURL&&!r.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=m(r.redirectURL),this.config.extraHeaders={...r.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"x-authorizer-client-id":this.config.clientID,"Content-Type":"application/json"},this.config.clientID=r.clientID.trim()}authorize=async r=>{if(!p())return this.errorResponse([new Error("this feature is only supported in browser")]);let s=["openid","profile","email"];r.use_refresh_token&&s.push("offline_access");let t={redirect_uri:this.config.redirectURL,response_mode:r.response_mode||"web_message",state:c(u()),nonce:c(u()),response_type:r.response_type,scope:s.join(" "),client_id:this.config.clientID};if(r.response_type===d.Code){this.codeVerifier=u();let o=await $(this.codeVerifier),a=E(o);t.code_challenge=a}let e=`${this.config.authorizerURL}/authorize?${v(t)}`;if(t.response_mode!=="web_message")return window.location.replace(e),this.okResponse(void 0);try{let o=await I(e,this.config.authorizerURL,60);if(r.response_type===d.Code){let a=await this.getToken({code:o.code});return a.errors.length?this.errorResponse(a.errors):this.okResponse(a.data)}return this.okResponse(o)}catch(o){return o.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(o)}};browserLogin=async()=>{try{let r=await this.getSession();return r.errors.length?this.errorResponse(r.errors):this.okResponse(r.data)}catch(r){return p()?(window.location.replace(`${this.config.authorizerURL}/app?state=${c(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),this.errorResponse(r)):{data:void 0,errors:[new Error("browserLogin is only supported for browsers")]}}};forgotPassword=async r=>{var s;r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);try{let t=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message should_show_mobile_otp_screen } }",variables:{data:r}});return(s=t==null?void 0:t.errors)!=null&&s.length?this.errorResponse(t.errors):this.okResponse(t==null?void 0:t.data.forgot_password)}catch(t){return this.errorResponse([t])}};getMetaData=async()=>{var r;try{let s=await this.graphqlQuery({query:"query { meta { version client_id is_google_login_enabled is_facebook_login_enabled is_github_login_enabled is_linkedin_login_enabled is_apple_login_enabled is_twitter_login_enabled is_microsoft_login_enabled is_twitch_login_enabled is_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled is_multi_factor_auth_enabled is_mobile_basic_authentication_enabled is_phone_verification_enabled } }"});return(r=s==null?void 0:s.errors)!=null&&r.length?this.errorResponse(s.errors):this.okResponse(s.data.meta)}catch(s){return this.errorResponse([s])}};getProfile=async r=>{var s;try{let t=await this.graphqlQuery({query:`query { profile { ${w} } }`,headers:r});return(s=t==null?void 0:t.errors)!=null&&s.length?this.errorResponse(t.errors):this.okResponse(t.data.profile)}catch(t){return this.errorResponse([t])}};getSession=async(r,s)=>{var t,e;try{let o=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${l} } }`,headers:r,variables:{params:s}});return(t=o==null?void 0:o.errors)!=null&&t.length?this.errorResponse(o.errors):this.okResponse((e=o.data)==null?void 0:e.session)}catch(o){return this.errorResponse(o)}};getToken=async r=>{if(r.grant_type||(r.grant_type="authorization_code"),r.grant_type==="refresh_token"&&!r.refresh_token)return this.errorResponse([new Error("Invalid refresh_token")]);if(r.grant_type==="authorization_code"&&!this.codeVerifier)return this.errorResponse([new Error("Invalid code verifier")]);let s={client_id:this.config.clientID,code:r.code||"",code_verifier:this.codeVerifier||"",grant_type:r.grant_type||"",refresh_token:r.refresh_token||""};try{let e=await y()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(s),headers:{...this.config.extraHeaders},credentials:"include"}),o=await e.json();return e.status>=400?this.errorResponse([new Error(o.error_description||o.error)]):this.okResponse(o)}catch(t){return this.errorResponse(t)}};login=async r=>{var s,t;try{let e=await this.graphqlQuery({query:`
|
|
2
2
|
mutation login($data: LoginInput!) { login(params: $data) { ${l}}}
|
|
3
3
|
`,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.login)}catch(e){return this.errorResponse([new Error(e)])}};logout=async r=>{var s,t;try{let e=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:r});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.response)}catch(e){return this.errorResponse([e])}};magicLinkLogin=async r=>{var s,t;try{r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);let e=await this.graphqlQuery({query:`
|
|
4
4
|
mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }}
|
|
@@ -12,4 +12,4 @@ var q=Object.defineProperty;var i=(n,r)=>q(n,"name",{value:r,configurable:!0});i
|
|
|
12
12
|
mutation resendVerifyEmail($data: ResendVerifyEmailInput!) { resend_verify_email(params: $data) { message }}
|
|
13
13
|
`,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.verify_email)}catch(e){return this.errorResponse([e])}};verifyOtp=async r=>{var s,t;try{let e=await this.graphqlQuery({query:`
|
|
14
14
|
mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${l}}}
|
|
15
|
-
`,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.verify_otp)}catch(e){return this.errorResponse([e])}};graphqlQuery=async r=>{var o;let e=await(await y()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:r.query,variables:r.variables||{}}),headers:{...this.config.extraHeaders,...r.headers||{}},credentials:"include"})).json();return(o=e==null?void 0:e.errors)!=null&&o.length?{data:void 0,errors:e.errors}:{data:e.data,errors:[]}};errorResponse=r=>({data:void 0,errors:r});okResponse=r=>({data:r,errors:[]})};i(R,"Authorizer");var
|
|
15
|
+
`,variables:{data:r}});return(s=e==null?void 0:e.errors)!=null&&s.length?this.errorResponse(e.errors):this.okResponse((t=e.data)==null?void 0:t.verify_otp)}catch(e){return this.errorResponse([e])}};graphqlQuery=async r=>{var o;let e=await(await y()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:r.query,variables:r.variables||{}}),headers:{...this.config.extraHeaders,...r.headers||{}},credentials:"include"})).json();return(o=e==null?void 0:e.errors)!=null&&o.length?{data:void 0,errors:e.errors}:{data:e.data,errors:[]}};errorResponse=r=>({data:void 0,errors:r});okResponse=r=>({data:r,errors:[]})};i(R,"Authorizer");var U=R;export{U as Authorizer,_ as OAuthProviders,d as ResponseTypes};
|