@roudanio/awesome-auth 0.1.0 → 0.1.3

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.
@@ -1 +1 @@
1
- var AwesomeAuth=function(m){"use strict";function A(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var k={exports:{}};(function(e){var r=Object.prototype.hasOwnProperty,t="~";function a(){}Object.create&&(a.prototype=Object.create(null),new a().__proto__||(t=!1));function d(c,i,s){this.fn=c,this.context=i,this.once=s||!1}function v(c,i,s,o,p){if(typeof s!="function")throw new TypeError("The listener must be a function");var u=new d(s,o||c,p),l=t?t+i:i;return c._events[l]?c._events[l].fn?c._events[l]=[c._events[l],u]:c._events[l].push(u):(c._events[l]=u,c._eventsCount++),c}function I(c,i){--c._eventsCount===0?c._events=new a:delete c._events[i]}function h(){this._events=new a,this._eventsCount=0}h.prototype.eventNames=function(){var i=[],s,o;if(this._eventsCount===0)return i;for(o in s=this._events)r.call(s,o)&&i.push(t?o.slice(1):o);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(s)):i},h.prototype.listeners=function(i){var s=t?t+i:i,o=this._events[s];if(!o)return[];if(o.fn)return[o.fn];for(var p=0,u=o.length,l=new Array(u);p<u;p++)l[p]=o[p].fn;return l},h.prototype.listenerCount=function(i){var s=t?t+i:i,o=this._events[s];return o?o.fn?1:o.length:0},h.prototype.emit=function(i,s,o,p,u,l){var g=t?t+i:i;if(!this._events[g])return!1;var n=this._events[g],y=arguments.length,b,f;if(n.fn){switch(n.once&&this.removeListener(i,n.fn,void 0,!0),y){case 1:return n.fn.call(n.context),!0;case 2:return n.fn.call(n.context,s),!0;case 3:return n.fn.call(n.context,s,o),!0;case 4:return n.fn.call(n.context,s,o,p),!0;case 5:return n.fn.call(n.context,s,o,p,u),!0;case 6:return n.fn.call(n.context,s,o,p,u,l),!0}for(f=1,b=new Array(y-1);f<y;f++)b[f-1]=arguments[f];n.fn.apply(n.context,b)}else{var re=n.length,T;for(f=0;f<re;f++)switch(n[f].once&&this.removeListener(i,n[f].fn,void 0,!0),y){case 1:n[f].fn.call(n[f].context);break;case 2:n[f].fn.call(n[f].context,s);break;case 3:n[f].fn.call(n[f].context,s,o);break;case 4:n[f].fn.call(n[f].context,s,o,p);break;default:if(!b)for(T=1,b=new Array(y-1);T<y;T++)b[T-1]=arguments[T];n[f].fn.apply(n[f].context,b)}}return!0},h.prototype.on=function(i,s,o){return v(this,i,s,o,!1)},h.prototype.once=function(i,s,o){return v(this,i,s,o,!0)},h.prototype.removeListener=function(i,s,o,p){var u=t?t+i:i;if(!this._events[u])return this;if(!s)return I(this,u),this;var l=this._events[u];if(l.fn)l.fn===s&&(!p||l.once)&&(!o||l.context===o)&&I(this,u);else{for(var g=0,n=[],y=l.length;g<y;g++)(l[g].fn!==s||p&&!l[g].once||o&&l[g].context!==o)&&n.push(l[g]);n.length?this._events[u]=n.length===1?n[0]:n:I(this,u)}return this},h.prototype.removeAllListeners=function(i){var s;return i?(s=t?t+i:i,this._events[s]&&I(this,s)):(this._events=new a,this._eventsCount=0),this},h.prototype.off=h.prototype.removeListener,h.prototype.addListener=h.prototype.on,h.prefixed=t,h.EventEmitter=h,e.exports=h})(k);var P=k.exports;const G=A(P);class w extends Error{}w.prototype.name="InvalidTokenError";function L(e){return decodeURIComponent(atob(e).replace(/(.)/g,(r,t)=>{let a=t.charCodeAt(0).toString(16).toUpperCase();return a.length<2&&(a="0"+a),"%"+a}))}function N(e){let r=e.replace(/-/g,"+").replace(/_/g,"/");switch(r.length%4){case 0:break;case 2:r+="==";break;case 3:r+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return L(r)}catch{return atob(r)}}function D(e,r){if(typeof e!="string")throw new w("Invalid token specified: must be a string");r||(r={});const t=r.header===!0?0:1,a=e.split(".")[t];if(typeof a!="string")throw new w(`Invalid token specified: missing part #${t+1}`);let d;try{d=N(a)}catch(v){throw new w(`Invalid token specified: invalid base64 for part #${t+1} (${v.message})`)}try{return JSON.parse(d)}catch(v){throw new w(`Invalid token specified: invalid json for part #${t+1} (${v.message})`)}}var R=typeof global=="object"&&global&&global.Object===Object&&global,F=typeof self=="object"&&self&&self.Object===Object&&self,V=R||F||Function("return this")(),O=V.Symbol,C=Object.prototype,z=C.hasOwnProperty,J=C.toString,S=O?O.toStringTag:void 0;function U(e){var r=z.call(e,S),t=e[S];try{e[S]=void 0;var a=!0}catch{}var d=J.call(e);return a&&(r?e[S]=t:delete e[S]),d}var B=Object.prototype,K=B.toString;function M(e){return K.call(e)}var q="[object Null]",H="[object Undefined]",E=O?O.toStringTag:void 0;function Y(e){return e==null?e===void 0?H:q:E&&E in Object(e)?U(e):M(e)}var Q=Array.isArray;function W(e){return e!=null&&typeof e=="object"}var X="[object String]";function Z(e){return typeof e=="string"||!Q(e)&&W(e)&&Y(e)==X}var x=(e=>(e.INIT="init",e.VERIFYING="verifying",e.VERIFIED="verified",e.REFRESH="refresh",e.ERROR="error",e))(x||{});let _;class $ extends G{#e="";#t={};#s=0;#c;#o=!1;#n=!1;#i=!1;#a;#l;#r;constructor({googleId:r,prefix:t="aAuth",root:a="/api"}){if(super(),this.#c=r,this.#l=t,this.#r=a,this.#a=Date.now()/1e3>>0,this.setAccessToken(localStorage.getItem(this.localKey)||"",!1),this.#e){this.verifyToken().then(d=>{d||this.initGoogleIdentity()});return}this.initGoogleIdentity()}get accessToken(){return this.#e}get expiredIn(){return this.#s?0:this.#s-this.#a}get isVerifying(){return this.#n}get isVerified(){return this.#i}get localKey(){return`${this.#l}-token`}get root(){return this.#r}get user(){return this.#t}doSignIn(){this.initGoogleIdentity()}doSignOut(){this.#e="",google.accounts.id.revoke(this.#t.sub||""),this.#t={}}async store(r,t){t=Z(t)?t:JSON.stringify(t),await fetch(`${this.#r}/store`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`},body:JSON.stringify({key:r,value:t})})}async retrieve(r){const t=await fetch(`${this.#r}/retrieve`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`},body:JSON.stringify({key:r})}),{data:a}=await t.json();return a?.value}initGoogleIdentity(){if(!("google"in globalThis)){ee(),globalThis.onGoogleLibraryLoad=()=>this.initGoogleIdentity();return}this.#o||(this.emit("init",!0),this.#o=!0,google.accounts.id.initialize({client_id:this.#c,callback:r=>this.onGoogleIdentityCallback(r),auto_select:!0,ux_mode:"popup"}),google.accounts.id.prompt())}refreshCountDown(){this.#a=Date.now()/1e3>>0,this.expiredIn<=60&&(clearInterval(_),this.refreshToken())}async refreshToken(){this.emit("refresh",!0);const r=await fetch(`${this.#r}/refresh-token`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`}}),{data:t}=await r.json(),{token:a}=t;this.setAccessToken(a),this.emit("refresh",!1)}setAccessToken(r,t=!0){if(this.#e=r,t&&localStorage.setItem(this.localKey,r),!r){this.#t={},this.#s=0;return}try{this.#t=D(r)}catch{this.#t={}}this.#s=this.#t.exp||0,this.expiredIn>0&&(clearInterval(_),_=setInterval(()=>this.refreshCountDown(),1e3))}async verifyToken(){this.emit("verifying",!0),this.#n=!0;try{const r=await fetch(`${this.#r}/verify-auth`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`}}),{data:t}=await r.json();t&&(this.#t=t,this.#i=!0,this.emit("verified",!0))}catch(r){this.#i=!1,this.emit("error",r.message||String(r))}return this.emit("verifying",!1),this.#n=!1,this.#i}async onGoogleIdentityCallback(r){this.emit("init",!1),this.#o=!1,this.emit("verifying",!0),this.#n=!0;const t=await fetch(`${this.#r}/google-auth`,{method:"POST",headers:{"Content-type":"application/json"},body:JSON.stringify({credential:r.credential})}),{data:a}=await t.json();a||this.emit("error","Failed to validate user.");const{token:d}=a;this.setAccessToken(d),this.emit("verifying",!1),this.#n=!1,this.emit("verified",!0),this.#i=!0}}function ee(){const e="https://accounts.google.com/gsi/client";if(document.querySelector(`script[src="${e}"]`))return;const r=document.createElement("script");r.src=e,r.async=!0,document.head.appendChild(r)}let j;function te(e){return j=j||new $(e),j}return m.AwesomeAuth=$,m.AwesomeAuthEvent=x,m.getInstance=te,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"}),m}({});
1
+ var AwesomeAuth=(function(m){"use strict";function P(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _={exports:{}},E;function G(){return E||(E=1,(function(e){var r=Object.prototype.hasOwnProperty,t="~";function a(){}Object.create&&(a.prototype=Object.create(null),new a().__proto__||(t=!1));function d(c,i,s){this.fn=c,this.context=i,this.once=s||!1}function v(c,i,s,o,p){if(typeof s!="function")throw new TypeError("The listener must be a function");var u=new d(s,o||c,p),l=t?t+i:i;return c._events[l]?c._events[l].fn?c._events[l]=[c._events[l],u]:c._events[l].push(u):(c._events[l]=u,c._eventsCount++),c}function I(c,i){--c._eventsCount===0?c._events=new a:delete c._events[i]}function h(){this._events=new a,this._eventsCount=0}h.prototype.eventNames=function(){var i=[],s,o;if(this._eventsCount===0)return i;for(o in s=this._events)r.call(s,o)&&i.push(t?o.slice(1):o);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(s)):i},h.prototype.listeners=function(i){var s=t?t+i:i,o=this._events[s];if(!o)return[];if(o.fn)return[o.fn];for(var p=0,u=o.length,l=new Array(u);p<u;p++)l[p]=o[p].fn;return l},h.prototype.listenerCount=function(i){var s=t?t+i:i,o=this._events[s];return o?o.fn?1:o.length:0},h.prototype.emit=function(i,s,o,p,u,l){var g=t?t+i:i;if(!this._events[g])return!1;var n=this._events[g],y=arguments.length,b,f;if(n.fn){switch(n.once&&this.removeListener(i,n.fn,void 0,!0),y){case 1:return n.fn.call(n.context),!0;case 2:return n.fn.call(n.context,s),!0;case 3:return n.fn.call(n.context,s,o),!0;case 4:return n.fn.call(n.context,s,o,p),!0;case 5:return n.fn.call(n.context,s,o,p,u),!0;case 6:return n.fn.call(n.context,s,o,p,u,l),!0}for(f=1,b=new Array(y-1);f<y;f++)b[f-1]=arguments[f];n.fn.apply(n.context,b)}else{var ie=n.length,T;for(f=0;f<ie;f++)switch(n[f].once&&this.removeListener(i,n[f].fn,void 0,!0),y){case 1:n[f].fn.call(n[f].context);break;case 2:n[f].fn.call(n[f].context,s);break;case 3:n[f].fn.call(n[f].context,s,o);break;case 4:n[f].fn.call(n[f].context,s,o,p);break;default:if(!b)for(T=1,b=new Array(y-1);T<y;T++)b[T-1]=arguments[T];n[f].fn.apply(n[f].context,b)}}return!0},h.prototype.on=function(i,s,o){return v(this,i,s,o,!1)},h.prototype.once=function(i,s,o){return v(this,i,s,o,!0)},h.prototype.removeListener=function(i,s,o,p){var u=t?t+i:i;if(!this._events[u])return this;if(!s)return I(this,u),this;var l=this._events[u];if(l.fn)l.fn===s&&(!p||l.once)&&(!o||l.context===o)&&I(this,u);else{for(var g=0,n=[],y=l.length;g<y;g++)(l[g].fn!==s||p&&!l[g].once||o&&l[g].context!==o)&&n.push(l[g]);n.length?this._events[u]=n.length===1?n[0]:n:I(this,u)}return this},h.prototype.removeAllListeners=function(i){var s;return i?(s=t?t+i:i,this._events[s]&&I(this,s)):(this._events=new a,this._eventsCount=0),this},h.prototype.off=h.prototype.removeListener,h.prototype.addListener=h.prototype.on,h.prefixed=t,h.EventEmitter=h,e.exports=h})(_)),_.exports}var L=G();const N=P(L);class w extends Error{}w.prototype.name="InvalidTokenError";function R(e){return decodeURIComponent(atob(e).replace(/(.)/g,(r,t)=>{let a=t.charCodeAt(0).toString(16).toUpperCase();return a.length<2&&(a="0"+a),"%"+a}))}function D(e){let r=e.replace(/-/g,"+").replace(/_/g,"/");switch(r.length%4){case 0:break;case 2:r+="==";break;case 3:r+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return R(r)}catch{return atob(r)}}function F(e,r){if(typeof e!="string")throw new w("Invalid token specified: must be a string");r||(r={});const t=r.header===!0?0:1,a=e.split(".")[t];if(typeof a!="string")throw new w(`Invalid token specified: missing part #${t+1}`);let d;try{d=D(a)}catch(v){throw new w(`Invalid token specified: invalid base64 for part #${t+1} (${v.message})`)}try{return JSON.parse(d)}catch(v){throw new w(`Invalid token specified: invalid json for part #${t+1} (${v.message})`)}}var V=typeof global=="object"&&global&&global.Object===Object&&global,z=typeof self=="object"&&self&&self.Object===Object&&self,J=V||z||Function("return this")(),O=J.Symbol,x=Object.prototype,U=x.hasOwnProperty,B=x.toString,S=O?O.toStringTag:void 0;function q(e){var r=U.call(e,S),t=e[S];try{e[S]=void 0;var a=!0}catch{}var d=B.call(e);return a&&(r?e[S]=t:delete e[S]),d}var K=Object.prototype,M=K.toString;function H(e){return M.call(e)}var Y="[object Null]",Q="[object Undefined]",C=O?O.toStringTag:void 0;function W(e){return e==null?e===void 0?Q:Y:C&&C in Object(e)?q(e):H(e)}var X=Array.isArray;function Z(e){return e!=null&&typeof e=="object"}var ee="[object String]";function te(e){return typeof e=="string"||!X(e)&&Z(e)&&W(e)==ee}var $=(e=>(e.INIT="init",e.VERIFYING="verifying",e.VERIFIED="verified",e.REFRESH="refresh",e.ERROR="error",e))($||{});let j;class A extends N{#e="";#t={};#s=0;#c;#o=!1;#n=!1;#i=!1;#a;#l;#r;constructor({googleId:r,prefix:t="aAuth",root:a="/api"}){if(super(),this.#c=r,this.#l=t,this.#r=a,this.#a=Date.now()/1e3>>0,this.setAccessToken(localStorage.getItem(this.localKey)||"",!1),this.#e){this.verifyToken().then(d=>{d||this.initGoogleIdentity()});return}this.initGoogleIdentity()}get accessToken(){return this.#e}get expiredIn(){return this.#s?0:this.#s-this.#a}get isVerifying(){return this.#n}get isVerified(){return this.#i}get localKey(){return`${this.#l}-token`}get root(){return this.#r}get user(){return this.#t}doSignIn(){this.initGoogleIdentity()}doSignOut(){this.#e="",google.accounts.id.revoke(this.#t.sub||""),this.#t={}}async store(r,t){t=te(t)?t:JSON.stringify(t),await fetch(`${this.#r}/store`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`},body:JSON.stringify({key:r,value:t})})}async retrieve(r){const t=await fetch(`${this.#r}/retrieve`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`},body:JSON.stringify({key:r})}),{data:a}=await t.json();return a?.value}initGoogleIdentity(){if(!("google"in globalThis)||!("accounts"in globalThis.google)){re(),globalThis.onGoogleLibraryLoad=()=>this.initGoogleIdentity();return}this.#o||(this.emit("init",!0),this.#o=!0,google.accounts.id.initialize({client_id:this.#c,callback:r=>this.onGoogleIdentityCallback(r),auto_select:!0,ux_mode:"popup"}),google.accounts.id.prompt())}refreshCountDown(){this.#a=Date.now()/1e3>>0,this.expiredIn<=60&&(clearInterval(j),this.refreshToken())}async refreshToken(){this.emit("refresh",!0);const r=await fetch(`${this.#r}/refresh-token`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`}}),{data:t}=await r.json(),{token:a}=t;this.setAccessToken(a),this.emit("refresh",!1)}setAccessToken(r,t=!0){if(this.#e=r,t&&localStorage.setItem(this.localKey,r),!r){this.#t={},this.#s=0;return}try{this.#t=F(r)}catch{this.#t={}}this.#s=this.#t.exp||0,this.expiredIn>0&&(clearInterval(j),j=setInterval(()=>this.refreshCountDown(),1e3))}async verifyToken(){this.emit("verifying",!0),this.#n=!0;try{const r=await fetch(`${this.#r}/verify-auth`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`}}),{data:t}=await r.json();t&&(this.#t=t,this.#i=!0,this.emit("verified",!0))}catch(r){this.#i=!1,this.emit("error",r.message||String(r))}return this.emit("verifying",!1),this.#n=!1,this.#i}async onGoogleIdentityCallback(r){this.emit("init",!1),this.#o=!1,this.emit("verifying",!0),this.#n=!0;const t=await fetch(`${this.#r}/google-auth`,{method:"POST",headers:{"Content-type":"application/json"},body:JSON.stringify({credential:r.credential})}),{data:a}=await t.json();a||this.emit("error","Failed to validate user.");const{token:d}=a;this.setAccessToken(d),this.emit("verifying",!1),this.#n=!1,this.emit("verified",!0),this.#i=!0}}function re(){const e="https://accounts.google.com/gsi/client";if(document.querySelector(`script[src="${e}"]`))return;const r=document.createElement("script");r.src=e,r.async=!0,document.head.appendChild(r)}let k;function ne(e){return k=k||new A(e),k}return m.AwesomeAuth=A,m.AwesomeAuthEvent=$,m.getInstance=ne,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"}),m})({});
@@ -1,123 +1,125 @@
1
- function E(e) {
1
+ function $(e) {
2
2
  return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e;
3
3
  }
4
- var k = { exports: {} };
5
- (function(e) {
6
- var r = Object.prototype.hasOwnProperty, t = "~";
7
- function a() {
8
- }
9
- Object.create && (a.prototype = /* @__PURE__ */ Object.create(null), new a().__proto__ || (t = !1));
10
- function d(c, i, s) {
11
- this.fn = c, this.context = i, this.once = s || !1;
12
- }
13
- function v(c, i, s, o, p) {
14
- if (typeof s != "function")
15
- throw new TypeError("The listener must be a function");
16
- var u = new d(s, o || c, p), f = t ? t + i : i;
17
- return c._events[f] ? c._events[f].fn ? c._events[f] = [c._events[f], u] : c._events[f].push(u) : (c._events[f] = u, c._eventsCount++), c;
18
- }
19
- function T(c, i) {
20
- --c._eventsCount === 0 ? c._events = new a() : delete c._events[i];
21
- }
22
- function h() {
23
- this._events = new a(), this._eventsCount = 0;
24
- }
25
- h.prototype.eventNames = function() {
26
- var i = [], s, o;
27
- if (this._eventsCount === 0) return i;
28
- for (o in s = this._events)
29
- r.call(s, o) && i.push(t ? o.slice(1) : o);
30
- return Object.getOwnPropertySymbols ? i.concat(Object.getOwnPropertySymbols(s)) : i;
31
- }, h.prototype.listeners = function(i) {
32
- var s = t ? t + i : i, o = this._events[s];
33
- if (!o) return [];
34
- if (o.fn) return [o.fn];
35
- for (var p = 0, u = o.length, f = new Array(u); p < u; p++)
36
- f[p] = o[p].fn;
37
- return f;
38
- }, h.prototype.listenerCount = function(i) {
39
- var s = t ? t + i : i, o = this._events[s];
40
- return o ? o.fn ? 1 : o.length : 0;
41
- }, h.prototype.emit = function(i, s, o, p, u, f) {
42
- var g = t ? t + i : i;
43
- if (!this._events[g]) return !1;
44
- var n = this._events[g], y = arguments.length, b, l;
45
- if (n.fn) {
46
- switch (n.once && this.removeListener(i, n.fn, void 0, !0), y) {
47
- case 1:
48
- return n.fn.call(n.context), !0;
49
- case 2:
50
- return n.fn.call(n.context, s), !0;
51
- case 3:
52
- return n.fn.call(n.context, s, o), !0;
53
- case 4:
54
- return n.fn.call(n.context, s, o, p), !0;
55
- case 5:
56
- return n.fn.call(n.context, s, o, p, u), !0;
57
- case 6:
58
- return n.fn.call(n.context, s, o, p, u, f), !0;
59
- }
60
- for (l = 1, b = new Array(y - 1); l < y; l++)
61
- b[l - 1] = arguments[l];
62
- n.fn.apply(n.context, b);
63
- } else {
64
- var C = n.length, m;
65
- for (l = 0; l < C; l++)
66
- switch (n[l].once && this.removeListener(i, n[l].fn, void 0, !0), y) {
4
+ var _ = { exports: {} }, k;
5
+ function P() {
6
+ return k || (k = 1, (function(e) {
7
+ var r = Object.prototype.hasOwnProperty, t = "~";
8
+ function a() {
9
+ }
10
+ Object.create && (a.prototype = /* @__PURE__ */ Object.create(null), new a().__proto__ || (t = !1));
11
+ function d(c, i, s) {
12
+ this.fn = c, this.context = i, this.once = s || !1;
13
+ }
14
+ function v(c, i, s, o, p) {
15
+ if (typeof s != "function")
16
+ throw new TypeError("The listener must be a function");
17
+ var u = new d(s, o || c, p), l = t ? t + i : i;
18
+ return c._events[l] ? c._events[l].fn ? c._events[l] = [c._events[l], u] : c._events[l].push(u) : (c._events[l] = u, c._eventsCount++), c;
19
+ }
20
+ function S(c, i) {
21
+ --c._eventsCount === 0 ? c._events = new a() : delete c._events[i];
22
+ }
23
+ function h() {
24
+ this._events = new a(), this._eventsCount = 0;
25
+ }
26
+ h.prototype.eventNames = function() {
27
+ var i = [], s, o;
28
+ if (this._eventsCount === 0) return i;
29
+ for (o in s = this._events)
30
+ r.call(s, o) && i.push(t ? o.slice(1) : o);
31
+ return Object.getOwnPropertySymbols ? i.concat(Object.getOwnPropertySymbols(s)) : i;
32
+ }, h.prototype.listeners = function(i) {
33
+ var s = t ? t + i : i, o = this._events[s];
34
+ if (!o) return [];
35
+ if (o.fn) return [o.fn];
36
+ for (var p = 0, u = o.length, l = new Array(u); p < u; p++)
37
+ l[p] = o[p].fn;
38
+ return l;
39
+ }, h.prototype.listenerCount = function(i) {
40
+ var s = t ? t + i : i, o = this._events[s];
41
+ return o ? o.fn ? 1 : o.length : 0;
42
+ }, h.prototype.emit = function(i, s, o, p, u, l) {
43
+ var g = t ? t + i : i;
44
+ if (!this._events[g]) return !1;
45
+ var n = this._events[g], y = arguments.length, b, f;
46
+ if (n.fn) {
47
+ switch (n.once && this.removeListener(i, n.fn, void 0, !0), y) {
67
48
  case 1:
68
- n[l].fn.call(n[l].context);
69
- break;
49
+ return n.fn.call(n.context), !0;
70
50
  case 2:
71
- n[l].fn.call(n[l].context, s);
72
- break;
51
+ return n.fn.call(n.context, s), !0;
73
52
  case 3:
74
- n[l].fn.call(n[l].context, s, o);
75
- break;
53
+ return n.fn.call(n.context, s, o), !0;
76
54
  case 4:
77
- n[l].fn.call(n[l].context, s, o, p);
78
- break;
79
- default:
80
- if (!b) for (m = 1, b = new Array(y - 1); m < y; m++)
81
- b[m - 1] = arguments[m];
82
- n[l].fn.apply(n[l].context, b);
55
+ return n.fn.call(n.context, s, o, p), !0;
56
+ case 5:
57
+ return n.fn.call(n.context, s, o, p, u), !0;
58
+ case 6:
59
+ return n.fn.call(n.context, s, o, p, u, l), !0;
83
60
  }
84
- }
85
- return !0;
86
- }, h.prototype.on = function(i, s, o) {
87
- return v(this, i, s, o, !1);
88
- }, h.prototype.once = function(i, s, o) {
89
- return v(this, i, s, o, !0);
90
- }, h.prototype.removeListener = function(i, s, o, p) {
91
- var u = t ? t + i : i;
92
- if (!this._events[u]) return this;
93
- if (!s)
94
- return T(this, u), this;
95
- var f = this._events[u];
96
- if (f.fn)
97
- f.fn === s && (!p || f.once) && (!o || f.context === o) && T(this, u);
98
- else {
99
- for (var g = 0, n = [], y = f.length; g < y; g++)
100
- (f[g].fn !== s || p && !f[g].once || o && f[g].context !== o) && n.push(f[g]);
101
- n.length ? this._events[u] = n.length === 1 ? n[0] : n : T(this, u);
102
- }
103
- return this;
104
- }, h.prototype.removeAllListeners = function(i) {
105
- var s;
106
- return i ? (s = t ? t + i : i, this._events[s] && T(this, s)) : (this._events = new a(), this._eventsCount = 0), this;
107
- }, h.prototype.off = h.prototype.removeListener, h.prototype.addListener = h.prototype.on, h.prefixed = t, h.EventEmitter = h, e.exports = h;
108
- })(k);
109
- var $ = k.exports;
110
- const P = /* @__PURE__ */ E($);
111
- class S extends Error {
61
+ for (f = 1, b = new Array(y - 1); f < y; f++)
62
+ b[f - 1] = arguments[f];
63
+ n.fn.apply(n.context, b);
64
+ } else {
65
+ var C = n.length, m;
66
+ for (f = 0; f < C; f++)
67
+ switch (n[f].once && this.removeListener(i, n[f].fn, void 0, !0), y) {
68
+ case 1:
69
+ n[f].fn.call(n[f].context);
70
+ break;
71
+ case 2:
72
+ n[f].fn.call(n[f].context, s);
73
+ break;
74
+ case 3:
75
+ n[f].fn.call(n[f].context, s, o);
76
+ break;
77
+ case 4:
78
+ n[f].fn.call(n[f].context, s, o, p);
79
+ break;
80
+ default:
81
+ if (!b) for (m = 1, b = new Array(y - 1); m < y; m++)
82
+ b[m - 1] = arguments[m];
83
+ n[f].fn.apply(n[f].context, b);
84
+ }
85
+ }
86
+ return !0;
87
+ }, h.prototype.on = function(i, s, o) {
88
+ return v(this, i, s, o, !1);
89
+ }, h.prototype.once = function(i, s, o) {
90
+ return v(this, i, s, o, !0);
91
+ }, h.prototype.removeListener = function(i, s, o, p) {
92
+ var u = t ? t + i : i;
93
+ if (!this._events[u]) return this;
94
+ if (!s)
95
+ return S(this, u), this;
96
+ var l = this._events[u];
97
+ if (l.fn)
98
+ l.fn === s && (!p || l.once) && (!o || l.context === o) && S(this, u);
99
+ else {
100
+ for (var g = 0, n = [], y = l.length; g < y; g++)
101
+ (l[g].fn !== s || p && !l[g].once || o && l[g].context !== o) && n.push(l[g]);
102
+ n.length ? this._events[u] = n.length === 1 ? n[0] : n : S(this, u);
103
+ }
104
+ return this;
105
+ }, h.prototype.removeAllListeners = function(i) {
106
+ var s;
107
+ return i ? (s = t ? t + i : i, this._events[s] && S(this, s)) : (this._events = new a(), this._eventsCount = 0), this;
108
+ }, h.prototype.off = h.prototype.removeListener, h.prototype.addListener = h.prototype.on, h.prefixed = t, h.EventEmitter = h, e.exports = h;
109
+ })(_)), _.exports;
110
+ }
111
+ var A = P();
112
+ const G = /* @__PURE__ */ $(A);
113
+ class T extends Error {
112
114
  }
113
- S.prototype.name = "InvalidTokenError";
114
- function A(e) {
115
+ T.prototype.name = "InvalidTokenError";
116
+ function L(e) {
115
117
  return decodeURIComponent(atob(e).replace(/(.)/g, (r, t) => {
116
118
  let a = t.charCodeAt(0).toString(16).toUpperCase();
117
119
  return a.length < 2 && (a = "0" + a), "%" + a;
118
120
  }));
119
121
  }
120
- function G(e) {
122
+ function N(e) {
121
123
  let r = e.replace(/-/g, "+").replace(/_/g, "/");
122
124
  switch (r.length % 4) {
123
125
  case 0:
@@ -132,60 +134,60 @@ function G(e) {
132
134
  throw new Error("base64 string is not of the correct length");
133
135
  }
134
136
  try {
135
- return A(r);
137
+ return L(r);
136
138
  } catch {
137
139
  return atob(r);
138
140
  }
139
141
  }
140
- function L(e, r) {
142
+ function R(e, r) {
141
143
  if (typeof e != "string")
142
- throw new S("Invalid token specified: must be a string");
144
+ throw new T("Invalid token specified: must be a string");
143
145
  r || (r = {});
144
146
  const t = r.header === !0 ? 0 : 1, a = e.split(".")[t];
145
147
  if (typeof a != "string")
146
- throw new S(`Invalid token specified: missing part #${t + 1}`);
148
+ throw new T(`Invalid token specified: missing part #${t + 1}`);
147
149
  let d;
148
150
  try {
149
- d = G(a);
151
+ d = N(a);
150
152
  } catch (v) {
151
- throw new S(`Invalid token specified: invalid base64 for part #${t + 1} (${v.message})`);
153
+ throw new T(`Invalid token specified: invalid base64 for part #${t + 1} (${v.message})`);
152
154
  }
153
155
  try {
154
156
  return JSON.parse(d);
155
157
  } catch (v) {
156
- throw new S(`Invalid token specified: invalid json for part #${t + 1} (${v.message})`);
158
+ throw new T(`Invalid token specified: invalid json for part #${t + 1} (${v.message})`);
157
159
  }
158
160
  }
159
- var N = typeof global == "object" && global && global.Object === Object && global, D = typeof self == "object" && self && self.Object === Object && self, R = N || D || Function("return this")(), O = R.Symbol, x = Object.prototype, F = x.hasOwnProperty, V = x.toString, w = O ? O.toStringTag : void 0;
160
- function z(e) {
161
- var r = F.call(e, w), t = e[w];
161
+ var D = typeof global == "object" && global && global.Object === Object && global, F = typeof self == "object" && self && self.Object === Object && self, V = D || F || Function("return this")(), O = V.Symbol, E = Object.prototype, z = E.hasOwnProperty, J = E.toString, w = O ? O.toStringTag : void 0;
162
+ function U(e) {
163
+ var r = z.call(e, w), t = e[w];
162
164
  try {
163
165
  e[w] = void 0;
164
166
  var a = !0;
165
167
  } catch {
166
168
  }
167
- var d = V.call(e);
169
+ var d = J.call(e);
168
170
  return a && (r ? e[w] = t : delete e[w]), d;
169
171
  }
170
- var J = Object.prototype, U = J.toString;
171
- function B(e) {
172
- return U.call(e);
173
- }
174
- var K = "[object Null]", q = "[object Undefined]", j = O ? O.toStringTag : void 0;
175
- function H(e) {
176
- return e == null ? e === void 0 ? q : K : j && j in Object(e) ? z(e) : B(e);
172
+ var B = Object.prototype, q = B.toString;
173
+ function K(e) {
174
+ return q.call(e);
177
175
  }
178
- var M = Array.isArray;
176
+ var H = "[object Null]", M = "[object Undefined]", x = O ? O.toStringTag : void 0;
179
177
  function Y(e) {
180
- return e != null && typeof e == "object";
178
+ return e == null ? e === void 0 ? M : H : x && x in Object(e) ? U(e) : K(e);
181
179
  }
182
- var Q = "[object String]";
180
+ var Q = Array.isArray;
183
181
  function W(e) {
184
- return typeof e == "string" || !M(e) && Y(e) && H(e) == Q;
182
+ return e != null && typeof e == "object";
183
+ }
184
+ var X = "[object String]";
185
+ function Z(e) {
186
+ return typeof e == "string" || !Q(e) && W(e) && Y(e) == X;
185
187
  }
186
- var X = /* @__PURE__ */ ((e) => (e.INIT = "init", e.VERIFYING = "verifying", e.VERIFIED = "verified", e.REFRESH = "refresh", e.ERROR = "error", e))(X || {});
187
- let _;
188
- class Z extends P {
188
+ var ee = /* @__PURE__ */ ((e) => (e.INIT = "init", e.VERIFYING = "verifying", e.VERIFIED = "verified", e.REFRESH = "refresh", e.ERROR = "error", e))(ee || {});
189
+ let I;
190
+ class te extends G {
189
191
  #e = "";
190
192
  #t = {};
191
193
  #s = 0;
@@ -194,14 +196,14 @@ class Z extends P {
194
196
  #n = !1;
195
197
  #i = !1;
196
198
  #a;
197
- #f;
199
+ #l;
198
200
  #r;
199
201
  constructor({
200
202
  googleId: r,
201
203
  prefix: t = "aAuth",
202
204
  root: a = "/api"
203
205
  }) {
204
- if (super(), this.#c = r, this.#f = t, this.#r = a, this.#a = Date.now() / 1e3 >> 0, this.setAccessToken(localStorage.getItem(this.localKey) || "", !1), this.#e) {
206
+ if (super(), this.#c = r, this.#l = t, this.#r = a, this.#a = Date.now() / 1e3 >> 0, this.setAccessToken(localStorage.getItem(this.localKey) || "", !1), this.#e) {
205
207
  this.verifyToken().then((d) => {
206
208
  d || this.initGoogleIdentity();
207
209
  });
@@ -222,7 +224,7 @@ class Z extends P {
222
224
  return this.#i;
223
225
  }
224
226
  get localKey() {
225
- return `${this.#f}-token`;
227
+ return `${this.#l}-token`;
226
228
  }
227
229
  get root() {
228
230
  return this.#r;
@@ -237,7 +239,7 @@ class Z extends P {
237
239
  this.#e = "", google.accounts.id.revoke(this.#t.sub || ""), this.#t = {};
238
240
  }
239
241
  async store(r, t) {
240
- t = W(t) ? t : JSON.stringify(t), await fetch(`${this.#r}/store`, {
242
+ t = Z(t) ? t : JSON.stringify(t), await fetch(`${this.#r}/store`, {
241
243
  method: "POST",
242
244
  headers: {
243
245
  "Content-type": "application/json",
@@ -263,8 +265,8 @@ class Z extends P {
263
265
  return a?.value;
264
266
  }
265
267
  initGoogleIdentity() {
266
- if (!("google" in globalThis)) {
267
- ee(), globalThis.onGoogleLibraryLoad = () => this.initGoogleIdentity();
268
+ if (!("google" in globalThis) || !("accounts" in globalThis.google)) {
269
+ re(), globalThis.onGoogleLibraryLoad = () => this.initGoogleIdentity();
268
270
  return;
269
271
  }
270
272
  this.#o || (this.emit("init", !0), this.#o = !0, google.accounts.id.initialize({
@@ -275,7 +277,7 @@ class Z extends P {
275
277
  }), google.accounts.id.prompt());
276
278
  }
277
279
  refreshCountDown() {
278
- this.#a = Date.now() / 1e3 >> 0, this.expiredIn <= 60 && (clearInterval(_), this.refreshToken());
280
+ this.#a = Date.now() / 1e3 >> 0, this.expiredIn <= 60 && (clearInterval(I), this.refreshToken());
279
281
  }
280
282
  async refreshToken() {
281
283
  this.emit("refresh", !0);
@@ -294,11 +296,11 @@ class Z extends P {
294
296
  return;
295
297
  }
296
298
  try {
297
- this.#t = L(r);
299
+ this.#t = R(r);
298
300
  } catch {
299
301
  this.#t = {};
300
302
  }
301
- this.#s = this.#t.exp || 0, this.expiredIn > 0 && (clearInterval(_), _ = setInterval(() => this.refreshCountDown(), 1e3));
303
+ this.#s = this.#t.exp || 0, this.expiredIn > 0 && (clearInterval(I), I = setInterval(() => this.refreshCountDown(), 1e3));
302
304
  }
303
305
  async verifyToken() {
304
306
  this.emit("verifying", !0), this.#n = !0;
@@ -332,19 +334,19 @@ class Z extends P {
332
334
  this.setAccessToken(d), this.emit("verifying", !1), this.#n = !1, this.emit("verified", !0), this.#i = !0;
333
335
  }
334
336
  }
335
- function ee() {
337
+ function re() {
336
338
  const e = "https://accounts.google.com/gsi/client";
337
339
  if (document.querySelector(`script[src="${e}"]`))
338
340
  return;
339
341
  const r = document.createElement("script");
340
342
  r.src = e, r.async = !0, document.head.appendChild(r);
341
343
  }
342
- let I;
343
- function te(e) {
344
- return I = I || new Z(e), I;
344
+ let j;
345
+ function ne(e) {
346
+ return j = j || new te(e), j;
345
347
  }
346
348
  export {
347
- Z as AwesomeAuth,
348
- X as AwesomeAuthEvent,
349
- te as getInstance
349
+ te as AwesomeAuth,
350
+ ee as AwesomeAuthEvent,
351
+ ne as getInstance
350
352
  };
@@ -1 +1 @@
1
- (function(y,w){typeof exports=="object"&&typeof module<"u"?w(exports):typeof define=="function"&&define.amd?define(["exports"],w):(y=typeof globalThis<"u"?globalThis:y||self,w(y.AwesomeAuth={}))})(this,function(y){"use strict";function w(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var x={exports:{}};(function(e){var n=Object.prototype.hasOwnProperty,t="~";function a(){}Object.create&&(a.prototype=Object.create(null),new a().__proto__||(t=!1));function p(c,i,s){this.fn=c,this.context=i,this.once=s||!1}function b(c,i,s,o,d){if(typeof s!="function")throw new TypeError("The listener must be a function");var u=new p(s,o||c,d),f=t?t+i:i;return c._events[f]?c._events[f].fn?c._events[f]=[c._events[f],u]:c._events[f].push(u):(c._events[f]=u,c._eventsCount++),c}function I(c,i){--c._eventsCount===0?c._events=new a:delete c._events[i]}function h(){this._events=new a,this._eventsCount=0}h.prototype.eventNames=function(){var i=[],s,o;if(this._eventsCount===0)return i;for(o in s=this._events)n.call(s,o)&&i.push(t?o.slice(1):o);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(s)):i},h.prototype.listeners=function(i){var s=t?t+i:i,o=this._events[s];if(!o)return[];if(o.fn)return[o.fn];for(var d=0,u=o.length,f=new Array(u);d<u;d++)f[d]=o[d].fn;return f},h.prototype.listenerCount=function(i){var s=t?t+i:i,o=this._events[s];return o?o.fn?1:o.length:0},h.prototype.emit=function(i,s,o,d,u,f){var g=t?t+i:i;if(!this._events[g])return!1;var r=this._events[g],v=arguments.length,m,l;if(r.fn){switch(r.once&&this.removeListener(i,r.fn,void 0,!0),v){case 1:return r.fn.call(r.context),!0;case 2:return r.fn.call(r.context,s),!0;case 3:return r.fn.call(r.context,s,o),!0;case 4:return r.fn.call(r.context,s,o,d),!0;case 5:return r.fn.call(r.context,s,o,d,u),!0;case 6:return r.fn.call(r.context,s,o,d,u,f),!0}for(l=1,m=new Array(v-1);l<v;l++)m[l-1]=arguments[l];r.fn.apply(r.context,m)}else{var ne=r.length,O;for(l=0;l<ne;l++)switch(r[l].once&&this.removeListener(i,r[l].fn,void 0,!0),v){case 1:r[l].fn.call(r[l].context);break;case 2:r[l].fn.call(r[l].context,s);break;case 3:r[l].fn.call(r[l].context,s,o);break;case 4:r[l].fn.call(r[l].context,s,o,d);break;default:if(!m)for(O=1,m=new Array(v-1);O<v;O++)m[O-1]=arguments[O];r[l].fn.apply(r[l].context,m)}}return!0},h.prototype.on=function(i,s,o){return b(this,i,s,o,!1)},h.prototype.once=function(i,s,o){return b(this,i,s,o,!0)},h.prototype.removeListener=function(i,s,o,d){var u=t?t+i:i;if(!this._events[u])return this;if(!s)return I(this,u),this;var f=this._events[u];if(f.fn)f.fn===s&&(!d||f.once)&&(!o||f.context===o)&&I(this,u);else{for(var g=0,r=[],v=f.length;g<v;g++)(f[g].fn!==s||d&&!f[g].once||o&&f[g].context!==o)&&r.push(f[g]);r.length?this._events[u]=r.length===1?r[0]:r:I(this,u)}return this},h.prototype.removeAllListeners=function(i){var s;return i?(s=t?t+i:i,this._events[s]&&I(this,s)):(this._events=new a,this._eventsCount=0),this},h.prototype.off=h.prototype.removeListener,h.prototype.addListener=h.prototype.on,h.prefixed=t,h.EventEmitter=h,e.exports=h})(x);var P=x.exports;const G=w(P);class T extends Error{}T.prototype.name="InvalidTokenError";function L(e){return decodeURIComponent(atob(e).replace(/(.)/g,(n,t)=>{let a=t.charCodeAt(0).toString(16).toUpperCase();return a.length<2&&(a="0"+a),"%"+a}))}function N(e){let n=e.replace(/-/g,"+").replace(/_/g,"/");switch(n.length%4){case 0:break;case 2:n+="==";break;case 3:n+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return L(n)}catch{return atob(n)}}function D(e,n){if(typeof e!="string")throw new T("Invalid token specified: must be a string");n||(n={});const t=n.header===!0?0:1,a=e.split(".")[t];if(typeof a!="string")throw new T(`Invalid token specified: missing part #${t+1}`);let p;try{p=N(a)}catch(b){throw new T(`Invalid token specified: invalid base64 for part #${t+1} (${b.message})`)}try{return JSON.parse(p)}catch(b){throw new T(`Invalid token specified: invalid json for part #${t+1} (${b.message})`)}}var R=typeof global=="object"&&global&&global.Object===Object&&global,F=typeof self=="object"&&self&&self.Object===Object&&self,V=R||F||Function("return this")(),j=V.Symbol,C=Object.prototype,z=C.hasOwnProperty,J=C.toString,S=j?j.toStringTag:void 0;function U(e){var n=z.call(e,S),t=e[S];try{e[S]=void 0;var a=!0}catch{}var p=J.call(e);return a&&(n?e[S]=t:delete e[S]),p}var B=Object.prototype,K=B.toString;function M(e){return K.call(e)}var q="[object Null]",H="[object Undefined]",E=j?j.toStringTag:void 0;function Y(e){return e==null?e===void 0?H:q:E&&E in Object(e)?U(e):M(e)}var Q=Array.isArray;function W(e){return e!=null&&typeof e=="object"}var X="[object String]";function Z(e){return typeof e=="string"||!Q(e)&&W(e)&&Y(e)==X}var $=(e=>(e.INIT="init",e.VERIFYING="verifying",e.VERIFIED="verified",e.REFRESH="refresh",e.ERROR="error",e))($||{});let _;class A extends G{#e="";#t={};#s=0;#c;#o=!1;#r=!1;#i=!1;#a;#f;#n;constructor({googleId:n,prefix:t="aAuth",root:a="/api"}){if(super(),this.#c=n,this.#f=t,this.#n=a,this.#a=Date.now()/1e3>>0,this.setAccessToken(localStorage.getItem(this.localKey)||"",!1),this.#e){this.verifyToken().then(p=>{p||this.initGoogleIdentity()});return}this.initGoogleIdentity()}get accessToken(){return this.#e}get expiredIn(){return this.#s?0:this.#s-this.#a}get isVerifying(){return this.#r}get isVerified(){return this.#i}get localKey(){return`${this.#f}-token`}get root(){return this.#n}get user(){return this.#t}doSignIn(){this.initGoogleIdentity()}doSignOut(){this.#e="",google.accounts.id.revoke(this.#t.sub||""),this.#t={}}async store(n,t){t=Z(t)?t:JSON.stringify(t),await fetch(`${this.#n}/store`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`},body:JSON.stringify({key:n,value:t})})}async retrieve(n){const t=await fetch(`${this.#n}/retrieve`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`},body:JSON.stringify({key:n})}),{data:a}=await t.json();return a?.value}initGoogleIdentity(){if(!("google"in globalThis)){ee(),globalThis.onGoogleLibraryLoad=()=>this.initGoogleIdentity();return}this.#o||(this.emit("init",!0),this.#o=!0,google.accounts.id.initialize({client_id:this.#c,callback:n=>this.onGoogleIdentityCallback(n),auto_select:!0,ux_mode:"popup"}),google.accounts.id.prompt())}refreshCountDown(){this.#a=Date.now()/1e3>>0,this.expiredIn<=60&&(clearInterval(_),this.refreshToken())}async refreshToken(){this.emit("refresh",!0);const n=await fetch(`${this.#n}/refresh-token`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`}}),{data:t}=await n.json(),{token:a}=t;this.setAccessToken(a),this.emit("refresh",!1)}setAccessToken(n,t=!0){if(this.#e=n,t&&localStorage.setItem(this.localKey,n),!n){this.#t={},this.#s=0;return}try{this.#t=D(n)}catch{this.#t={}}this.#s=this.#t.exp||0,this.expiredIn>0&&(clearInterval(_),_=setInterval(()=>this.refreshCountDown(),1e3))}async verifyToken(){this.emit("verifying",!0),this.#r=!0;try{const n=await fetch(`${this.#n}/verify-auth`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`}}),{data:t}=await n.json();t&&(this.#t=t,this.#i=!0,this.emit("verified",!0))}catch(n){this.#i=!1,this.emit("error",n.message||String(n))}return this.emit("verifying",!1),this.#r=!1,this.#i}async onGoogleIdentityCallback(n){this.emit("init",!1),this.#o=!1,this.emit("verifying",!0),this.#r=!0;const t=await fetch(`${this.#n}/google-auth`,{method:"POST",headers:{"Content-type":"application/json"},body:JSON.stringify({credential:n.credential})}),{data:a}=await t.json();a||this.emit("error","Failed to validate user.");const{token:p}=a;this.setAccessToken(p),this.emit("verifying",!1),this.#r=!1,this.emit("verified",!0),this.#i=!0}}function ee(){const e="https://accounts.google.com/gsi/client";if(document.querySelector(`script[src="${e}"]`))return;const n=document.createElement("script");n.src=e,n.async=!0,document.head.appendChild(n)}let k;function te(e){return k=k||new A(e),k}y.AwesomeAuth=A,y.AwesomeAuthEvent=$,y.getInstance=te,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})});
1
+ (function(y,w){typeof exports=="object"&&typeof module<"u"?w(exports):typeof define=="function"&&define.amd?define(["exports"],w):(y=typeof globalThis<"u"?globalThis:y||self,w(y.AwesomeAuth={}))})(this,(function(y){"use strict";function w(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _={exports:{}},E;function G(){return E||(E=1,(function(e){var n=Object.prototype.hasOwnProperty,t="~";function a(){}Object.create&&(a.prototype=Object.create(null),new a().__proto__||(t=!1));function p(c,i,s){this.fn=c,this.context=i,this.once=s||!1}function b(c,i,s,o,d){if(typeof s!="function")throw new TypeError("The listener must be a function");var u=new p(s,o||c,d),f=t?t+i:i;return c._events[f]?c._events[f].fn?c._events[f]=[c._events[f],u]:c._events[f].push(u):(c._events[f]=u,c._eventsCount++),c}function I(c,i){--c._eventsCount===0?c._events=new a:delete c._events[i]}function h(){this._events=new a,this._eventsCount=0}h.prototype.eventNames=function(){var i=[],s,o;if(this._eventsCount===0)return i;for(o in s=this._events)n.call(s,o)&&i.push(t?o.slice(1):o);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(s)):i},h.prototype.listeners=function(i){var s=t?t+i:i,o=this._events[s];if(!o)return[];if(o.fn)return[o.fn];for(var d=0,u=o.length,f=new Array(u);d<u;d++)f[d]=o[d].fn;return f},h.prototype.listenerCount=function(i){var s=t?t+i:i,o=this._events[s];return o?o.fn?1:o.length:0},h.prototype.emit=function(i,s,o,d,u,f){var g=t?t+i:i;if(!this._events[g])return!1;var r=this._events[g],v=arguments.length,m,l;if(r.fn){switch(r.once&&this.removeListener(i,r.fn,void 0,!0),v){case 1:return r.fn.call(r.context),!0;case 2:return r.fn.call(r.context,s),!0;case 3:return r.fn.call(r.context,s,o),!0;case 4:return r.fn.call(r.context,s,o,d),!0;case 5:return r.fn.call(r.context,s,o,d,u),!0;case 6:return r.fn.call(r.context,s,o,d,u,f),!0}for(l=1,m=new Array(v-1);l<v;l++)m[l-1]=arguments[l];r.fn.apply(r.context,m)}else{var ie=r.length,O;for(l=0;l<ie;l++)switch(r[l].once&&this.removeListener(i,r[l].fn,void 0,!0),v){case 1:r[l].fn.call(r[l].context);break;case 2:r[l].fn.call(r[l].context,s);break;case 3:r[l].fn.call(r[l].context,s,o);break;case 4:r[l].fn.call(r[l].context,s,o,d);break;default:if(!m)for(O=1,m=new Array(v-1);O<v;O++)m[O-1]=arguments[O];r[l].fn.apply(r[l].context,m)}}return!0},h.prototype.on=function(i,s,o){return b(this,i,s,o,!1)},h.prototype.once=function(i,s,o){return b(this,i,s,o,!0)},h.prototype.removeListener=function(i,s,o,d){var u=t?t+i:i;if(!this._events[u])return this;if(!s)return I(this,u),this;var f=this._events[u];if(f.fn)f.fn===s&&(!d||f.once)&&(!o||f.context===o)&&I(this,u);else{for(var g=0,r=[],v=f.length;g<v;g++)(f[g].fn!==s||d&&!f[g].once||o&&f[g].context!==o)&&r.push(f[g]);r.length?this._events[u]=r.length===1?r[0]:r:I(this,u)}return this},h.prototype.removeAllListeners=function(i){var s;return i?(s=t?t+i:i,this._events[s]&&I(this,s)):(this._events=new a,this._eventsCount=0),this},h.prototype.off=h.prototype.removeListener,h.prototype.addListener=h.prototype.on,h.prefixed=t,h.EventEmitter=h,e.exports=h})(_)),_.exports}var L=G();const N=w(L);class T extends Error{}T.prototype.name="InvalidTokenError";function R(e){return decodeURIComponent(atob(e).replace(/(.)/g,(n,t)=>{let a=t.charCodeAt(0).toString(16).toUpperCase();return a.length<2&&(a="0"+a),"%"+a}))}function D(e){let n=e.replace(/-/g,"+").replace(/_/g,"/");switch(n.length%4){case 0:break;case 2:n+="==";break;case 3:n+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return R(n)}catch{return atob(n)}}function F(e,n){if(typeof e!="string")throw new T("Invalid token specified: must be a string");n||(n={});const t=n.header===!0?0:1,a=e.split(".")[t];if(typeof a!="string")throw new T(`Invalid token specified: missing part #${t+1}`);let p;try{p=D(a)}catch(b){throw new T(`Invalid token specified: invalid base64 for part #${t+1} (${b.message})`)}try{return JSON.parse(p)}catch(b){throw new T(`Invalid token specified: invalid json for part #${t+1} (${b.message})`)}}var V=typeof global=="object"&&global&&global.Object===Object&&global,z=typeof self=="object"&&self&&self.Object===Object&&self,J=V||z||Function("return this")(),j=J.Symbol,C=Object.prototype,U=C.hasOwnProperty,B=C.toString,S=j?j.toStringTag:void 0;function q(e){var n=U.call(e,S),t=e[S];try{e[S]=void 0;var a=!0}catch{}var p=B.call(e);return a&&(n?e[S]=t:delete e[S]),p}var K=Object.prototype,M=K.toString;function H(e){return M.call(e)}var Y="[object Null]",Q="[object Undefined]",$=j?j.toStringTag:void 0;function W(e){return e==null?e===void 0?Q:Y:$&&$ in Object(e)?q(e):H(e)}var X=Array.isArray;function Z(e){return e!=null&&typeof e=="object"}var ee="[object String]";function te(e){return typeof e=="string"||!X(e)&&Z(e)&&W(e)==ee}var A=(e=>(e.INIT="init",e.VERIFYING="verifying",e.VERIFIED="verified",e.REFRESH="refresh",e.ERROR="error",e))(A||{});let k;class P extends N{#e="";#t={};#s=0;#c;#o=!1;#r=!1;#i=!1;#a;#f;#n;constructor({googleId:n,prefix:t="aAuth",root:a="/api"}){if(super(),this.#c=n,this.#f=t,this.#n=a,this.#a=Date.now()/1e3>>0,this.setAccessToken(localStorage.getItem(this.localKey)||"",!1),this.#e){this.verifyToken().then(p=>{p||this.initGoogleIdentity()});return}this.initGoogleIdentity()}get accessToken(){return this.#e}get expiredIn(){return this.#s?0:this.#s-this.#a}get isVerifying(){return this.#r}get isVerified(){return this.#i}get localKey(){return`${this.#f}-token`}get root(){return this.#n}get user(){return this.#t}doSignIn(){this.initGoogleIdentity()}doSignOut(){this.#e="",google.accounts.id.revoke(this.#t.sub||""),this.#t={}}async store(n,t){t=te(t)?t:JSON.stringify(t),await fetch(`${this.#n}/store`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`},body:JSON.stringify({key:n,value:t})})}async retrieve(n){const t=await fetch(`${this.#n}/retrieve`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`},body:JSON.stringify({key:n})}),{data:a}=await t.json();return a?.value}initGoogleIdentity(){if(!("google"in globalThis)||!("accounts"in globalThis.google)){ne(),globalThis.onGoogleLibraryLoad=()=>this.initGoogleIdentity();return}this.#o||(this.emit("init",!0),this.#o=!0,google.accounts.id.initialize({client_id:this.#c,callback:n=>this.onGoogleIdentityCallback(n),auto_select:!0,ux_mode:"popup"}),google.accounts.id.prompt())}refreshCountDown(){this.#a=Date.now()/1e3>>0,this.expiredIn<=60&&(clearInterval(k),this.refreshToken())}async refreshToken(){this.emit("refresh",!0);const n=await fetch(`${this.#n}/refresh-token`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`}}),{data:t}=await n.json(),{token:a}=t;this.setAccessToken(a),this.emit("refresh",!1)}setAccessToken(n,t=!0){if(this.#e=n,t&&localStorage.setItem(this.localKey,n),!n){this.#t={},this.#s=0;return}try{this.#t=F(n)}catch{this.#t={}}this.#s=this.#t.exp||0,this.expiredIn>0&&(clearInterval(k),k=setInterval(()=>this.refreshCountDown(),1e3))}async verifyToken(){this.emit("verifying",!0),this.#r=!0;try{const n=await fetch(`${this.#n}/verify-auth`,{method:"POST",headers:{"Content-type":"application/json",Authorization:`Bearer ${this.#e}`}}),{data:t}=await n.json();t&&(this.#t=t,this.#i=!0,this.emit("verified",!0))}catch(n){this.#i=!1,this.emit("error",n.message||String(n))}return this.emit("verifying",!1),this.#r=!1,this.#i}async onGoogleIdentityCallback(n){this.emit("init",!1),this.#o=!1,this.emit("verifying",!0),this.#r=!0;const t=await fetch(`${this.#n}/google-auth`,{method:"POST",headers:{"Content-type":"application/json"},body:JSON.stringify({credential:n.credential})}),{data:a}=await t.json();a||this.emit("error","Failed to validate user.");const{token:p}=a;this.setAccessToken(p),this.emit("verifying",!1),this.#r=!1,this.emit("verified",!0),this.#i=!0}}function ne(){const e="https://accounts.google.com/gsi/client";if(document.querySelector(`script[src="${e}"]`))return;const n=document.createElement("script");n.src=e,n.async=!0,document.head.appendChild(n)}let x;function re(e){return x=x||new P(e),x}y.AwesomeAuth=P,y.AwesomeAuthEvent=A,y.getInstance=re,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@roudanio/awesome-auth",
3
- "version": "0.1.0",
3
+ "version": "0.1.3",
4
4
  "type": "module",
5
5
  "main": "dist/awesome-auth.umd.js",
6
6
  "module": "dist/awesome-auth.js",
@@ -8,30 +8,33 @@
8
8
  "types": "dist/auth.d.ts",
9
9
  "dependencies": {
10
10
  "eventemitter3": "^5.0.1",
11
- "google-auth-library": "^9.14.1",
12
- "jsonwebtoken": "^9.0.2",
11
+ "google-auth-library": "^10.5.0",
12
+ "jsonwebtoken": "^9.0.3",
13
13
  "jwt-decode": "^4.0.0",
14
- "lodash-es": "^4.17.21",
15
- "vue": "^3.5.10",
16
- "@awesome-comment/core": "0.1.0"
14
+ "lodash-es": "^4.17.22",
15
+ "vue": "^3.5.26",
16
+ "@awesome-comment/core": "0.1.1"
17
17
  },
18
18
  "devDependencies": {
19
19
  "@types/gapi": "^0.0.47",
20
20
  "@types/gapi.auth2": "^0.0.61",
21
- "@types/google.accounts": "^0.0.15",
22
- "@types/jsonwebtoken": "^9.0.7",
23
- "@vitejs/plugin-vue": "^5.1.4",
24
- "autoprefixer": "^10.4.20",
25
- "postcss": "^8.4.47",
26
- "tailwindcss": "^3.4.13",
27
- "typescript": "^5.5.3",
28
- "vite": "^5.4.8",
29
- "vite-plugin-dts": "^4.2.3",
30
- "vue-tsc": "^2.1.6"
21
+ "@types/google.accounts": "^0.0.18",
22
+ "@types/jsonwebtoken": "^9.0.10",
23
+ "@types/lodash-es": "^4.17.12",
24
+ "@vitejs/plugin-vue": "^6.0.3",
25
+ "autoprefixer": "^10.4.23",
26
+ "postcss": "^8.5.6",
27
+ "tailwindcss": "^3.4.19",
28
+ "typescript": "^5.9.3",
29
+ "vite": "^7.3.1",
30
+ "vite-plugin-dts": "^4.5.4",
31
+ "vitest": "^4.0.17",
32
+ "vue-tsc": "^3.2.2"
31
33
  },
32
34
  "scripts": {
33
35
  "dev": "vite",
34
36
  "build": "vue-tsc -b && vite build",
35
- "preview": "vite preview"
37
+ "test": "vitest",
38
+ "test:run": "vitest run"
36
39
  }
37
40
  }
@@ -0,0 +1,112 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { AwesomeAuth, AwesomeAuthEvent } from '../../src/auth';
3
+
4
+ type PromptCallback = (notification: google.accounts.id.PromptMomentNotification) => void;
5
+
6
+ type PromptState = 'not-displayed' | 'skipped' | 'dismissed' | 'displayed';
7
+
8
+ function createPromptNotification(state: PromptState): google.accounts.id.PromptMomentNotification {
9
+ return {
10
+ isDisplayMoment: () => state === 'displayed' || state === 'not-displayed',
11
+ isDisplayed: () => state === 'displayed',
12
+ isNotDisplayed: () => state === 'not-displayed',
13
+ getNotDisplayedReason: () => 'suppressed_by_user',
14
+ isSkippedMoment: () => state === 'skipped',
15
+ getSkippedReason: () => 'user_cancel',
16
+ isDismissedMoment: () => state === 'dismissed',
17
+ getDismissedReason: () => 'cancel_called',
18
+ getMomentType: () => {
19
+ if (state === 'skipped') return 'skipped';
20
+ if (state === 'dismissed') return 'dismissed';
21
+ return 'display';
22
+ },
23
+ } as unknown as google.accounts.id.PromptMomentNotification;
24
+ }
25
+
26
+ describe('AwesomeAuth One Tap', () => {
27
+ let promptCallbacks: PromptCallback[];
28
+ let initialize: ReturnType<typeof vi.fn>;
29
+ let prompt: ReturnType<typeof vi.fn>;
30
+
31
+ beforeEach(() => {
32
+ promptCallbacks = [];
33
+ initialize = vi.fn();
34
+ prompt = vi.fn((callback?: PromptCallback) => {
35
+ if (callback) {
36
+ promptCallbacks.push(callback);
37
+ }
38
+ });
39
+
40
+ const googleMock = {
41
+ accounts: {
42
+ id: {
43
+ initialize,
44
+ prompt,
45
+ },
46
+ },
47
+ };
48
+
49
+ (globalThis as typeof globalThis & { google: typeof google }).google = googleMock as unknown as typeof google;
50
+
51
+ const storage = new Map<string, string>();
52
+ const localStorageMock: Storage = {
53
+ get length() {
54
+ return storage.size;
55
+ },
56
+ clear() {
57
+ storage.clear();
58
+ },
59
+ getItem(key: string) {
60
+ return storage.get(key) ?? null;
61
+ },
62
+ key(index: number) {
63
+ return Array.from(storage.keys())[index] ?? null;
64
+ },
65
+ removeItem(key: string) {
66
+ storage.delete(key);
67
+ },
68
+ setItem(key: string, value: string) {
69
+ storage.set(key, String(value));
70
+ },
71
+ };
72
+ (globalThis as typeof globalThis & { localStorage: Storage }).localStorage = localStorageMock;
73
+ });
74
+
75
+ afterEach(() => {
76
+ delete (globalThis as typeof globalThis & { google?: typeof google }).google;
77
+ delete (globalThis as typeof globalThis & { localStorage?: Storage }).localStorage;
78
+ promptCallbacks = [];
79
+ vi.clearAllMocks();
80
+ });
81
+
82
+ it('在提示被关闭后重置初始化状态,并允许再次唤起', () => {
83
+ const events: boolean[] = [];
84
+ const auth = new AwesomeAuth({ googleId: 'test-client' });
85
+ auth.on(AwesomeAuthEvent.INIT, (value: boolean) => {
86
+ events.push(value);
87
+ });
88
+
89
+ expect(promptCallbacks).toHaveLength(1);
90
+ promptCallbacks[0](createPromptNotification('dismissed'));
91
+
92
+ expect(events).toEqual([false]);
93
+
94
+ auth.doSignIn();
95
+ expect(promptCallbacks).toHaveLength(2);
96
+ expect(events[1]).toBe(true);
97
+ expect(initialize).toHaveBeenCalledTimes(1);
98
+ });
99
+
100
+ it('在提示未显示时结束初始化状态', () => {
101
+ const events: boolean[] = [];
102
+ const auth = new AwesomeAuth({ googleId: 'test-client' });
103
+ auth.on(AwesomeAuthEvent.INIT, (value: boolean) => {
104
+ events.push(value);
105
+ });
106
+
107
+ expect(promptCallbacks).toHaveLength(1);
108
+ promptCallbacks[0](createPromptNotification('not-displayed'));
109
+
110
+ expect(events).toEqual([false]);
111
+ });
112
+ });
@@ -1 +1 @@
1
- {"root":["./src/auth.ts","./src/main.ts","./src/vite-env.d.ts","./src/app.vue"],"version":"5.6.2"}
1
+ {"root":["./src/auth.ts","./src/main.ts","./src/vite-env.d.ts","./src/app.vue"],"errors":true,"version":"5.9.3"}
@@ -1 +1 @@
1
- {"root":["./vite.config.ts"],"version":"5.6.2"}
1
+ {"root":["./vite.config.ts"],"version":"5.9.3"}
@@ -0,0 +1,9 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ environment: 'happy-dom',
6
+ include: ['tests/**/*.test.ts'],
7
+ globals: false,
8
+ },
9
+ });