@authorizerdev/authorizer-js 1.2.1 → 1.2.2-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/README.md CHANGED
@@ -18,12 +18,12 @@ All the above versions require `Authorizer` instance to be instantiated and used
18
18
 
19
19
  ```js
20
20
  const authRef = new Authorizer({
21
- authorizerURL: 'https://app.herokuapp.com',
22
- redirectURL: window.location.origin,
21
+ authorizerURL: "https://app.herokuapp.com",
22
+ redirectURL: window.location.origin,
23
23
  });
24
24
  ```
25
25
 
26
- ## UMD
26
+ ## IIFE
27
27
 
28
28
  - Step 1: Load Javascript using CDN
29
29
 
@@ -35,35 +35,35 @@ const authRef = new Authorizer({
35
35
 
36
36
  ```html
37
37
  <script type="text/javascript">
38
- const authorizerRef = new authorizerdev.Authorizer({
39
- authorizerURL: `AUTHORIZER_URL`,
40
- redirectURL: window.location.origin,
41
- clientID: 'YOUR_CLIENT_ID', // can be obtained from authorizer dashboard
42
- });
43
-
44
- // use the button selector as per your application
45
- const logoutBtn = document.getElementById('logout');
46
- logoutBtn.addEventListener('click', async function () {
47
- await authorizerRef.logout();
48
- window.location.href = '/';
49
- });
50
-
51
- async function onLoad() {
52
- const res = await authorizerRef.authorize({
53
- response_type: 'code',
54
- use_refresh_token: false,
55
- });
56
- if (res && res.access_token) {
57
- // get user profile using the access token
58
- const user = await authorizerRef.getProfile({
59
- Authorization: `Bearer ${res.access_token}`,
60
- });
61
-
62
- // logoutSection.classList.toggle('hide');
63
- // userSection.innerHTML = `Welcome, ${user.email}`;
64
- }
65
- }
66
- onLoad();
38
+ const authorizerRef = new authorizerdev.Authorizer({
39
+ authorizerURL: `AUTHORIZER_URL`,
40
+ redirectURL: window.location.origin,
41
+ clientID: "YOUR_CLIENT_ID", // can be obtained from authorizer dashboard
42
+ });
43
+
44
+ // use the button selector as per your application
45
+ const logoutBtn = document.getElementById("logout");
46
+ logoutBtn.addEventListener("click", async function () {
47
+ await authorizerRef.logout();
48
+ window.location.href = "/";
49
+ });
50
+
51
+ async function onLoad() {
52
+ const res = await authorizerRef.authorize({
53
+ response_type: "code",
54
+ use_refresh_token: false,
55
+ });
56
+ if (res && res.access_token) {
57
+ // get user profile using the access token
58
+ const user = await authorizerRef.getProfile({
59
+ Authorization: `Bearer ${res.access_token}`,
60
+ });
61
+
62
+ // logoutSection.classList.toggle('hide');
63
+ // userSection.innerHTML = `Welcome, ${user.email}`;
64
+ }
65
+ }
66
+ onLoad();
67
67
  </script>
68
68
  ```
69
69
 
@@ -80,18 +80,18 @@ yarn add @authorizerdev/authoirzer-js
80
80
  - Step 2: Import and initialize the authorizer instance
81
81
 
82
82
  ```js
83
- const { Authorizer } = require('@authorizerdev/authoirzer-js');
83
+ const { Authorizer } = require("@authorizerdev/authoirzer-js");
84
84
 
85
85
  const authRef = new Authorizer({
86
- authorizerURL: 'https://app.heroku.com',
87
- redirectURL: 'http://app.heroku.com/app',
86
+ authorizerURL: "https://app.heroku.com",
87
+ redirectURL: "http://app.heroku.com/app",
88
88
  });
89
89
 
90
90
  async function main() {
91
- await authRef.login({
92
- email: 'foo@bar.com',
93
- password: 'test',
94
- });
91
+ await authRef.login({
92
+ email: "foo@bar.com",
93
+ password: "test",
94
+ });
95
95
  }
96
96
  ```
97
97
 
@@ -108,34 +108,35 @@ yarn add @authorizerdev/authorizer-js
108
108
  - Step 2: Import and initialize the authorizer instance
109
109
 
110
110
  ```js
111
- import { Authorizer } from '@authorizerdev/authorizer-js';
111
+ import { Authorizer } from "@authorizerdev/authorizer-js";
112
112
 
113
113
  const authRef = new Authorizer({
114
- authorizerURL: 'https://app.heroku.com',
115
- redirectURL: 'http://app.heroku.com/app',
114
+ authorizerURL: "https://app.heroku.com",
115
+ redirectURL: "http://app.heroku.com/app",
116
116
  });
117
117
 
118
118
  async function main() {
119
- await authRef.login({
120
- email: 'foo@bar.com',
121
- password: 'test',
122
- });
119
+ await authRef.login({
120
+ email: "foo@bar.com",
121
+ password: "test",
122
+ });
123
123
  }
124
124
  ```
125
125
 
126
-
127
126
  ## Local Development Setup
128
127
 
129
128
  ### Prerequisites
129
+
130
130
  - [Pnpm](https://pnpm.io/installation)
131
131
  - [NodeJS](https://nodejs.org/en/download/)
132
132
 
133
133
  ### Setup
134
+
134
135
  - Clone the repository
135
136
  - Install dependencies using `pnpm install`
136
137
  - Run `pnpm build` to build the library
137
138
  - Run `pnpm test` to run the tests
138
139
 
139
-
140
140
  ### Release
141
- - Run `pnpm release` to release a new version of the library
141
+
142
+ - Run `pnpm release` to release a new version of the library
@@ -1,2 +1,14 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("cross-fetch")):"function"==typeof define&&define.amd?define(["exports","cross-fetch"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).authorizerdev={},e.crossFetch)}(this,(function(e,t){"use strict";function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=r(t);function o(e,t,r,i){return new(r||(r=Promise))((function(o,n){function s(e){try{d(i.next(e))}catch(e){n(e)}}function a(e){try{d(i.throw(e))}catch(e){n(e)}}function d(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}d((i=i.apply(e,t||[])).next())}))}var n,s;e.OAuthProviders=void 0,(n=e.OAuthProviders||(e.OAuthProviders={})).Apple="apple",n.Github="github",n.Google="google",n.Facebook="facebook",n.LinkedIn="linkedin",e.ResponseTypes=void 0,(s=e.ResponseTypes||(e.ResponseTypes={})).Code="code",s.Token="token";const a=()=>"undefined"!=typeof window,d=e=>{let t=e.trim();return"/"===t[t.length-1]&&(t=t.slice(0,-1)),t},c=()=>a()?window.crypto||window.msCrypto:null,h=()=>{const e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.";let t="";const r=c();if(r){Array.from(r.getRandomValues(new Uint8Array(43))).forEach((r=>t+=e[r%e.length]))}return t},u=e=>a()?btoa(e):Buffer.from(e).toString("base64"),l=e=>o(void 0,void 0,void 0,(function*(){const t=(()=>{const e=c();return e&&e.subtle||e.webkitSubtle})().digest({name:"SHA-256"},(new TextEncoder).encode(e));return window.msCrypto?new Promise(((e,r)=>{t.oncomplete=t=>{e(t.target.result)},t.onerror=e=>{r(e.error)},t.onabort=()=>{r(new Error("The digest operation was aborted"))}})):yield t})),f="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 ",p=`message access_token expires_in refresh_token id_token should_show_otp_screen user { ${f} }`,g=()=>a()?window.fetch:i.default;e.Authorizer=class{constructor(t){if(this.authorize=t=>o(this,void 0,void 0,(function*(){if(!a())throw new Error("this feature is only supported in browser");const r=["openid","profile","email"];t.use_refresh_token&&r.push("offline_access");const i={redirect_uri:this.config.redirectURL,response_mode:t.response_mode||"web_message",state:u(h()),nonce:u(h()),response_type:t.response_type,scope:r.join(" "),client_id:this.config.clientID};if(t.response_type===e.ResponseTypes.Code){this.codeVerifier=h();const e=(e=>{const t=new Uint8Array(e);return(e=>{const t={"+":"-","/":"_","=":""};return e.replace(/[+/=]/g,(e=>t[e]))})(window.btoa(String.fromCharCode(...Array.from(t))))})(yield l(this.codeVerifier));i.code_challenge=e}const o=`${this.config.authorizerURL}/authorize?${n=i,Object.keys(n).filter((e=>void 0!==n[e])).map((e=>`${encodeURIComponent(e)}=${encodeURIComponent(n[e])}`)).join("&")}`;var n;if("web_message"===i.response_mode)try{const r=yield((e,t,r=60)=>new Promise(((i,o)=>{const n=window.document.createElement("iframe");let s;n.setAttribute("id","authorizer-iframe"),n.setAttribute("width","0"),n.setAttribute("height","0"),n.style.display="none";const a=()=>{window.document.body.contains(n)&&(window.document.body.removeChild(n),window.removeEventListener("message",s,!1))},d=setTimeout((()=>{a()}),1e3*r);s=function(e){if(e.origin!==t)return;if(!e.data||!e.data.response)return;const r=e.source;r&&r.close(),e.data.response.error?o(e.data.response):i(e.data.response),clearTimeout(d),window.removeEventListener("message",s,!1),setTimeout(a,2e3)},window.addEventListener("message",s,!1),window.document.body.appendChild(n),n.setAttribute("src",e)})))(o,this.config.authorizerURL,60);if(t.response_type===e.ResponseTypes.Code){return yield this.getToken({code:r.code})}return r}catch(e){throw e.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${u(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),e}else window.location.replace(o)})),this.browserLogin=()=>o(this,void 0,void 0,(function*(){try{return yield this.getSession()}catch(e){if(!a())throw new Error("browserLogin is only supported for browsers");window.location.replace(`${this.config.authorizerURL}/app?state=${u(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`)}})),this.forgotPassword=e=>o(this,void 0,void 0,(function*(){e.state||(e.state=u(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{return(yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) {\tforgot_password(params: $data) { message } }",variables:{data:e}})).forgot_password}catch(e){throw new Error(e)}})),this.getMetaData=()=>o(this,void 0,void 0,(function*(){try{return(yield this.graphqlQuery({query:"query { meta { version 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_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"})).meta}catch(e){throw new Error(e)}})),this.getProfile=e=>o(this,void 0,void 0,(function*(){try{return(yield this.graphqlQuery({query:`query {\tprofile { ${f} } }`,headers:e})).profile}catch(e){throw new Error(e)}})),this.getSession=(e,t)=>o(this,void 0,void 0,(function*(){try{return(yield this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${p} } }`,headers:e,variables:{params:t}})).session}catch(e){throw new Error(e)}})),this.getToken=e=>o(this,void 0,void 0,(function*(){if(e.grant_type||(e.grant_type="authorization_code"),"refresh_token"===e.grant_type&&!e.refresh_token)throw new Error("Invalid refresh_token");if("authorization_code"===e.grant_type&&!this.codeVerifier)throw new Error("Invalid code verifier");const t={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{const e=g(),r=yield e(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:Object.assign({},this.config.extraHeaders),credentials:"include"}),i=yield r.json();if(r.status>=400)throw new Error(i);return i}catch(e){throw new Error(e)}})),this.graphqlQuery=e=>o(this,void 0,void 0,(function*(){const t=g(),r=yield t(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:Object.assign(Object.assign({},this.config.extraHeaders),e.headers||{}),credentials:"include"}),i=yield r.json();if(i.errors&&i.errors.length)throw console.error(i.errors),new Error(i.errors[0].message);return i.data})),this.login=e=>o(this,void 0,void 0,(function*(){try{return(yield this.graphqlQuery({query:`\n\t\t\t\t\tmutation login($data: LoginInput!) { login(params: $data) { ${p}}}\n\t\t\t\t`,variables:{data:e}})).login}catch(e){throw new Error(e)}})),this.logout=e=>o(this,void 0,void 0,(function*(){try{return(yield this.graphqlQuery({query:" mutation { logout { message } } ",headers:e})).logout}catch(e){console.error(e)}})),this.magicLinkLogin=e=>o(this,void 0,void 0,(function*(){try{e.state||(e.state=u(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);return(yield this.graphqlQuery({query:"\n\t\t\t\t\tmutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }}\n\t\t\t\t",variables:{data:e}})).magic_link_login}catch(e){throw new Error(e)}})),this.oauthLogin=(t,r,i,n)=>o(this,void 0,void 0,(function*(){let o=n;if(o||(o=u(h())),!Object.values(e.OAuthProviders).includes(t))throw new Error(`only following oauth providers are supported: ${Object.values(t).toString()}`);if(!a())throw new Error("oauthLogin is only supported for browsers");window.location.replace(`${this.config.authorizerURL}/oauth_login/${t}?redirect_uri=${i||this.config.redirectURL}&state=${o}${r&&r.length?`&roles=${r.join(",")}`:""}`)})),this.resendOtp=e=>o(this,void 0,void 0,(function*(){try{return(yield this.graphqlQuery({query:"\n\t\t\t\t\tmutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}\n\t\t\t\t",variables:{data:e}})).resend_otp}catch(e){throw new Error(e)}})),this.resetPassword=e=>o(this,void 0,void 0,(function*(){try{return(yield this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) {\treset_password(params: $data) { message } }",variables:{data:e}})).reset_password}catch(e){throw new Error(e)}})),this.revokeToken=e=>o(this,void 0,void 0,(function*(){if(!e.refresh_token&&!e.refresh_token.trim())throw new Error("Invalid refresh_token");const t=g(),r=yield t(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:Object.assign({},this.config.extraHeaders),body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})});return yield r.json()})),this.signup=e=>o(this,void 0,void 0,(function*(){try{return(yield this.graphqlQuery({query:`\n\t\t\t\t\tmutation signup($data: SignUpInput!) { signup(params: $data) { ${p}}}\n\t\t\t\t`,variables:{data:e}})).signup}catch(e){throw new Error(e)}})),this.updateProfile=(e,t)=>o(this,void 0,void 0,(function*(){try{return(yield this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) {\tupdate_profile(params: $data) { message } }",headers:t,variables:{data:e}})).update_profile}catch(e){throw new Error(e)}})),this.validateJWTToken=e=>o(this,void 0,void 0,(function*(){try{return(yield this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}})).validate_jwt_token}catch(e){throw new Error(e)}})),this.verifyEmail=e=>o(this,void 0,void 0,(function*(){try{return(yield this.graphqlQuery({query:`\n\t\t\t\t\tmutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${p}}}\n\t\t\t\t`,variables:{data:e}})).verify_email}catch(e){throw new Error(e)}})),this.verifyOtp=e=>o(this,void 0,void 0,(function*(){try{return(yield this.graphqlQuery({query:`\n\t\t\t\t\tmutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${p}}}\n\t\t\t\t`,variables:{data:e}})).verify_otp}catch(e){throw new Error(e)}})),!t)throw new Error("Configuration is required");if(this.config=t,!t.authorizerURL&&!t.authorizerURL.trim())throw new Error("Invalid authorizerURL");if(t.authorizerURL&&(this.config.authorizerURL=d(t.authorizerURL)),!t.redirectURL&&!t.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=d(t.redirectURL),this.config.extraHeaders=Object.assign(Object.assign({},t.extraHeaders||{}),{"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"}),this.config.clientID=t.clientID.trim()}}}));
2
- //# sourceMappingURL=authorizer.min.js.map
1
+ var __AUTHORIZER_JS__=(()=>{var pe=Object.create;var A=Object.defineProperty,ye=Object.defineProperties,we=Object.getOwnPropertyDescriptor,me=Object.getOwnPropertyDescriptors,_e=Object.getOwnPropertyNames,V=Object.getOwnPropertySymbols,ge=Object.getPrototypeOf,J=Object.prototype.hasOwnProperty,be=Object.prototype.propertyIsEnumerable;var j=(o,e,t)=>e in o?A(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,O=(o,e)=>{for(var t in e||(e={}))J.call(e,t)&&j(o,t,e[t]);if(V)for(var t of V(e))be.call(e,t)&&j(o,t,e[t]);return o},G=(o,e)=>ye(o,me(e)),n=(o,e)=>A(o,"name",{value:e,configurable:!0});var Ee=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),ve=(o,e)=>{for(var t in e)A(o,t,{get:e[t],enumerable:!0})},W=(o,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of _e(e))!J.call(o,c)&&c!==t&&A(o,c,{get:()=>e[c],enumerable:!(s=we(e,c))||s.enumerable});return o};var Te=(o,e,t)=>(t=o!=null?pe(ge(o)):{},W(e||!o||!o.__esModule?A(t,"default",{value:o,enumerable:!0}):t,o)),Re=o=>W(A({},"__esModule",{value:!0}),o);var l=(o,e,t)=>(j(o,typeof e!="symbol"?e+"":e,t),t);var f=(o,e,t)=>new Promise((s,c)=>{var u=_=>{try{m(t.next(_))}catch(w){c(w)}},g=_=>{try{m(t.throw(_))}catch(w){c(w)}},m=_=>_.done?s(_.value):Promise.resolve(_.value).then(u,g);m((t=t.apply(o,e)).next())});var K=Ee((E,X)=>{var Z=typeof self!="undefined"?self:E,P=function(){function o(){this.fetch=!1,this.DOMException=Z.DOMException}return n(o,"F"),o.prototype=Z,new o}();(function(o){var e=function(t){var s={searchParams:"URLSearchParams"in o,iterable:"Symbol"in o&&"iterator"in Symbol,blob:"FileReader"in o&&"Blob"in o&&function(){try{return new Blob,!0}catch(r){return!1}}(),formData:"FormData"in o,arrayBuffer:"ArrayBuffer"in o};function c(r){return r&&DataView.prototype.isPrototypeOf(r)}if(n(c,"isDataView"),s.arrayBuffer)var u=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],g=ArrayBuffer.isView||function(r){return r&&u.indexOf(Object.prototype.toString.call(r))>-1};function m(r){if(typeof r!="string"&&(r=String(r)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(r))throw new TypeError("Invalid character in header field name");return r.toLowerCase()}n(m,"normalizeName");function _(r){return typeof r!="string"&&(r=String(r)),r}n(_,"normalizeValue");function w(r){var i={next:function(){var a=r.shift();return{done:a===void 0,value:a}}};return s.iterable&&(i[Symbol.iterator]=function(){return i}),i}n(w,"iteratorFor");function d(r){this.map={},r instanceof d?r.forEach(function(i,a){this.append(a,i)},this):Array.isArray(r)?r.forEach(function(i){this.append(i[0],i[1])},this):r&&Object.getOwnPropertyNames(r).forEach(function(i){this.append(i,r[i])},this)}n(d,"Headers"),d.prototype.append=function(r,i){r=m(r),i=_(i);var a=this.map[r];this.map[r]=a?a+", "+i:i},d.prototype.delete=function(r){delete this.map[m(r)]},d.prototype.get=function(r){return r=m(r),this.has(r)?this.map[r]:null},d.prototype.has=function(r){return this.map.hasOwnProperty(m(r))},d.prototype.set=function(r,i){this.map[m(r)]=_(i)},d.prototype.forEach=function(r,i){for(var a in this.map)this.map.hasOwnProperty(a)&&r.call(i,this.map[a],a,this)},d.prototype.keys=function(){var r=[];return this.forEach(function(i,a){r.push(a)}),w(r)},d.prototype.values=function(){var r=[];return this.forEach(function(i){r.push(i)}),w(r)},d.prototype.entries=function(){var r=[];return this.forEach(function(i,a){r.push([a,i])}),w(r)},s.iterable&&(d.prototype[Symbol.iterator]=d.prototype.entries);function B(r){if(r.bodyUsed)return Promise.reject(new TypeError("Already read"));r.bodyUsed=!0}n(B,"consumed");function H(r){return new Promise(function(i,a){r.onload=function(){i(r.result)},r.onerror=function(){a(r.error)}})}n(H,"fileReaderReady");function se(r){var i=new FileReader,a=H(i);return i.readAsArrayBuffer(r),a}n(se,"readBlobAsArrayBuffer");function ae(r){var i=new FileReader,a=H(i);return i.readAsText(r),a}n(ae,"readBlobAsText");function ce(r){for(var i=new Uint8Array(r),a=new Array(i.length),y=0;y<i.length;y++)a[y]=String.fromCharCode(i[y]);return a.join("")}n(ce,"readArrayBufferAsText");function N(r){if(r.slice)return r.slice(0);var i=new Uint8Array(r.byteLength);return i.set(new Uint8Array(r)),i.buffer}n(N,"bufferClone");function Q(){return this.bodyUsed=!1,this._initBody=function(r){this._bodyInit=r,r?typeof r=="string"?this._bodyText=r:s.blob&&Blob.prototype.isPrototypeOf(r)?this._bodyBlob=r:s.formData&&FormData.prototype.isPrototypeOf(r)?this._bodyFormData=r:s.searchParams&&URLSearchParams.prototype.isPrototypeOf(r)?this._bodyText=r.toString():s.arrayBuffer&&s.blob&&c(r)?(this._bodyArrayBuffer=N(r.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(r)||g(r))?this._bodyArrayBuffer=N(r):this._bodyText=r=Object.prototype.toString.call(r):this._bodyText="",this.headers.get("content-type")||(typeof r=="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(r)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},s.blob&&(this.blob=function(){var r=B(this);if(r)return r;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(se)}),this.text=function(){var r=B(this);if(r)return r;if(this._bodyBlob)return ae(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(ce(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(fe)}),this.json=function(){return this.text().then(JSON.parse)},this}n(Q,"Body");var ue=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function he(r){var i=r.toUpperCase();return ue.indexOf(i)>-1?i:r}n(he,"normalizeMethod");function T(r,i){i=i||{};var a=i.body;if(r instanceof T){if(r.bodyUsed)throw new TypeError("Already read");this.url=r.url,this.credentials=r.credentials,i.headers||(this.headers=new d(r.headers)),this.method=r.method,this.mode=r.mode,this.signal=r.signal,!a&&r._bodyInit!=null&&(a=r._bodyInit,r.bodyUsed=!0)}else this.url=String(r);if(this.credentials=i.credentials||this.credentials||"same-origin",(i.headers||!this.headers)&&(this.headers=new d(i.headers)),this.method=he(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")&&a)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(a)}n(T,"Request"),T.prototype.clone=function(){return new T(this,{body:this._bodyInit})};function fe(r){var i=new FormData;return r.trim().split("&").forEach(function(a){if(a){var y=a.split("="),p=y.shift().replace(/\+/g," "),h=y.join("=").replace(/\+/g," ");i.append(decodeURIComponent(p),decodeURIComponent(h))}}),i}n(fe,"decode");function de(r){var i=new d,a=r.replace(/\r?\n[\t ]+/g," ");return a.split(/\r?\n/).forEach(function(y){var p=y.split(":"),h=p.shift().trim();if(h){var q=p.join(":").trim();i.append(h,q)}}),i}n(de,"parseHeaders"),Q.call(T.prototype);function b(r,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 d(i.headers),this.url=i.url||"",this._initBody(r)}n(b,"Response"),Q.call(b.prototype),b.prototype.clone=function(){return new b(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},b.error=function(){var r=new b(null,{status:0,statusText:""});return r.type="error",r};var le=[301,302,303,307,308];b.redirect=function(r,i){if(le.indexOf(i)===-1)throw new RangeError("Invalid status code");return new b(null,{status:i,headers:{location:r}})},t.DOMException=o.DOMException;try{new t.DOMException}catch(r){t.DOMException=function(i,a){this.message=i,this.name=a;var y=Error(i);this.stack=y.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function D(r,i){return new Promise(function(a,y){var p=new T(r,i);if(p.signal&&p.signal.aborted)return y(new t.DOMException("Aborted","AbortError"));var h=new XMLHttpRequest;function q(){h.abort()}n(q,"abortXhr"),h.onload=function(){var x={status:h.status,statusText:h.statusText,headers:de(h.getAllResponseHeaders()||"")};x.url="responseURL"in h?h.responseURL:x.headers.get("X-Request-URL");var C="response"in h?h.response:h.responseText;a(new b(C,x))},h.onerror=function(){y(new TypeError("Network request failed"))},h.ontimeout=function(){y(new TypeError("Network request failed"))},h.onabort=function(){y(new t.DOMException("Aborted","AbortError"))},h.open(p.method,p.url,!0),p.credentials==="include"?h.withCredentials=!0:p.credentials==="omit"&&(h.withCredentials=!1),"responseType"in h&&s.blob&&(h.responseType="blob"),p.headers.forEach(function(x,C){h.setRequestHeader(C,x)}),p.signal&&(p.signal.addEventListener("abort",q),h.onreadystatechange=function(){h.readyState===4&&p.signal.removeEventListener("abort",q)}),h.send(typeof p._bodyInit=="undefined"?null:p._bodyInit)})}return n(D,"fetch"),D.polyfill=!0,o.fetch||(o.fetch=D,o.Headers=d,o.Request=T,o.Response=b),t.Headers=d,t.Request=T,t.Response=b,t.fetch=D,Object.defineProperty(t,"__esModule",{value:!0}),t}({})})(P);P.fetch.ponyfill=!0;delete P.fetch.polyfill;var I=P;E=I.fetch;E.default=I.fetch;E.fetch=I.fetch;E.Headers=I.Headers;E.Request=I.Request;E.Response=I.Response;X.exports=E});var Le={};ve(Le,{Authorizer:()=>$,OAuthProviders:()=>S,ResponseTypes:()=>L});var ie=Te(K());var S;(function(o){o.Apple="apple",o.Github="github",o.Google="google",o.Facebook="facebook",o.LinkedIn="linkedin"})(S||(S={}));var L;(function(o){o.Code="code",o.Token="token"})(L||(L={}));var R=n(()=>typeof window!="undefined","hasWindow"),M=n(o=>{let e=o.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),Y=n(()=>R()?window.crypto||window.msCrypto:null,"getCrypto"),Oe=n(()=>{let o=Y();return o&&o.subtle||o.webkitSubtle},"getCryptoSubtle"),U=n(()=>{let o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",t=Y();return t&&Array.from(t.getRandomValues(new Uint8Array(43))).forEach(c=>e+=o[c%o.length]),e},"createRandomString"),v=n(o=>R()?btoa(o):Buffer.from(o).toString("base64"),"encode");var ee=n(o=>Object.keys(o).filter(e=>typeof o[e]!="undefined").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(o[e])}`).join("&"),"createQueryParams"),re=n(o=>f(void 0,null,function*(){let e=Oe().digest({name:"SHA-256"},new TextEncoder().encode(o));return window.msCrypto?new Promise((t,s)=>{e.oncomplete=c=>{t(c.target.result)},e.onerror=c=>{s(c.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):yield e}),"sha256"),Ie=n(o=>{let e={"+":"-","/":"_","=":""};return o.replace(/[+/=]/g,t=>e[t])},"urlEncodeB64");var te=n(o=>{let e=new Uint8Array(o);return Ie(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),oe=n((o,e,t=60)=>new Promise((s,c)=>{let u=window.document.createElement("iframe");u.setAttribute("id","authorizer-iframe"),u.setAttribute("width","0"),u.setAttribute("height","0"),u.style.display="none";let g,m=n(()=>{window.document.body.contains(u)&&(window.document.body.removeChild(u),window.removeEventListener("message",g,!1))},"removeIframe"),_=setTimeout(()=>{m()},t*1e3);g=n(function(w){if(w.origin!==e||!w.data||!w.data.response)return;let d=w.source;d&&d.close(),w.data.response.error?c(w.data.response):s(w.data.response),clearTimeout(_),window.removeEventListener("message",g,!1),setTimeout(m,2*1e3)},"iframeEventHandler"),window.addEventListener("message",g,!1),window.document.body.appendChild(u),u.setAttribute("src",o)}),"executeIframe");var ne="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 ",k=`message access_token expires_in refresh_token id_token should_show_otp_screen user { ${ne} }`,z=n(()=>R()?window.fetch:ie.default,"getFetcher"),$=class{constructor(e){l(this,"authorize",n(e=>f(this,null,function*(){if(!R())throw 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:v(U()),nonce:v(U()),response_type:e.response_type,scope:t.join(" "),client_id:this.config.clientID};if(e.response_type===L.Code){this.codeVerifier=U();let u=yield re(this.codeVerifier),g=te(u);s.code_challenge=g}let c=`${this.config.authorizerURL}/authorize?${ee(s)}`;if(s.response_mode!=="web_message"){window.location.replace(c);return}try{let u=yield oe(c,this.config.authorizerURL,60);return e.response_type===L.Code?yield this.getToken({code:u.code}):u}catch(u){throw u.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),u}}),"authorize"));l(this,"browserLogin",n(()=>f(this,null,function*(){try{return yield this.getSession()}catch(e){if(!R())throw new Error("browserLogin is only supported for browsers");window.location.replace(`${this.config.authorizerURL}/app?state=${v(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`)}}),"browserLogin"));l(this,"forgotPassword",n(e=>f(this,null,function*(){e.state||(e.state=v(U())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{return(yield this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}})).forgot_password}catch(t){throw new Error(t)}}),"forgotPassword"));l(this,"getMetaData",n(()=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:"query { meta { version 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_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"})).meta}catch(e){throw new Error(e)}}),"getMetaData"));l(this,"getProfile",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`query { profile { ${ne} } }`,headers:e})).profile}catch(t){throw new Error(t)}}),"getProfile"));l(this,"getSession",n((e,t)=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${k} } }`,headers:e,variables:{params:t}})).session}catch(s){throw new Error(s)}}),"getSession"));l(this,"getToken",n(e=>f(this,null,function*(){if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)throw new Error("Invalid refresh_token");if(e.grant_type==="authorization_code"&&!this.codeVerifier)throw 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 c=yield z()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(t),headers:O({},this.config.extraHeaders),credentials:"include"}),u=yield c.json();if(c.status>=400)throw new Error(u);return u}catch(s){throw new Error(s)}}),"getToken"));l(this,"graphqlQuery",n(e=>f(this,null,function*(){let c=yield(yield z()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:O(O({},this.config.extraHeaders),e.headers||{}),credentials:"include"})).json();if(c.errors&&c.errors.length)throw console.error(c.errors),new Error(c.errors[0].message);return c.data}),"graphqlQuery"));l(this,"login",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`
2
+ mutation login($data: LoginInput!) { login(params: $data) { ${k}}}
3
+ `,variables:{data:e}})).login}catch(t){throw new Error(t)}}),"login"));l(this,"logout",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:" mutation { logout { message } } ",headers:e})).logout}catch(t){console.error(t)}}),"logout"));l(this,"magicLinkLogin",n(e=>f(this,null,function*(){try{return e.state||(e.state=v(U())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL),(yield this.graphqlQuery({query:`
4
+ mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }}
5
+ `,variables:{data:e}})).magic_link_login}catch(t){throw new Error(t)}}),"magicLinkLogin"));l(this,"oauthLogin",n((e,t,s,c)=>f(this,null,function*(){let u=c;if(u||(u=v(U())),!Object.values(S).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!R())throw new Error("oauthLogin is only supported for browsers");window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${s||this.config.redirectURL}&state=${u}${t&&t.length?`&roles=${t.join(",")}`:""}`)}),"oauthLogin"));l(this,"resendOtp",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`
6
+ mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}
7
+ `,variables:{data:e}})).resend_otp}catch(t){throw new Error(t)}}),"resendOtp"));l(this,"resetPassword",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}})).reset_password}catch(t){throw new Error(t)}}),"resetPassword"));l(this,"revokeToken",n(e=>f(this,null,function*(){if(!e.refresh_token&&!e.refresh_token.trim())throw new Error("Invalid refresh_token");return yield(yield z()(`${this.config.authorizerURL}/oauth/revoke`,{method:"POST",headers:O({},this.config.extraHeaders),body:JSON.stringify({refresh_token:e.refresh_token,client_id:this.config.clientID})})).json()}),"revokeToken"));l(this,"signup",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`
8
+ mutation signup($data: SignUpInput!) { signup(params: $data) { ${k}}}
9
+ `,variables:{data:e}})).signup}catch(t){throw new Error(t)}}),"signup"));l(this,"updateProfile",n((e,t)=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:t,variables:{data:e}})).update_profile}catch(s){throw new Error(s)}}),"updateProfile"));l(this,"validateJWTToken",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}})).validate_jwt_token}catch(t){throw new Error(t)}}),"validateJWTToken"));l(this,"verifyEmail",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`
10
+ mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${k}}}
11
+ `,variables:{data:e}})).verify_email}catch(t){throw new Error(t)}}),"verifyEmail"));l(this,"verifyOtp",n(e=>f(this,null,function*(){try{return(yield this.graphqlQuery({query:`
12
+ mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${k}}}
13
+ `,variables:{data:e}})).verify_otp}catch(t){throw new Error(t)}}),"verifyOtp"));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=M(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=M(e.redirectURL),this.config.extraHeaders=G(O({},e.extraHeaders||{}),{"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"}),this.config.clientID=e.clientID.trim()}};n($,"Authorizer");return Re(Le);})();
14
+ window.__TAURI__ = __AUTHORIZER_JS__
package/lib/index.d.ts CHANGED
@@ -1,29 +1,215 @@
1
- import * as Types from './types';
2
- export * from './types';
3
- export declare class Authorizer {
4
- config: Types.ConfigType;
1
+ interface ConfigType {
2
+ authorizerURL: string;
3
+ redirectURL: string;
4
+ clientID: string;
5
+ extraHeaders?: Record<string, string>;
6
+ }
7
+ interface User {
8
+ id: string;
9
+ email: string;
10
+ preferred_username: string;
11
+ email_verified: boolean;
12
+ signup_methods: string;
13
+ given_name?: string | null;
14
+ family_name?: string | null;
15
+ middle_name?: string | null;
16
+ nickname?: string | null;
17
+ picture?: string | null;
18
+ gender?: string | null;
19
+ birthdate?: string | null;
20
+ phone_number?: string | null;
21
+ phone_number_verified?: boolean | null;
22
+ roles?: string[];
23
+ created_at: number;
24
+ updated_at: number;
25
+ is_multi_factor_auth_enabled?: boolean;
26
+ }
27
+ interface AuthToken {
28
+ message?: string;
29
+ access_token: string;
30
+ expires_in: number;
31
+ id_token: string;
32
+ refresh_token?: string;
33
+ user?: User;
34
+ should_show_otp_screen?: boolean;
35
+ }
36
+ interface Response {
37
+ message: string;
38
+ }
39
+ type Headers = Record<string, string>;
40
+ interface LoginInput {
41
+ email: string;
42
+ password: string;
43
+ roles?: string[];
44
+ scope?: string[];
45
+ state?: string;
46
+ }
47
+ interface SignupInput {
48
+ email: string;
49
+ password: string;
50
+ confirm_password: string;
51
+ given_name?: string;
52
+ family_name?: string;
53
+ middle_name?: string;
54
+ nickname?: string;
55
+ picture?: string;
56
+ gender?: string;
57
+ birthdate?: string;
58
+ phone_number?: string;
59
+ roles?: string[];
60
+ scope?: string[];
61
+ redirect_uri?: string;
62
+ is_multi_factor_auth_enabled?: boolean;
63
+ state?: string;
64
+ }
65
+ interface MagicLinkLoginInput {
66
+ email: string;
67
+ roles?: string[];
68
+ scopes?: string[];
69
+ state?: string;
70
+ redirect_uri?: string;
71
+ }
72
+ interface VerifyEmailInput {
73
+ token: string;
74
+ state?: string;
75
+ }
76
+ interface VerifyOtpInput {
77
+ email: string;
78
+ otp: string;
79
+ state?: string;
80
+ }
81
+ interface ResendOtpInput {
82
+ email: string;
83
+ }
84
+ interface GraphqlQueryInput {
85
+ query: string;
86
+ variables?: Record<string, any>;
87
+ headers?: Headers;
88
+ }
89
+ interface MetaData {
90
+ version: string;
91
+ client_id: string;
92
+ is_google_login_enabled: boolean;
93
+ is_facebook_login_enabled: boolean;
94
+ is_github_login_enabled: boolean;
95
+ is_linkedin_login_enabled: boolean;
96
+ is_apple_login_enabled: boolean;
97
+ is_twitter_login_enabled: boolean;
98
+ is_microsoft_login_enabled: boolean;
99
+ is_email_verification_enabled: boolean;
100
+ is_basic_authentication_enabled: boolean;
101
+ is_magic_link_login_enabled: boolean;
102
+ is_sign_up_enabled: boolean;
103
+ is_strong_password_enabled: boolean;
104
+ }
105
+ interface UpdateProfileInput {
106
+ old_password?: string;
107
+ new_password?: string;
108
+ confirm_new_password?: string;
109
+ email?: string;
110
+ given_name?: string;
111
+ family_name?: string;
112
+ middle_name?: string;
113
+ nickname?: string;
114
+ gender?: string;
115
+ birthdate?: string;
116
+ phone_number?: string;
117
+ picture?: string;
118
+ is_multi_factor_auth_enabled?: boolean;
119
+ }
120
+ interface ForgotPasswordInput {
121
+ email: string;
122
+ state?: string;
123
+ redirect_uri?: string;
124
+ }
125
+ interface ResetPasswordInput {
126
+ token: string;
127
+ password: string;
128
+ confirm_password: string;
129
+ }
130
+ interface SessionQueryInput {
131
+ roles?: string[];
132
+ }
133
+ interface IsValidJWTQueryInput {
134
+ jwt: string;
135
+ roles?: string[];
136
+ }
137
+ interface ValidJWTResponse {
138
+ valid: string;
139
+ message: string;
140
+ }
141
+ declare enum OAuthProviders {
142
+ Apple = "apple",
143
+ Github = "github",
144
+ Google = "google",
145
+ Facebook = "facebook",
146
+ LinkedIn = "linkedin"
147
+ }
148
+ declare enum ResponseTypes {
149
+ Code = "code",
150
+ Token = "token"
151
+ }
152
+ interface AuthorizeInput {
153
+ response_type: ResponseTypes;
154
+ use_refresh_token?: boolean;
155
+ response_mode?: string;
156
+ }
157
+ interface AuthorizeResponse {
158
+ state: string;
159
+ code?: string;
160
+ error?: string;
161
+ error_description?: string;
162
+ }
163
+ interface RevokeTokenInput {
164
+ refresh_token: string;
165
+ }
166
+ interface GetTokenInput {
167
+ code?: string;
168
+ grant_type?: string;
169
+ refresh_token?: string;
170
+ }
171
+ interface GetTokenResponse {
172
+ access_token: string;
173
+ expires_in: number;
174
+ id_token: string;
175
+ refresh_token?: string;
176
+ }
177
+ interface ValidateJWTTokenInput {
178
+ token_type: "access_token" | "id_token" | "refresh_token";
179
+ token: string;
180
+ roles?: string[];
181
+ }
182
+ interface ValidateJWTTokenResponse {
183
+ is_valid: boolean;
184
+ claims: Record<string, any>;
185
+ }
186
+
187
+ declare class Authorizer {
188
+ config: ConfigType;
5
189
  codeVerifier: string;
6
- constructor(config: Types.ConfigType);
7
- authorize: (data: Types.AuthorizeInput) => Promise<Types.AuthorizeResponse | Types.GetTokenResponse | undefined>;
8
- browserLogin: () => Promise<Types.AuthToken | void>;
9
- forgotPassword: (data: Types.ForgotPasswordInput) => Promise<Types.Response | void>;
10
- getMetaData: () => Promise<Types.MetaData | void>;
11
- getProfile: (headers?: Types.Headers) => Promise<Types.User | void>;
12
- getSession: (headers?: Types.Headers, params?: Types.SessionQueryInput) => Promise<Types.AuthToken>;
13
- getToken: (data: Types.GetTokenInput) => Promise<Types.GetTokenResponse>;
14
- graphqlQuery: (data: Types.GraphqlQueryInput) => Promise<any>;
15
- login: (data: Types.LoginInput) => Promise<Types.AuthToken | void>;
16
- logout: (headers?: Types.Headers) => Promise<Types.Response | void>;
17
- magicLinkLogin: (data: Types.MagicLinkLoginInput) => Promise<Types.Response>;
190
+ constructor(config: ConfigType);
191
+ authorize: (data: AuthorizeInput) => Promise<GetTokenResponse | AuthorizeResponse | undefined>;
192
+ browserLogin: () => Promise<AuthToken | void>;
193
+ forgotPassword: (data: ForgotPasswordInput) => Promise<Response | void>;
194
+ getMetaData: () => Promise<MetaData | void>;
195
+ getProfile: (headers?: Headers) => Promise<User | void>;
196
+ getSession: (headers?: Headers, params?: SessionQueryInput) => Promise<AuthToken>;
197
+ getToken: (data: GetTokenInput) => Promise<GetTokenResponse>;
198
+ graphqlQuery: (data: GraphqlQueryInput) => Promise<any>;
199
+ login: (data: LoginInput) => Promise<AuthToken | void>;
200
+ logout: (headers?: Headers) => Promise<Response | void>;
201
+ magicLinkLogin: (data: MagicLinkLoginInput) => Promise<Response>;
18
202
  oauthLogin: (oauthProvider: string, roles?: string[], redirect_uri?: string, state?: string) => Promise<void>;
19
- resendOtp: (data: Types.ResendOtpInput) => Promise<Types.Response | void>;
20
- resetPassword: (data: Types.ResetPasswordInput) => Promise<Types.Response | void>;
203
+ resendOtp: (data: ResendOtpInput) => Promise<Response | void>;
204
+ resetPassword: (data: ResetPasswordInput) => Promise<Response | void>;
21
205
  revokeToken: (data: {
22
206
  refresh_token: string;
23
207
  }) => Promise<any>;
24
- signup: (data: Types.SignupInput) => Promise<Types.AuthToken | void>;
25
- updateProfile: (data: Types.UpdateProfileInput, headers?: Types.Headers) => Promise<Types.Response | void>;
26
- validateJWTToken: (params?: Types.ValidateJWTTokenInput) => Promise<Types.ValidateJWTTokenResponse>;
27
- verifyEmail: (data: Types.VerifyEmailInput) => Promise<Types.AuthToken | void>;
28
- verifyOtp: (data: Types.VerifyOtpInput) => Promise<Types.AuthToken | void>;
208
+ signup: (data: SignupInput) => Promise<AuthToken | void>;
209
+ updateProfile: (data: UpdateProfileInput, headers?: Headers) => Promise<Response | void>;
210
+ validateJWTToken: (params?: ValidateJWTTokenInput) => Promise<ValidateJWTTokenResponse>;
211
+ verifyEmail: (data: VerifyEmailInput) => Promise<AuthToken | void>;
212
+ verifyOtp: (data: VerifyOtpInput) => Promise<AuthToken | void>;
29
213
  }
214
+
215
+ export { AuthToken, AuthorizeInput, AuthorizeResponse, Authorizer, ConfigType, ForgotPasswordInput, GetTokenInput, GetTokenResponse, GraphqlQueryInput, Headers, IsValidJWTQueryInput, LoginInput, MagicLinkLoginInput, MetaData, OAuthProviders, ResendOtpInput, ResetPasswordInput, Response, ResponseTypes, RevokeTokenInput, SessionQueryInput, SignupInput, UpdateProfileInput, User, ValidJWTResponse, ValidateJWTTokenInput, ValidateJWTTokenResponse, VerifyEmailInput, VerifyOtpInput };
package/lib/index.js ADDED
@@ -0,0 +1,13 @@
1
+ var S=Object.create;var p=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var C=Object.getPrototypeOf,P=Object.prototype.hasOwnProperty;var n=(t,e)=>p(t,"name",{value:e,configurable:!0});var z=(t,e)=>{for(var r in e)p(t,r,{get:e[r],enumerable:!0})},R=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of x(e))!P.call(t,o)&&o!==r&&p(t,o,{get:()=>e[o],enumerable:!(s=O(e,o))||s.enumerable});return t};var A=(t,e,r)=>(r=t!=null?S(C(t)):{},R(e||!t||!t.__esModule?p(r,"default",{value:t,enumerable:!0}):r,t)),D=t=>R(p({},"__esModule",{value:!0}),t);var H={};z(H,{Authorizer:()=>w,OAuthProviders:()=>f,ResponseTypes:()=>l});module.exports=D(H);var k=A(require("cross-fetch"));var f;(function(t){t.Apple="apple",t.Github="github",t.Google="google",t.Facebook="facebook",t.LinkedIn="linkedin"})(f||(f={}));var l;(function(t){t.Code="code",t.Token="token"})(l||(l={}));var d=n(()=>typeof window<"u","hasWindow"),m=n(t=>{let e=t.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),U=n(()=>d()?window.crypto||window.msCrypto:null,"getCrypto"),j=n(()=>{let t=U();return t&&t.subtle||t.webkitSubtle},"getCryptoSubtle"),h=n(()=>{let t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",r=U();return r&&Array.from(r.getRandomValues(new Uint8Array(43))).forEach(o=>e+=t[o%t.length]),e},"createRandomString"),a=n(t=>d()?btoa(t):Buffer.from(t).toString("base64"),"encode");var T=n(t=>Object.keys(t).filter(e=>typeof t[e]<"u").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`).join("&"),"createQueryParams"),$=n(async t=>{let e=j().digest({name:"SHA-256"},new TextEncoder().encode(t));return window.msCrypto?new Promise((r,s)=>{e.oncomplete=o=>{r(o.target.result)},e.onerror=o=>{s(o.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):await e},"sha256"),F=n(t=>{let e={"+":"-","/":"_","=":""};return t.replace(/[+/=]/g,r=>e[r])},"urlEncodeB64");var L=n(t=>{let e=new Uint8Array(t);return F(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),v=n((t,e,r=60)=>new Promise((s,o)=>{let i=window.document.createElement("iframe");i.setAttribute("id","authorizer-iframe"),i.setAttribute("width","0"),i.setAttribute("height","0"),i.style.display="none";let c,b=n(()=>{window.document.body.contains(i)&&(window.document.body.removeChild(i),window.removeEventListener("message",c,!1))},"removeIframe"),q=setTimeout(()=>{b()},r*1e3);c=n(function(u){if(u.origin!==e||!u.data||!u.data.response)return;let E=u.source;E&&E.close(),u.data.response.error?o(u.data.response):s(u.data.response),clearTimeout(q),window.removeEventListener("message",c,!1),setTimeout(b,2*1e3)},"iframeEventHandler"),window.addEventListener("message",c,!1),window.document.body.appendChild(i),i.setAttribute("src",t)}),"executeIframe");var I="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 ",g=`message access_token expires_in refresh_token id_token should_show_otp_screen user { ${I} }`,y=n(()=>d()?window.fetch:k.default,"getFetcher"),w=class{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.authorizerURL&&(this.config.authorizerURL=m(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=m(e.redirectURL),this.config.extraHeaders={...e.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=e.clientID.trim()}authorize=async e=>{if(!d())throw new Error("this feature is only supported in browser");let r=["openid","profile","email"];e.use_refresh_token&&r.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:a(h()),nonce:a(h()),response_type:e.response_type,scope:r.join(" "),client_id:this.config.clientID};if(e.response_type===l.Code){this.codeVerifier=h();let i=await $(this.codeVerifier),c=L(i);s.code_challenge=c}let o=`${this.config.authorizerURL}/authorize?${T(s)}`;if(s.response_mode!=="web_message"){window.location.replace(o);return}try{let i=await v(o,this.config.authorizerURL,60);return e.response_type===l.Code?await this.getToken({code:i.code}):i}catch(i){throw i.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${a(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),i}};browserLogin=async()=>{try{return await this.getSession()}catch{if(!d())throw new Error("browserLogin is only supported for browsers");window.location.replace(`${this.config.authorizerURL}/app?state=${a(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`)}};forgotPassword=async e=>{e.state||(e.state=a(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{return(await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}})).forgot_password}catch(r){throw new Error(r)}};getMetaData=async()=>{try{return(await this.graphqlQuery({query:"query { meta { version 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_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"})).meta}catch(e){throw new Error(e)}};getProfile=async e=>{try{return(await this.graphqlQuery({query:`query { profile { ${I} } }`,headers:e})).profile}catch(r){throw new Error(r)}};getSession=async(e,r)=>{try{return(await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${g} } }`,headers:e,variables:{params:r}})).session}catch(s){throw new Error(s)}};getToken=async e=>{if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)throw new Error("Invalid refresh_token");if(e.grant_type==="authorization_code"&&!this.codeVerifier)throw new Error("Invalid code verifier");let r={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let o=await y()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(r),headers:{...this.config.extraHeaders},credentials:"include"}),i=await o.json();if(o.status>=400)throw new Error(i);return i}catch(s){throw new Error(s)}};graphqlQuery=async e=>{let o=await(await y()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:{...this.config.extraHeaders,...e.headers||{}},credentials:"include"})).json();if(o.errors&&o.errors.length)throw console.error(o.errors),new Error(o.errors[0].message);return o.data};login=async e=>{try{return(await this.graphqlQuery({query:`
2
+ mutation login($data: LoginInput!) { login(params: $data) { ${g}}}
3
+ `,variables:{data:e}})).login}catch(r){throw new Error(r)}};logout=async e=>{try{return(await this.graphqlQuery({query:" mutation { logout { message } } ",headers:e})).logout}catch(r){console.error(r)}};magicLinkLogin=async e=>{try{return e.state||(e.state=a(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL),(await this.graphqlQuery({query:`
4
+ mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }}
5
+ `,variables:{data:e}})).magic_link_login}catch(r){throw new Error(r)}};oauthLogin=async(e,r,s,o)=>{let i=o;if(i||(i=a(h())),!Object.values(f).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!d())throw new Error("oauthLogin is only supported for browsers");window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${s||this.config.redirectURL}&state=${i}${r&&r.length?`&roles=${r.join(",")}`:""}`)};resendOtp=async e=>{try{return(await this.graphqlQuery({query:`
6
+ mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}
7
+ `,variables:{data:e}})).resend_otp}catch(r){throw new Error(r)}};resetPassword=async e=>{try{return(await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}})).reset_password}catch(r){throw new Error(r)}};revokeToken=async e=>{if(!e.refresh_token&&!e.refresh_token.trim())throw new Error("Invalid refresh_token");return await(await y()(`${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()};signup=async e=>{try{return(await this.graphqlQuery({query:`
8
+ mutation signup($data: SignUpInput!) { signup(params: $data) { ${g}}}
9
+ `,variables:{data:e}})).signup}catch(r){throw new Error(r)}};updateProfile=async(e,r)=>{try{return(await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:r,variables:{data:e}})).update_profile}catch(s){throw new Error(s)}};validateJWTToken=async e=>{try{return(await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}})).validate_jwt_token}catch(r){throw new Error(r)}};verifyEmail=async e=>{try{return(await this.graphqlQuery({query:`
10
+ mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${g}}}
11
+ `,variables:{data:e}})).verify_email}catch(r){throw new Error(r)}};verifyOtp=async e=>{try{return(await this.graphqlQuery({query:`
12
+ mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${g}}}
13
+ `,variables:{data:e}})).verify_otp}catch(r){throw new Error(r)}}};n(w,"Authorizer");0&&(module.exports={Authorizer,OAuthProviders,ResponseTypes});
package/lib/index.mjs ADDED
@@ -0,0 +1,13 @@
1
+ var k=Object.defineProperty;var n=(t,e)=>k(t,"name",{value:e,configurable:!0});import x from"cross-fetch";var f;(function(t){t.Apple="apple",t.Github="github",t.Google="google",t.Facebook="facebook",t.LinkedIn="linkedin"})(f||(f={}));var l;(function(t){t.Code="code",t.Token="token"})(l||(l={}));var d=n(()=>typeof window<"u","hasWindow"),w=n(t=>{let e=t.trim();return e[e.length-1]==="/"&&(e=e.slice(0,-1)),e},"trimURL"),E=n(()=>d()?window.crypto||window.msCrypto:null,"getCrypto"),S=n(()=>{let t=E();return t&&t.subtle||t.webkitSubtle},"getCryptoSubtle"),h=n(()=>{let t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.",e="",r=E();return r&&Array.from(r.getRandomValues(new Uint8Array(43))).forEach(i=>e+=t[i%t.length]),e},"createRandomString"),a=n(t=>d()?btoa(t):Buffer.from(t).toString("base64"),"encode");var R=n(t=>Object.keys(t).filter(e=>typeof t[e]<"u").map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(t[e])}`).join("&"),"createQueryParams"),U=n(async t=>{let e=S().digest({name:"SHA-256"},new TextEncoder().encode(t));return window.msCrypto?new Promise((r,s)=>{e.oncomplete=i=>{r(i.target.result)},e.onerror=i=>{s(i.error)},e.onabort=()=>{s(new Error("The digest operation was aborted"))}}):await e},"sha256"),O=n(t=>{let e={"+":"-","/":"_","=":""};return t.replace(/[+/=]/g,r=>e[r])},"urlEncodeB64");var T=n(t=>{let e=new Uint8Array(t);return O(window.btoa(String.fromCharCode(...Array.from(e))))},"bufferToBase64UrlEncoded"),$=n((t,e,r=60)=>new Promise((s,i)=>{let o=window.document.createElement("iframe");o.setAttribute("id","authorizer-iframe"),o.setAttribute("width","0"),o.setAttribute("height","0"),o.style.display="none";let c,y=n(()=>{window.document.body.contains(o)&&(window.document.body.removeChild(o),window.removeEventListener("message",c,!1))},"removeIframe"),v=setTimeout(()=>{y()},r*1e3);c=n(function(u){if(u.origin!==e||!u.data||!u.data.response)return;let b=u.source;b&&b.close(),u.data.response.error?i(u.data.response):s(u.data.response),clearTimeout(v),window.removeEventListener("message",c,!1),setTimeout(y,2*1e3)},"iframeEventHandler"),window.addEventListener("message",c,!1),window.document.body.appendChild(o),o.setAttribute("src",t)}),"executeIframe");var L="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 ",p=`message access_token expires_in refresh_token id_token should_show_otp_screen user { ${L} }`,_=n(()=>d()?window.fetch:x,"getFetcher"),m=class{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.authorizerURL&&(this.config.authorizerURL=w(e.authorizerURL)),!e.redirectURL&&!e.redirectURL.trim())throw new Error("Invalid redirectURL");this.config.redirectURL=w(e.redirectURL),this.config.extraHeaders={...e.extraHeaders||{},"x-authorizer-url":this.config.authorizerURL,"Content-Type":"application/json"},this.config.clientID=e.clientID.trim()}authorize=async e=>{if(!d())throw new Error("this feature is only supported in browser");let r=["openid","profile","email"];e.use_refresh_token&&r.push("offline_access");let s={redirect_uri:this.config.redirectURL,response_mode:e.response_mode||"web_message",state:a(h()),nonce:a(h()),response_type:e.response_type,scope:r.join(" "),client_id:this.config.clientID};if(e.response_type===l.Code){this.codeVerifier=h();let o=await U(this.codeVerifier),c=T(o);s.code_challenge=c}let i=`${this.config.authorizerURL}/authorize?${R(s)}`;if(s.response_mode!=="web_message"){window.location.replace(i);return}try{let o=await $(i,this.config.authorizerURL,60);return e.response_type===l.Code?await this.getToken({code:o.code}):o}catch(o){throw o.error&&window.location.replace(`${this.config.authorizerURL}/app?state=${a(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`),o}};browserLogin=async()=>{try{return await this.getSession()}catch{if(!d())throw new Error("browserLogin is only supported for browsers");window.location.replace(`${this.config.authorizerURL}/app?state=${a(JSON.stringify(this.config))}&redirect_uri=${this.config.redirectURL}`)}};forgotPassword=async e=>{e.state||(e.state=a(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL);try{return(await this.graphqlQuery({query:"mutation forgotPassword($data: ForgotPasswordInput!) { forgot_password(params: $data) { message } }",variables:{data:e}})).forgot_password}catch(r){throw new Error(r)}};getMetaData=async()=>{try{return(await this.graphqlQuery({query:"query { meta { version 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_email_verification_enabled is_basic_authentication_enabled is_magic_link_login_enabled is_sign_up_enabled is_strong_password_enabled } }"})).meta}catch(e){throw new Error(e)}};getProfile=async e=>{try{return(await this.graphqlQuery({query:`query { profile { ${L} } }`,headers:e})).profile}catch(r){throw new Error(r)}};getSession=async(e,r)=>{try{return(await this.graphqlQuery({query:`query getSession($params: SessionQueryInput){session(params: $params) { ${p} } }`,headers:e,variables:{params:r}})).session}catch(s){throw new Error(s)}};getToken=async e=>{if(e.grant_type||(e.grant_type="authorization_code"),e.grant_type==="refresh_token"&&!e.refresh_token)throw new Error("Invalid refresh_token");if(e.grant_type==="authorization_code"&&!this.codeVerifier)throw new Error("Invalid code verifier");let r={client_id:this.config.clientID,code:e.code||"",code_verifier:this.codeVerifier||"",grant_type:e.grant_type||"",refresh_token:e.refresh_token||""};try{let i=await _()(`${this.config.authorizerURL}/oauth/token`,{method:"POST",body:JSON.stringify(r),headers:{...this.config.extraHeaders},credentials:"include"}),o=await i.json();if(i.status>=400)throw new Error(o);return o}catch(s){throw new Error(s)}};graphqlQuery=async e=>{let i=await(await _()(`${this.config.authorizerURL}/graphql`,{method:"POST",body:JSON.stringify({query:e.query,variables:e.variables||{}}),headers:{...this.config.extraHeaders,...e.headers||{}},credentials:"include"})).json();if(i.errors&&i.errors.length)throw console.error(i.errors),new Error(i.errors[0].message);return i.data};login=async e=>{try{return(await this.graphqlQuery({query:`
2
+ mutation login($data: LoginInput!) { login(params: $data) { ${p}}}
3
+ `,variables:{data:e}})).login}catch(r){throw new Error(r)}};logout=async e=>{try{return(await this.graphqlQuery({query:" mutation { logout { message } } ",headers:e})).logout}catch(r){console.error(r)}};magicLinkLogin=async e=>{try{return e.state||(e.state=a(h())),e.redirect_uri||(e.redirect_uri=this.config.redirectURL),(await this.graphqlQuery({query:`
4
+ mutation magicLinkLogin($data: MagicLinkLoginInput!) { magic_link_login(params: $data) { message }}
5
+ `,variables:{data:e}})).magic_link_login}catch(r){throw new Error(r)}};oauthLogin=async(e,r,s,i)=>{let o=i;if(o||(o=a(h())),!Object.values(f).includes(e))throw new Error(`only following oauth providers are supported: ${Object.values(e).toString()}`);if(!d())throw new Error("oauthLogin is only supported for browsers");window.location.replace(`${this.config.authorizerURL}/oauth_login/${e}?redirect_uri=${s||this.config.redirectURL}&state=${o}${r&&r.length?`&roles=${r.join(",")}`:""}`)};resendOtp=async e=>{try{return(await this.graphqlQuery({query:`
6
+ mutation resendOtp($data: ResendOTPRequest!) { resend_otp(params: $data) { message }}
7
+ `,variables:{data:e}})).resend_otp}catch(r){throw new Error(r)}};resetPassword=async e=>{try{return(await this.graphqlQuery({query:"mutation resetPassword($data: ResetPasswordInput!) { reset_password(params: $data) { message } }",variables:{data:e}})).reset_password}catch(r){throw new Error(r)}};revokeToken=async e=>{if(!e.refresh_token&&!e.refresh_token.trim())throw new Error("Invalid refresh_token");return await(await _()(`${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()};signup=async e=>{try{return(await this.graphqlQuery({query:`
8
+ mutation signup($data: SignUpInput!) { signup(params: $data) { ${p}}}
9
+ `,variables:{data:e}})).signup}catch(r){throw new Error(r)}};updateProfile=async(e,r)=>{try{return(await this.graphqlQuery({query:"mutation updateProfile($data: UpdateProfileInput!) { update_profile(params: $data) { message } }",headers:r,variables:{data:e}})).update_profile}catch(s){throw new Error(s)}};validateJWTToken=async e=>{try{return(await this.graphqlQuery({query:"query validateJWTToken($params: ValidateJWTTokenInput!){validate_jwt_token(params: $params) { is_valid claims } }",variables:{params:e}})).validate_jwt_token}catch(r){throw new Error(r)}};verifyEmail=async e=>{try{return(await this.graphqlQuery({query:`
10
+ mutation verifyEmail($data: VerifyEmailInput!) { verify_email(params: $data) { ${p}}}
11
+ `,variables:{data:e}})).verify_email}catch(r){throw new Error(r)}};verifyOtp=async e=>{try{return(await this.graphqlQuery({query:`
12
+ mutation verifyOtp($data: VerifyOTPRequest!) { verify_otp(params: $data) { ${p}}}
13
+ `,variables:{data:e}})).verify_otp}catch(r){throw new Error(r)}}};n(m,"Authorizer");export{m as Authorizer,f as OAuthProviders,l as ResponseTypes};
package/package.json CHANGED
@@ -1,18 +1,32 @@
1
1
  {
2
- "version": "1.2.1",
2
+ "version": "1.2.2-beta.2",
3
3
  "license": "MIT",
4
- "types": "lib/cjs/index.d.ts",
5
- "main": "lib/cjs/index.js",
6
- "module": "lib/esm/index.js",
4
+ "types": "lib/index.d.ts",
5
+ "main": "lib/index.js",
6
+ "module": "lib/index.mjs",
7
+ "unpkg": "lib/authorizer.min.js",
7
8
  "files": [
8
- "lib",
9
- "src"
9
+ "lib"
10
10
  ],
11
+ "exports": {
12
+ ".": {
13
+ "types": "./lib/index.d.ts",
14
+ "import": "./lib/index.mjs",
15
+ "require": "./lib/index.js"
16
+ }
17
+ },
11
18
  "engines": {
12
- "node": ">=10"
19
+ "node": ">=16"
13
20
  },
14
21
  "packageManager": "pnpm@7.28.0",
15
- "repository": "https://github.com/authorizerdev/authorizer-js",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/authorizerdev/authorizer-js.git"
25
+ },
26
+ "bugs": {
27
+ "url": "https://github.com/authorizerdev/authorizer-js/issues"
28
+ },
29
+ "funding": "https://github.com/sponsors/authorizerdev",
16
30
  "browser": {
17
31
  "path": "path-browserify"
18
32
  },
@@ -22,9 +36,10 @@
22
36
  "@antfu/eslint-config": "^0.35.3",
23
37
  "@rollup/plugin-node-resolve": "^13.0.4",
24
38
  "@rollup/plugin-typescript": "^8.2.5",
25
- "@types/node-fetch": "^2.5.12",
39
+ "@swc/core": "^1.3.37",
26
40
  "bumpp": "^9.0.0",
27
41
  "eslint": "^8.35.0",
42
+ "encoding": "^0.1.13",
28
43
  "husky": "^7.0.1",
29
44
  "jest": "^27.0.6",
30
45
  "rimraf": "^2.7.1",
@@ -33,16 +48,16 @@
33
48
  "rollup-plugin-serve": "^1.1.0",
34
49
  "rollup-plugin-terser": "^7.0.2",
35
50
  "tslib": "^2.3.0",
51
+ "tsup": "^6.6.3",
36
52
  "typescript": "^4.3.5"
37
53
  },
38
54
  "dependencies": {
39
55
  "cross-fetch": "^3.1.5"
40
56
  },
41
57
  "scripts": {
42
- "clean": "rm -rf lib",
43
58
  "start": "rollup -w --config rollup.test.config.js",
44
59
  "ts-types": "tsc --emitDeclarationOnly --outDir lib",
45
- "build": "npm run clean && rollup --config rollup.config.js --environment INCLUDE_DEPS,BUILD:production",
60
+ "build": "tsup",
46
61
  "test": "npm run build && jest --testTimeout=20000 --runInBand",
47
62
  "release": "pnpm build && bumpp --commit --push --tag && pnpm publish",
48
63
  "lint": "eslint --ext .ts,.tsx,.js,.jsx .",