@authorizerdev/authorizer-js 2.0.0-beta.0 → 2.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/authorizer.min.js +1 -1
- package/lib/index.d.mts +2 -1
- package/lib/index.d.ts +2 -1
- package/lib/index.js +1 -1
- package/lib/index.mjs +1 -1
- package/package.json +1 -1
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 } }",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 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:`
|
|
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 }}
|
package/lib/index.d.mts
CHANGED
package/lib/index.d.ts
CHANGED
package/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var x=Object.create;var l=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var i=(o,r)=>l(o,"name",{value:r,configurable:!0});var D=(o,r)=>{for(var t in r)l(o,t,{get:r[t],enumerable:!0})},$=(o,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let e of O(r))!z.call(o,e)&&e!==t&&l(o,e,{get:()=>r[e],enumerable:!(s=C(r,e))||s.enumerable});return o};var A=(o,r,t)=>(t=o!=null?x(Q(o)):{},$(r||!o||!o.__esModule?l(t,"default",{value:o,enumerable:!0}):t,o)),N=o=>$(l({},"__esModule",{value:!0}),o);var H={};D(H,{Authorizer:()=>b,OAuthProviders:()=>_,ResponseTypes:()=>d});module.exports=N(H);var I=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 r=o.trim();return r[r.length-1]==="/"&&(r=r.slice(0,-1)),r},"trimURL"),U=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),F=i(()=>{let o=U();return o&&o.subtle||o.webkitSubtle},"getCryptoSubtle"),u=i(()=>{let o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",r="",t=U();return t&&Array.from(t.getRandomValues(new Uint8Array(43))).forEach(e=>r+=o[e%o.length]),r},"createRandomString"),c=i(o=>p()?btoa(o):Buffer.from(o).toString("base64"),"encode");var E=i(o=>Object.keys(o).filter(r=>typeof o[r]<"u").map(r=>`${encodeURIComponent(r)}=${encodeURIComponent(o[r])}`).join("&"),"createQueryParams"),T=i(async o=>{let r=F().digest({name:"SHA-256"},new TextEncoder().encode(o));return window.msCrypto?new Promise((t,s)=>{r.oncomplete=e=>{t(e.target.result)},r.onerror=e=>{s(e.error)},r.onabort=()=>{s(new Error("The digest operation was aborted"))}}):await r},"sha256"),M=i(o=>{let r={"+":"-","/":"_","=":""};return o.replace(/[+/=]/g,t=>r[t])},"urlEncodeB64");var L=i(o=>{let r=new Uint8Array(o);return M(window.btoa(String.fromCharCode(...Array.from(r))))},"bufferToBase64UrlEncoded"),q=i((o,r,t=60)=>new Promise((s,e)=>{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!==r||!h.data||!h.data.response)return;let v=h.source;v&&v.close(),h.data.response.error?e(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:I.default,"getFetcher"),k=class k{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.authorizerURL&&(this.config.authorizerURL=y(r.authorizerURL)),!r.redirectURL&&!r.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=y(r.redirectURL),this.config.extraHeaders={...r.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"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 t=["openid","profile","email"];r.use_refresh_token&&t.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:r.response_mode||"web_message",state:c(u()),nonce:c(u()),response_type:r.response_type,scope:t.join(" "),client_id:this.config.clientID};if(r.response_type===d.Code){this.codeVerifier=u();let n=await T(this.codeVerifier),a=L(n);s.code_challenge=a}let e=`${this.config.authorizerURL}/authorize?${E(s)}`;if(s.response_mode!=="web_message")return window.location.replace(e),this.okResponse(void 0);try{let n=await q(e,this.config.authorizerURL,60);if(r.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 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 t;r.state||(r.state=c(u())),r.redirect_uri||(r.redirect_uri=this.config.redirectURL);try{let s=await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:r}});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 r;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(r=t==null?void 0:t.errors)!=null&&r.length?this.errorResponse(t.errors):this.okResponse(t.data.meta)}catch(t){return this.errorResponse([t])}};getProfile=async r=>{var t;try{let s=await this.graphqlQuery({query:`query { profile { ${R} } }`,headers:r});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(r,t)=>{var s,e;try{let n=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${g} } }`,headers:r,variables:{params:t}});return(s=n==null?void 0:n.errors)!=null&&s.length?this.errorResponse(n.errors):this.okResponse((e=n.data)==null?void 0:e.session)}catch(n){return this.errorResponse(n)}};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 t={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 w()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:{...this.config.extraHeaders},credentials:"include"}),n=await e.json();return e.status>=400?this.errorResponse([new Error(n.error_description||n.error)]):this.okResponse(n)}catch(s){return this.errorResponse(s)}};login=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`
|
|
1
|
+
var x=Object.create;var l=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var i=(o,r)=>l(o,"name",{value:r,configurable:!0});var D=(o,r)=>{for(var t in r)l(o,t,{get:r[t],enumerable:!0})},$=(o,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let e of O(r))!z.call(o,e)&&e!==t&&l(o,e,{get:()=>r[e],enumerable:!(s=C(r,e))||s.enumerable});return o};var A=(o,r,t)=>(t=o!=null?x(Q(o)):{},$(r||!o||!o.__esModule?l(t,"default",{value:o,enumerable:!0}):t,o)),N=o=>$(l({},"__esModule",{value:!0}),o);var H={};D(H,{Authorizer:()=>b,OAuthProviders:()=>_,ResponseTypes:()=>d});module.exports=N(H);var I=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 r=o.trim();return r[r.length-1]==="/"&&(r=r.slice(0,-1)),r},"trimURL"),U=i(()=>p()?window.crypto||window.msCrypto:null,"getCrypto"),F=i(()=>{let o=U();return o&&o.subtle||o.webkitSubtle},"getCryptoSubtle"),u=i(()=>{let o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",r="",t=U();return t&&Array.from(t.getRandomValues(new Uint8Array(43))).forEach(e=>r+=o[e%o.length]),r},"createRandomString"),c=i(o=>p()?btoa(o):Buffer.from(o).toString("base64"),"encode");var E=i(o=>Object.keys(o).filter(r=>typeof o[r]<"u").map(r=>`${encodeURIComponent(r)}=${encodeURIComponent(o[r])}`).join("&"),"createQueryParams"),T=i(async o=>{let r=F().digest({name:"SHA-256"},new TextEncoder().encode(o));return window.msCrypto?new Promise((t,s)=>{r.oncomplete=e=>{t(e.target.result)},r.onerror=e=>{s(e.error)},r.onabort=()=>{s(new Error("The digest operation was aborted"))}}):await r},"sha256"),M=i(o=>{let r={"+":"-","/":"_","=":""};return o.replace(/[+/=]/g,t=>r[t])},"urlEncodeB64");var L=i(o=>{let r=new Uint8Array(o);return M(window.btoa(String.fromCharCode(...Array.from(r))))},"bufferToBase64UrlEncoded"),q=i((o,r,t=60)=>new Promise((s,e)=>{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!==r||!h.data||!h.data.response)return;let v=h.source;v&&v.close(),h.data.response.error?e(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:I.default,"getFetcher"),k=class k{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.authorizerURL&&(this.config.authorizerURL=y(r.authorizerURL)),!r.redirectURL&&!r.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=y(r.redirectURL),this.config.extraHeaders={...r.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"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 t=["openid","profile","email"];r.use_refresh_token&&t.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:r.response_mode||"web_message",state:c(u()),nonce:c(u()),response_type:r.response_type,scope:t.join(" "),client_id:this.config.clientID};if(r.response_type===d.Code){this.codeVerifier=u();let n=await T(this.codeVerifier),a=L(n);s.code_challenge=a}let e=`${this.config.authorizerURL}/authorize?${E(s)}`;if(s.response_mode!=="web_message")return window.location.replace(e),this.okResponse(void 0);try{let n=await q(e,this.config.authorizerURL,60);if(r.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 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 t;r.state||(r.state=c(u())),r.redirect_uri||(r.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:r}});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 r;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(r=t==null?void 0:t.errors)!=null&&r.length?this.errorResponse(t.errors):this.okResponse(t.data.meta)}catch(t){return this.errorResponse([t])}};getProfile=async r=>{var t;try{let s=await this.graphqlQuery({query:`query { profile { ${R} } }`,headers:r});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(r,t)=>{var s,e;try{let n=await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${g} } }`,headers:r,variables:{params:t}});return(s=n==null?void 0:n.errors)!=null&&s.length?this.errorResponse(n.errors):this.okResponse((e=n.data)==null?void 0:e.session)}catch(n){return this.errorResponse(n)}};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 t={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 w()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:{...this.config.extraHeaders},credentials:"include"}),n=await e.json();return e.status>=400?this.errorResponse([new Error(n.error_description||n.error)]):this.okResponse(n)}catch(s){return this.errorResponse(s)}};login=async r=>{var t,s;try{let e=await this.graphqlQuery({query:`
|
|
2
2
|
mutation login($data: LoginInput!) { login(params: $data) { ${g}}}
|
|
3
3
|
`,variables:{data:r}});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.login)}catch(e){return this.errorResponse([new Error(e)])}};logout=async r=>{var t,s;try{let e=await this.graphqlQuery({query:" mutation { logout { message } } ",headers:r});return(t=e==null?void 0:e.errors)!=null&&t.length?this.errorResponse(e.errors):this.okResponse((s=e.data)==null?void 0:s.response)}catch(e){return this.errorResponse([e])}};magicLinkLogin=async r=>{var t,s;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 }}
|
package/lib/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var q=Object.defineProperty;var i=(n,r)=>q(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 U=i(n=>{let r=new Uint8Array(n);return C(window.btoa(String.fromCharCode(...Array.from(r))))},"bufferToBase64UrlEncoded"),E=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"),L=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(L),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.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,"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=U(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 E(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 } }",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:`
|
|
1
|
+
var q=Object.defineProperty;var i=(n,r)=>q(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 U=i(n=>{let r=new Uint8Array(n);return C(window.btoa(String.fromCharCode(...Array.from(r))))},"bufferToBase64UrlEncoded"),E=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"),L=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(L),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.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,"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=U(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 E(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 }}
|