@amaster.ai/auth-client 1.1.1 → 1.1.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/dist/auth.d.cts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/oauth.d.cts +1 -1
- package/dist/oauth.d.ts +1 -1
- package/dist/permissions.d.cts +1 -1
- package/dist/permissions.d.ts +1 -1
- package/dist/sessions.d.cts +1 -1
- package/dist/sessions.d.ts +1 -1
- package/dist/{types-Cz0vVJqO.d.cts → types-YfiSfMTJ.d.cts} +41 -1
- package/dist/{types-Cz0vVJqO.d.ts → types-YfiSfMTJ.d.ts} +41 -1
- package/dist/user.d.cts +1 -1
- package/dist/user.d.ts +1 -1
- package/package.json +2 -2
package/dist/auth.d.cts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* ============================================================================
|
|
15
15
|
*/
|
|
16
16
|
import { HttpClient, ClientResult } from '@amaster.ai/http-client';
|
|
17
|
-
import {
|
|
17
|
+
import { s as User, k as RegisterParams, e as LoginResponse, L as LoginParams, c as CodeLoginParams, S as SendCodeParams, r as SuccessResponse, b as CaptchaResponse, i as OAuthProvider, h as MiniProgramPhoneResponse, R as RefreshTokenResponse } from './types-YfiSfMTJ.cjs';
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* Authentication Module
|
package/dist/auth.d.ts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* ============================================================================
|
|
15
15
|
*/
|
|
16
16
|
import { HttpClient, ClientResult } from '@amaster.ai/http-client';
|
|
17
|
-
import {
|
|
17
|
+
import { s as User, k as RegisterParams, e as LoginResponse, L as LoginParams, c as CodeLoginParams, S as SendCodeParams, r as SuccessResponse, b as CaptchaResponse, i as OAuthProvider, h as MiniProgramPhoneResponse, R as RefreshTokenResponse } from './types-YfiSfMTJ.js';
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* Authentication Module
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var httpClient=require('@amaster.ai/http-client');var S=class{constructor(){this.events={};}on(e,n){this.events[e]||(this.events[e]=[]),this.events[e].push(n);}off(e,n){this.events[e]&&(this.events[e]=this.events[e].filter(r=>r!==n));}emit(e,...n){this.events[e]&&this.events[e].forEach(r=>{try{r(...n);}catch(o){console.error(`[AuthClient] Error in event handler for "${e}":`,o);}});}removeAllListeners(){this.events={};}};var d={ACCESS_TOKEN:"amaster_access_token",REFRESH_TOKEN:"amaster_refresh_token",USER:"amaster_user"};function z(){return typeof wx<"u"&&wx.getStorageSync?"wechat-miniprogram":typeof tt<"u"&&tt.getStorageSync?"douyin-miniprogram":typeof window<"u"&&typeof window.localStorage<"u"?"browser":"node"}function P(){switch(z()){case "wechat-miniprogram":return T(wx,"WeChat");case "douyin-miniprogram":return T(tt,"Douyin");case "browser":return K();case "node":return j()}}function K(){let t=window.localStorage;return {getItem(e){try{return t.getItem(e)}catch(n){return console.error("[AuthClient] Failed to get item from localStorage:",n),null}},setItem(e,n){try{t.setItem(e,n);}catch(r){console.error("[AuthClient] Failed to set item in localStorage:",r);}},removeItem(e){try{t.removeItem(e);}catch(n){console.error("[AuthClient] Failed to remove item from localStorage:",n);}},clear(){try{t.removeItem(d.ACCESS_TOKEN),t.removeItem(d.REFRESH_TOKEN),t.removeItem(d.USER);}catch(e){console.error("[AuthClient] Failed to clear localStorage:",e);}}}}function T(t,e){return {getItem(n){try{return t.getStorageSync(n)||null}catch(r){return console.error(`[AuthClient] Failed to get item from ${e} storage:`,r),null}},setItem(n,r){try{t.setStorageSync(n,r);}catch(o){console.error(`[AuthClient] Failed to set item in ${e} storage:`,o);}},removeItem(n){try{t.removeStorageSync(n);}catch(r){console.error(`[AuthClient] Failed to remove item from ${e} storage:`,r);}},clear(){try{t.removeStorageSync(d.ACCESS_TOKEN),t.removeStorageSync(d.REFRESH_TOKEN),t.removeStorageSync(d.USER);}catch(n){console.error(`[AuthClient] Failed to clear ${e} storage:`,n);}}}}function j(){let t=new Map;return {getItem(e){return t.get(e)??null},setItem(e,n){t.set(e,n);},removeItem(e){t.delete(e);},clear(){t.clear();}}}function D(t){try{let e=t.split(".");if(e.length!==3)return null;let r=(e[1]||"").replace(/-/g,"+").replace(/_/g,"/");if(typeof atob<"u"){let o=decodeURIComponent(atob(r).split("").map(l=>"%"+("00"+l.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(o)}if(typeof Buffer<"u"){let o=Buffer.from(r,"base64").toString("utf-8");return JSON.parse(o)}return null}catch(e){return console.error("[AuthClient] Failed to parse JWT token:",e),null}}var v=class{constructor(){this.refreshTimer=null;this.isRefreshing=false;this.refreshCallback=null;}setRefreshCallback(e){this.refreshCallback=e;}scheduleRefresh(e){this.clearSchedule(),!(e<=0)&&(this.refreshTimer=setTimeout(()=>{this.refresh();},e));}scheduleRefreshFromToken(e,n=300){let r=D(e);if(!r||!r.exp){console.warn("[AuthClient] Cannot schedule refresh: invalid token or missing exp claim");return}let o=r.exp*1e3,l=Date.now(),a=o-l-n*1e3;a<=0?(console.warn("[AuthClient] Token already expired or expiring soon, refreshing immediately"),this.refresh()):this.scheduleRefresh(a);}async refresh(){if(!this.isRefreshing){if(!this.refreshCallback){console.error("[AuthClient] No refresh callback set");return}this.isRefreshing=true;try{await this.refreshCallback();}catch(e){console.error("[AuthClient] Token refresh failed:",e);}finally{this.isRefreshing=false;}}}clearSchedule(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}isCurrentlyRefreshing(){return this.isRefreshing}destroy(){this.clearSchedule(),this.refreshCallback=null,this.isRefreshing=false;}};function E(t){return t&&typeof t=="object"&&("statusCode"in t||"status"in t)&&"data"in t?t.data:t}var k={transformResponse:E,logErrors:true};function J(t){if(t.email)return "email";if(t.username)return "username";if(t.phone)return "phone"}function W(t){if(t.email)return "email";if(t.phone)return "phone"}function G(t){let e=new URLSearchParams(t);return e.get("access_token")||e.get("accessToken")}function Y(t){return new URLSearchParams(t).get("user")}function Q(){if(typeof window>"u")return null;try{let t=new URLSearchParams(window.location.search).get("redirect");if(!t)return null;let e=new URL(t,window.location.origin);return e.origin!==window.location.origin?(console.warn("[AuthClient] Ignored cross-origin redirect target:",t),null):`${e.pathname}${e.search}${e.hash}`}catch(t){return console.warn("[AuthClient] Failed to resolve redirect target:",t),null}}var V={replace(t){window.location.replace(t);}};function R(t,e){return e.handled?{...t,redirectHandled:true,redirectTarget:e.target}:t}function A(t){if(!t||typeof window>"u"||window.opener)return {handled:false};let e=Q();return e?(V.replace(e),{handled:true,target:e}):{handled:false}}function O(t){let{http:e,onLoginSuccess:n,onLogout:r,autoRedirectAfterLogin:o,storage:l,clearAuth:m}=t;return {async register(a){let s=await e.request({url:"/api/auth/register",method:"post",headers:{"Content-Type":"application/json"},data:a});if(s.data?.user&&s.data?.accessToken){n(s.data.user,s.data.accessToken);let h=A(o);s.data=R(s.data,h);}return s},async login(a){let s=a.loginType||J(a);if(!s)return {data:null,error:{message:"Unable to determine login type. Please provide email, username, or phone.",status:400},status:400};let h={...a,loginType:s},u=await e.request({url:"/api/auth/login",method:"post",headers:{"Content-Type":"application/json"},data:h});if(u.data?.user&&u.data?.accessToken){n(u.data.user,u.data.accessToken);let c=A(o);u.data=R(u.data,c);}return u},async loginWithCode(a){let s=a.loginType||W(a);if(!s)return {data:null,error:{message:"Unable to determine login type. Please provide email or phone.",status:400},status:400};let h={...a,loginType:s},u=await e.request({url:"/api/auth/login-with-code",method:"post",headers:{"Content-Type":"application/json"},data:h});if(u.data?.user&&u.data?.accessToken){n(u.data.user,u.data.accessToken);let c=A(o);u.data=R(u.data,c);}return u},async sendCode(a){return e.request({url:"/api/auth/send-code",method:"post",headers:{"Content-Type":"application/json"},data:a})},async getCaptcha(){return e.request({url:"/api/auth/captcha",method:"get"})},loginWithOAuth(a,s){if(typeof window>"u"){console.error("[AuthClient] OAuth login is only available in browser environment");return}let h=s?`/api/auth/oauth/${a}?redirect_url=${encodeURIComponent(s)}`:`/api/auth/oauth/${a}`;window.location.href=h;},async handleOAuthCallback(){if(typeof window>"u")return {data:null,error:{message:"OAuth callback is only available in browser environment",status:400},status:400};try{let a=window.location.hash.substring(1),s=G(a),h=Y(a);if(!s)return {data:null,error:{message:"OAuth callback failed: missing access token",status:400},status:400};let u;if(h)u=JSON.parse(decodeURIComponent(h));else {l.setItem(d.ACCESS_TOKEN,s);let p=await e.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${s}`}});if(!p.data)return {data:null,error:{message:"OAuth callback failed: unable to fetch user info",status:p.status||500},status:p.status||500};u=p.data;}if(n(u,s),window.history&&window.history.replaceState){let p=window.location.pathname+window.location.search;window.history.replaceState(null,"",p);}else window.location.hash="";let c=A(o);return {data:R({user:u,accessToken:s},c),error:null,status:200}}catch(a){return {data:null,error:{message:`OAuth callback failed: ${a instanceof Error?a.message:String(a)}`,status:400},status:400}}},async loginWithMiniProgram(a){let s=await e.request({url:"/api/auth/miniprogram/login",method:"post",headers:{"Content-Type":"application/json"},data:{code:a}});if(s.data?.user&&s.data?.accessToken){n(s.data.user,s.data.accessToken);let h=A(o);s.data=R(s.data,h);}return s},async getMiniProgramPhoneNumber(a){let s=l.getItem("amaster_access_token");return s?e.request({url:"/api/auth/miniprogram/phone",method:"post",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},data:{code:a}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async logout(){let a=l.getItem("amaster_access_token"),s=await e.request({url:"/api/auth/logout",method:"post",headers:a?{Authorization:`Bearer ${a}`}:void 0});return m(),r(),s},async refreshToken(){let a=await e.request({url:"/api/auth/refresh",method:"post"});return a.data?.accessToken&&l.setItem("amaster_access_token",a.data.accessToken),a}}}function b(t){let{getCurrentUser:e}=t;return {hasRole(n){let r=e();return !r||!r.roles?false:r.roles.includes(n)},hasPermission(n,r){let o=e();if(!o||!o.permissions)return false;let l=`${n}.${r}`;return o.permissions.includes(l)},hasAnyPermission(n){return n.some(({resource:r,action:o})=>this.hasPermission(r,o))},hasAllPermissions(n){return n.every(({resource:r,action:o})=>this.hasPermission(r,o))}}}function M(t){let{http:e,storage:n,onUserUpdate:r}=t;return {async getMe(){let o=n.getItem("amaster_access_token");if(!o)return {data:null,error:{message:"Not authenticated",status:401},status:401};let l=await e.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${o}`}});return l.data&&r(l.data),l},async updateMe(o){let l=n.getItem("amaster_access_token");if(!l)return {data:null,error:{message:"Not authenticated",status:401},status:401};let m=await e.request({url:"/api/auth/me",method:"put",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},data:o});return m.data&&r(m.data),m},async changePassword(o){let l=n.getItem("amaster_access_token");return l?e.request({url:"/api/auth/change-password",method:"post",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},data:o}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function U(t){let{http:e,storage:n}=t;return {async getOAuthBindings(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/oauth-bindings",method:"get",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},bindOAuth(r){if(typeof window>"u"){console.error("[AuthClient] OAuth binding is only available in browser environment");return}window.location.href=`/api/auth/oauth/${r}/bind`;},async unbindOAuth(r){let o=n.getItem("amaster_access_token");return o?e.request({url:`/api/auth/oauth/${r}/unbind`,method:"delete",headers:{Authorization:`Bearer ${o}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function I(t){let{http:e,storage:n}=t;return {async getSession(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/sessions/current",method:"get",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async getSessions(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/sessions",method:"get",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeSession(r){let o=n.getItem("amaster_access_token");return o?r?e.request({url:`/api/auth/sessions/${r}`,method:"delete",headers:{Authorization:`Bearer ${o}`}}):{data:null,error:{message:"Session ID is required",status:400},status:400}:{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeAllSessions(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/sessions",method:"delete",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function Z(t={},e){let {baseURL:n,headers:r,onTokenExpired:o,onUnauthorized:l,autoHandleOAuthCallback:m=true,autoRedirectAfterLogin:a=true}=t,s=e||httpClient.createHttpClient({...k,baseURL:n,headers:r}),u=300,c=P(),p=new S,C=new v,y=null;try{let i=c.getItem(d.USER);i&&(y=JSON.parse(i));}catch(i){console.error("[AuthClient] Failed to load user from storage:",i);}let f;C.setRefreshCallback(async()=>{let i=await f.refreshToken();i.data?(await f.getMe(),p.emit("tokenRefreshed",i.data.accessToken)):(p.emit("tokenExpired"),o?.());});function L(i,g){c.setItem(d.ACCESS_TOKEN,g),c.setItem(d.USER,JSON.stringify(i)),y=i,C.scheduleRefreshFromToken(g,u),p.emit("login",i);}function _(i){y=i,c.setItem(d.USER,JSON.stringify(i));}function x(){p.emit("logout");}function w(){c.clear(),y=null,C.clearSchedule();}function H(){return y}let N=O({http:s,onLoginSuccess:L,onLogout:x,autoRedirectAfterLogin:a,storage:c,clearAuth:w}),$=b({getCurrentUser:H}),q=M({http:s,storage:c,onUserUpdate:_}),B=U({http:s,storage:c}),F=I({http:s,storage:c});if(f={...N,...$,...q,...B,...F,on(i,g){p.on(i,g);},off(i,g){p.off(i,g);},isAuthenticated(){return !!c.getItem(d.ACCESS_TOKEN)},getAccessToken(){return c.getItem(d.ACCESS_TOKEN)},setAccessToken(i){c.setItem(d.ACCESS_TOKEN,i),C.scheduleRefreshFromToken(i,u);},clearAuth:w},f.on("unauthorized",()=>{l?.();}),f.isAuthenticated()&&f.getMe().catch(i=>{console.warn("[AuthClient] Failed to sync user info on init:",i);}),m&&typeof window<"u"){let i=window.location.hash;i&&(i.includes("access_token")||i.includes("accessToken"))&&f.handleOAuthCallback().then(g=>{g.error&&console.error("[AuthClient] Auto OAuth callback failed:",g.error);}).catch(g=>{console.error("[AuthClient] Auto OAuth callback error:",g);});}return f}exports.createAuthClient=Z;exports.defaultHttpClientOptions=k;exports.transformAmasterResponse=E;//# sourceMappingURL=index.cjs.map
|
|
1
|
+
'use strict';var httpClient=require('@amaster.ai/http-client');var S=class{constructor(){this.events={};}on(e,n){this.events[e]||(this.events[e]=[]),this.events[e].push(n);}off(e,n){this.events[e]&&(this.events[e]=this.events[e].filter(r=>r!==n));}emit(e,...n){this.events[e]&&this.events[e].forEach(r=>{try{r(...n);}catch(o){console.error(`[AuthClient] Error in event handler for "${e}":`,o);}});}removeAllListeners(){this.events={};}};var d={ACCESS_TOKEN:"amaster_access_token",REFRESH_TOKEN:"amaster_refresh_token",USER:"amaster_user"};function z(){return typeof wx<"u"&&wx.getStorageSync?"wechat-miniprogram":typeof tt<"u"&&tt.getStorageSync?"douyin-miniprogram":typeof window<"u"&&typeof window.localStorage<"u"?"browser":"node"}function P(){switch(z()){case "wechat-miniprogram":return T(wx,"WeChat");case "douyin-miniprogram":return T(tt,"Douyin");case "browser":return K();case "node":return j()}}function K(){let t=window.localStorage;return {getItem(e){try{return t.getItem(e)}catch(n){return console.error("[AuthClient] Failed to get item from localStorage:",n),null}},setItem(e,n){try{t.setItem(e,n);}catch(r){console.error("[AuthClient] Failed to set item in localStorage:",r);}},removeItem(e){try{t.removeItem(e);}catch(n){console.error("[AuthClient] Failed to remove item from localStorage:",n);}},clear(){try{t.removeItem(d.ACCESS_TOKEN),t.removeItem(d.REFRESH_TOKEN),t.removeItem(d.USER);}catch(e){console.error("[AuthClient] Failed to clear localStorage:",e);}}}}function T(t,e){return {getItem(n){try{return t.getStorageSync(n)||null}catch(r){return console.error(`[AuthClient] Failed to get item from ${e} storage:`,r),null}},setItem(n,r){try{t.setStorageSync(n,r);}catch(o){console.error(`[AuthClient] Failed to set item in ${e} storage:`,o);}},removeItem(n){try{t.removeStorageSync(n);}catch(r){console.error(`[AuthClient] Failed to remove item from ${e} storage:`,r);}},clear(){try{t.removeStorageSync(d.ACCESS_TOKEN),t.removeStorageSync(d.REFRESH_TOKEN),t.removeStorageSync(d.USER);}catch(n){console.error(`[AuthClient] Failed to clear ${e} storage:`,n);}}}}function j(){let t=new Map;return {getItem(e){return t.get(e)??null},setItem(e,n){t.set(e,n);},removeItem(e){t.delete(e);},clear(){t.clear();}}}function D(t){try{let e=t.split(".");if(e.length!==3)return null;let r=(e[1]||"").replace(/-/g,"+").replace(/_/g,"/");if(typeof atob<"u"){let o=decodeURIComponent(atob(r).split("").map(l=>"%"+("00"+l.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(o)}if(typeof Buffer<"u"){let o=Buffer.from(r,"base64").toString("utf-8");return JSON.parse(o)}return null}catch(e){return console.error("[AuthClient] Failed to parse JWT token:",e),null}}var v=class{constructor(){this.refreshTimer=null;this.isRefreshing=false;this.refreshCallback=null;}setRefreshCallback(e){this.refreshCallback=e;}scheduleRefresh(e){this.clearSchedule(),!(e<=0)&&(this.refreshTimer=setTimeout(()=>{this.refresh();},e));}scheduleRefreshFromToken(e,n=300){let r=D(e);if(!r||!r.exp){console.warn("[AuthClient] Cannot schedule refresh: invalid token or missing exp claim");return}let o=r.exp*1e3,l=Date.now(),a=o-l-n*1e3;a<=0?(console.warn("[AuthClient] Token already expired or expiring soon, refreshing immediately"),this.refresh()):this.scheduleRefresh(a);}async refresh(){if(!this.isRefreshing){if(!this.refreshCallback){console.error("[AuthClient] No refresh callback set");return}this.isRefreshing=true;try{await this.refreshCallback();}catch(e){console.error("[AuthClient] Token refresh failed:",e);}finally{this.isRefreshing=false;}}}clearSchedule(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}isCurrentlyRefreshing(){return this.isRefreshing}destroy(){this.clearSchedule(),this.refreshCallback=null,this.isRefreshing=false;}};function E(t){return t&&typeof t=="object"&&("statusCode"in t||"status"in t)&&"data"in t?t.data:t}var k={transformResponse:E,logErrors:true};function J(t){if(t.email)return "email";if(t.username)return "username";if(t.phone)return "phone"}function W(t){if(t.email)return "email";if(t.phone)return "phone"}function G(t){let e=new URLSearchParams(t);return e.get("access_token")||e.get("accessToken")}function Y(t){return new URLSearchParams(t).get("user")}function Q(){if(typeof window>"u")return null;try{let t=new URLSearchParams(window.location.search).get("redirect");if(!t)return null;let e=new URL(t,window.location.origin);return e.origin!==window.location.origin?(console.warn("[AuthClient] Ignored cross-origin redirect target:",t),null):`${e.pathname}${e.search}${e.hash}`}catch(t){return console.warn("[AuthClient] Failed to resolve redirect target:",t),null}}var V={replace(t){window.location.replace(t);}};function R(t,e){return e.handled?{...t,redirectHandled:true,redirectTarget:e.target}:t}function A(t){if(!t||typeof window>"u"||window.opener)return {handled:false};let e=Q();return e?(V.replace(e),{handled:true,target:e}):{handled:false}}function M(t){let{http:e,onLoginSuccess:n,onLogout:r,autoRedirectAfterLogin:o,storage:l,clearAuth:m}=t;return {async register(a){let s=await e.request({url:"/api/auth/register",method:"post",headers:{"Content-Type":"application/json"},data:a});if(s.data?.user&&s.data?.accessToken){n(s.data.user,s.data.accessToken);let h=A(o);s.data=R(s.data,h);}return s},async login(a){let s=a.loginType||J(a);if(!s)return {data:null,error:{message:"Unable to determine login type. Please provide email, username, or phone.",status:400},status:400};let h={...a,loginType:s},u=await e.request({url:"/api/auth/login",method:"post",headers:{"Content-Type":"application/json"},data:h});if(u.data?.user&&u.data?.accessToken){n(u.data.user,u.data.accessToken);let c=A(o);u.data=R(u.data,c);}return u},async loginWithCode(a){let s=a.loginType||W(a);if(!s)return {data:null,error:{message:"Unable to determine login type. Please provide email or phone.",status:400},status:400};let h={...a,loginType:s},u=await e.request({url:"/api/auth/login-with-code",method:"post",headers:{"Content-Type":"application/json"},data:h});if(u.data?.user&&u.data?.accessToken){n(u.data.user,u.data.accessToken);let c=A(o);u.data=R(u.data,c);}return u},async sendCode(a){return e.request({url:"/api/auth/send-code",method:"post",headers:{"Content-Type":"application/json"},data:a})},async getCaptcha(){return e.request({url:"/api/auth/captcha",method:"get"})},loginWithOAuth(a,s){if(typeof window>"u"){console.error("[AuthClient] OAuth login is only available in browser environment");return}let h=s?`/api/auth/oauth/${a}?redirect_url=${encodeURIComponent(s)}`:`/api/auth/oauth/${a}`;window.location.href=h;},async handleOAuthCallback(){if(typeof window>"u")return {data:null,error:{message:"OAuth callback is only available in browser environment",status:400},status:400};try{let a=window.location.hash.substring(1),s=G(a),h=Y(a);if(!s)return {data:null,error:{message:"OAuth callback failed: missing access token",status:400},status:400};let u;if(h)u=JSON.parse(decodeURIComponent(h));else {l.setItem(d.ACCESS_TOKEN,s);let p=await e.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${s}`}});if(!p.data)return {data:null,error:{message:"OAuth callback failed: unable to fetch user info",status:p.status||500},status:p.status||500};u=p.data;}if(n(u,s),window.history&&window.history.replaceState){let p=window.location.pathname+window.location.search;window.history.replaceState(null,"",p);}else window.location.hash="";let c=A(o);return {data:R({user:u,accessToken:s},c),error:null,status:200}}catch(a){return {data:null,error:{message:`OAuth callback failed: ${a instanceof Error?a.message:String(a)}`,status:400},status:400}}},async loginWithMiniProgram(a){let s=await e.request({url:"/api/auth/miniprogram/login",method:"post",headers:{"Content-Type":"application/json"},data:{code:a}});if(s.data?.user&&s.data?.accessToken){n(s.data.user,s.data.accessToken);let h=A(o);s.data=R(s.data,h);}return s},async getMiniProgramPhoneNumber(a){let s=l.getItem("amaster_access_token");return s?e.request({url:"/api/auth/miniprogram/phone",method:"post",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},data:{code:a}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async logout(){let a=l.getItem("amaster_access_token"),s=await e.request({url:"/api/auth/logout",method:"post",headers:a?{Authorization:`Bearer ${a}`}:void 0});return m(),r(),s},async refreshToken(){let a=await e.request({url:"/api/auth/refresh",method:"post"});return a.data?.accessToken&&l.setItem("amaster_access_token",a.data.accessToken),a}}}function O(t){let{getCurrentUser:e}=t;return {hasRole(n){let r=e();return !r||!r.roles?false:r.roles.includes(n)},hasPermission(n,r){let o=e();if(!o||!o.permissions)return false;let l=`${n}.${r}`;return o.permissions.includes(l)},hasAnyPermission(n){return n.some(({resource:r,action:o})=>this.hasPermission(r,o))},hasAllPermissions(n){return n.every(({resource:r,action:o})=>this.hasPermission(r,o))}}}function b(t){let{http:e,storage:n,onUserUpdate:r}=t;return {async getMe(){let o=n.getItem("amaster_access_token");if(!o)return {data:null,error:{message:"Not authenticated",status:401},status:401};let l=await e.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${o}`}});return l.data&&r(l.data),l},async updateMe(o){let l=n.getItem("amaster_access_token");if(!l)return {data:null,error:{message:"Not authenticated",status:401},status:401};let m=await e.request({url:"/api/auth/me",method:"put",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},data:o});return m.data&&r(m.data),m},async changePassword(o){let l=n.getItem("amaster_access_token");return l?e.request({url:"/api/auth/change-password",method:"post",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},data:o}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function U(t){let{http:e,storage:n}=t;return {async getOAuthBindings(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/oauth-bindings",method:"get",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},bindOAuth(r){if(typeof window>"u"){console.error("[AuthClient] OAuth binding is only available in browser environment");return}window.location.href=`/api/auth/oauth/${r}/bind`;},async unbindOAuth(r){let o=n.getItem("amaster_access_token");return o?e.request({url:`/api/auth/oauth/${r}/unbind`,method:"delete",headers:{Authorization:`Bearer ${o}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function I(t){let{http:e,storage:n}=t;return {async getSession(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/sessions/current",method:"get",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async getSessions(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/sessions",method:"get",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeSession(r){let o=n.getItem("amaster_access_token");return o?r?e.request({url:`/api/auth/sessions/${r}`,method:"delete",headers:{Authorization:`Bearer ${o}`}}):{data:null,error:{message:"Session ID is required",status:400},status:400}:{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeAllSessions(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/sessions",method:"delete",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function Z(t={},e){let {baseURL:n,headers:r,onTokenExpired:o,onUnauthorized:l,autoHandleOAuthCallback:m=true,autoRedirectAfterLogin:a=true}=t,s=e||httpClient.createHttpClient({...k,baseURL:n,headers:r}),u=300,c=P(),p=new S,C=new v,y=null;try{let i=c.getItem(d.USER);i&&(y=JSON.parse(i));}catch(i){console.error("[AuthClient] Failed to load user from storage:",i);}let f;C.setRefreshCallback(async()=>{let i=await f.refreshToken();i.data?(await f.getMe(),p.emit("tokenRefreshed",i.data.accessToken)):(p.emit("tokenExpired"),o?.());});function L(i,g){c.setItem(d.ACCESS_TOKEN,g),c.setItem(d.USER,JSON.stringify(i)),y=i,C.scheduleRefreshFromToken(g,u),p.emit("login",i);}function _(i){y=i,c.setItem(d.USER,JSON.stringify(i));}function x(){p.emit("logout");}function w(){c.clear(),y=null,C.clearSchedule();}function H(){return y}let N=M({http:s,onLoginSuccess:L,onLogout:x,autoRedirectAfterLogin:a,storage:c,clearAuth:w}),$=O({getCurrentUser:H}),q=b({http:s,storage:c,onUserUpdate:_}),B=U({http:s,storage:c}),F=I({http:s,storage:c});if(f={...N,...$,...q,...B,...F,on(i,g){p.on(i,g);},off(i,g){p.off(i,g);},isAuthenticated(){return !!c.getItem(d.ACCESS_TOKEN)},getAccessToken(){return c.getItem(d.ACCESS_TOKEN)},setAccessToken(i){c.setItem(d.ACCESS_TOKEN,i),C.scheduleRefreshFromToken(i,u);},clearAuth:w},f.on("unauthorized",()=>{l?.();}),f.isAuthenticated()&&f.getMe().catch(i=>{console.warn("[AuthClient] Failed to sync user info on init:",i);}),m&&typeof window<"u"){let i=window.location.hash;i&&(i.includes("access_token")||i.includes("accessToken"))&&f.handleOAuthCallback().then(g=>{g.error&&console.error("[AuthClient] Auto OAuth callback failed:",g.error);}).catch(g=>{console.error("[AuthClient] Auto OAuth callback error:",g);});}return f}exports.createAuthClient=Z;exports.defaultHttpClientOptions=k;exports.transformAmasterResponse=E;//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.d.cts
CHANGED
|
@@ -19,8 +19,8 @@ import { createPermissionsModule } from './permissions.cjs';
|
|
|
19
19
|
import { createUserModule } from './user.cjs';
|
|
20
20
|
import { createOAuthModule } from './oauth.cjs';
|
|
21
21
|
import { createSessionsModule } from './sessions.cjs';
|
|
22
|
-
import { A as AuthClientOptions, a as AuthEvent, E as EventHandler } from './types-
|
|
23
|
-
export { b as CaptchaResponse, C as ChangePasswordParams, c as CodeLoginParams, d as CodeLoginType, L as LoginParams, e as LoginResponse, f as LoginType, O as OAuthBinding,
|
|
22
|
+
import { A as AuthClientOptions, a as AuthEvent, E as EventHandler } from './types-YfiSfMTJ.cjs';
|
|
23
|
+
export { b as CaptchaResponse, C as ChangePasswordParams, c as CodeLoginParams, d as CodeLoginType, L as LoginParams, e as LoginResponse, f as LoginType, M as MiniProgramLoginParams, g as MiniProgramPhoneParams, h as MiniProgramPhoneResponse, O as OAuthBinding, i as OAuthProvider, P as Permission, j as PermissionDetail, R as RefreshTokenResponse, k as RegisterParams, l as RegisterResponse, m as RevokeAllSessionsResponse, n as Role, o as RoleDetail, S as SendCodeParams, p as SendCodeType, q as Session, r as SuccessResponse, U as UpdateMeParams, s as User } from './types-YfiSfMTJ.cjs';
|
|
24
24
|
|
|
25
25
|
/**
|
|
26
26
|
* Main Authentication Client
|
package/dist/index.d.ts
CHANGED
|
@@ -19,8 +19,8 @@ import { createPermissionsModule } from './permissions.js';
|
|
|
19
19
|
import { createUserModule } from './user.js';
|
|
20
20
|
import { createOAuthModule } from './oauth.js';
|
|
21
21
|
import { createSessionsModule } from './sessions.js';
|
|
22
|
-
import { A as AuthClientOptions, a as AuthEvent, E as EventHandler } from './types-
|
|
23
|
-
export { b as CaptchaResponse, C as ChangePasswordParams, c as CodeLoginParams, d as CodeLoginType, L as LoginParams, e as LoginResponse, f as LoginType, O as OAuthBinding,
|
|
22
|
+
import { A as AuthClientOptions, a as AuthEvent, E as EventHandler } from './types-YfiSfMTJ.js';
|
|
23
|
+
export { b as CaptchaResponse, C as ChangePasswordParams, c as CodeLoginParams, d as CodeLoginType, L as LoginParams, e as LoginResponse, f as LoginType, M as MiniProgramLoginParams, g as MiniProgramPhoneParams, h as MiniProgramPhoneResponse, O as OAuthBinding, i as OAuthProvider, P as Permission, j as PermissionDetail, R as RefreshTokenResponse, k as RegisterParams, l as RegisterResponse, m as RevokeAllSessionsResponse, n as Role, o as RoleDetail, S as SendCodeParams, p as SendCodeType, q as Session, r as SuccessResponse, U as UpdateMeParams, s as User } from './types-YfiSfMTJ.js';
|
|
24
24
|
|
|
25
25
|
/**
|
|
26
26
|
* Main Authentication Client
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {createHttpClient}from'@amaster.ai/http-client';var S=class{constructor(){this.events={};}on(e,n){this.events[e]||(this.events[e]=[]),this.events[e].push(n);}off(e,n){this.events[e]&&(this.events[e]=this.events[e].filter(r=>r!==n));}emit(e,...n){this.events[e]&&this.events[e].forEach(r=>{try{r(...n);}catch(o){console.error(`[AuthClient] Error in event handler for "${e}":`,o);}});}removeAllListeners(){this.events={};}};var d={ACCESS_TOKEN:"amaster_access_token",REFRESH_TOKEN:"amaster_refresh_token",USER:"amaster_user"};function z(){return typeof wx<"u"&&wx.getStorageSync?"wechat-miniprogram":typeof tt<"u"&&tt.getStorageSync?"douyin-miniprogram":typeof window<"u"&&typeof window.localStorage<"u"?"browser":"node"}function P(){switch(z()){case "wechat-miniprogram":return T(wx,"WeChat");case "douyin-miniprogram":return T(tt,"Douyin");case "browser":return K();case "node":return j()}}function K(){let t=window.localStorage;return {getItem(e){try{return t.getItem(e)}catch(n){return console.error("[AuthClient] Failed to get item from localStorage:",n),null}},setItem(e,n){try{t.setItem(e,n);}catch(r){console.error("[AuthClient] Failed to set item in localStorage:",r);}},removeItem(e){try{t.removeItem(e);}catch(n){console.error("[AuthClient] Failed to remove item from localStorage:",n);}},clear(){try{t.removeItem(d.ACCESS_TOKEN),t.removeItem(d.REFRESH_TOKEN),t.removeItem(d.USER);}catch(e){console.error("[AuthClient] Failed to clear localStorage:",e);}}}}function T(t,e){return {getItem(n){try{return t.getStorageSync(n)||null}catch(r){return console.error(`[AuthClient] Failed to get item from ${e} storage:`,r),null}},setItem(n,r){try{t.setStorageSync(n,r);}catch(o){console.error(`[AuthClient] Failed to set item in ${e} storage:`,o);}},removeItem(n){try{t.removeStorageSync(n);}catch(r){console.error(`[AuthClient] Failed to remove item from ${e} storage:`,r);}},clear(){try{t.removeStorageSync(d.ACCESS_TOKEN),t.removeStorageSync(d.REFRESH_TOKEN),t.removeStorageSync(d.USER);}catch(n){console.error(`[AuthClient] Failed to clear ${e} storage:`,n);}}}}function j(){let t=new Map;return {getItem(e){return t.get(e)??null},setItem(e,n){t.set(e,n);},removeItem(e){t.delete(e);},clear(){t.clear();}}}function D(t){try{let e=t.split(".");if(e.length!==3)return null;let r=(e[1]||"").replace(/-/g,"+").replace(/_/g,"/");if(typeof atob<"u"){let o=decodeURIComponent(atob(r).split("").map(l=>"%"+("00"+l.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(o)}if(typeof Buffer<"u"){let o=Buffer.from(r,"base64").toString("utf-8");return JSON.parse(o)}return null}catch(e){return console.error("[AuthClient] Failed to parse JWT token:",e),null}}var v=class{constructor(){this.refreshTimer=null;this.isRefreshing=false;this.refreshCallback=null;}setRefreshCallback(e){this.refreshCallback=e;}scheduleRefresh(e){this.clearSchedule(),!(e<=0)&&(this.refreshTimer=setTimeout(()=>{this.refresh();},e));}scheduleRefreshFromToken(e,n=300){let r=D(e);if(!r||!r.exp){console.warn("[AuthClient] Cannot schedule refresh: invalid token or missing exp claim");return}let o=r.exp*1e3,l=Date.now(),a=o-l-n*1e3;a<=0?(console.warn("[AuthClient] Token already expired or expiring soon, refreshing immediately"),this.refresh()):this.scheduleRefresh(a);}async refresh(){if(!this.isRefreshing){if(!this.refreshCallback){console.error("[AuthClient] No refresh callback set");return}this.isRefreshing=true;try{await this.refreshCallback();}catch(e){console.error("[AuthClient] Token refresh failed:",e);}finally{this.isRefreshing=false;}}}clearSchedule(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}isCurrentlyRefreshing(){return this.isRefreshing}destroy(){this.clearSchedule(),this.refreshCallback=null,this.isRefreshing=false;}};function E(t){return t&&typeof t=="object"&&("statusCode"in t||"status"in t)&&"data"in t?t.data:t}var k={transformResponse:E,logErrors:true};function J(t){if(t.email)return "email";if(t.username)return "username";if(t.phone)return "phone"}function W(t){if(t.email)return "email";if(t.phone)return "phone"}function G(t){let e=new URLSearchParams(t);return e.get("access_token")||e.get("accessToken")}function Y(t){return new URLSearchParams(t).get("user")}function Q(){if(typeof window>"u")return null;try{let t=new URLSearchParams(window.location.search).get("redirect");if(!t)return null;let e=new URL(t,window.location.origin);return e.origin!==window.location.origin?(console.warn("[AuthClient] Ignored cross-origin redirect target:",t),null):`${e.pathname}${e.search}${e.hash}`}catch(t){return console.warn("[AuthClient] Failed to resolve redirect target:",t),null}}var V={replace(t){window.location.replace(t);}};function R(t,e){return e.handled?{...t,redirectHandled:true,redirectTarget:e.target}:t}function A(t){if(!t||typeof window>"u"||window.opener)return {handled:false};let e=Q();return e?(V.replace(e),{handled:true,target:e}):{handled:false}}function O(t){let{http:e,onLoginSuccess:n,onLogout:r,autoRedirectAfterLogin:o,storage:l,clearAuth:m}=t;return {async register(a){let s=await e.request({url:"/api/auth/register",method:"post",headers:{"Content-Type":"application/json"},data:a});if(s.data?.user&&s.data?.accessToken){n(s.data.user,s.data.accessToken);let h=A(o);s.data=R(s.data,h);}return s},async login(a){let s=a.loginType||J(a);if(!s)return {data:null,error:{message:"Unable to determine login type. Please provide email, username, or phone.",status:400},status:400};let h={...a,loginType:s},u=await e.request({url:"/api/auth/login",method:"post",headers:{"Content-Type":"application/json"},data:h});if(u.data?.user&&u.data?.accessToken){n(u.data.user,u.data.accessToken);let c=A(o);u.data=R(u.data,c);}return u},async loginWithCode(a){let s=a.loginType||W(a);if(!s)return {data:null,error:{message:"Unable to determine login type. Please provide email or phone.",status:400},status:400};let h={...a,loginType:s},u=await e.request({url:"/api/auth/login-with-code",method:"post",headers:{"Content-Type":"application/json"},data:h});if(u.data?.user&&u.data?.accessToken){n(u.data.user,u.data.accessToken);let c=A(o);u.data=R(u.data,c);}return u},async sendCode(a){return e.request({url:"/api/auth/send-code",method:"post",headers:{"Content-Type":"application/json"},data:a})},async getCaptcha(){return e.request({url:"/api/auth/captcha",method:"get"})},loginWithOAuth(a,s){if(typeof window>"u"){console.error("[AuthClient] OAuth login is only available in browser environment");return}let h=s?`/api/auth/oauth/${a}?redirect_url=${encodeURIComponent(s)}`:`/api/auth/oauth/${a}`;window.location.href=h;},async handleOAuthCallback(){if(typeof window>"u")return {data:null,error:{message:"OAuth callback is only available in browser environment",status:400},status:400};try{let a=window.location.hash.substring(1),s=G(a),h=Y(a);if(!s)return {data:null,error:{message:"OAuth callback failed: missing access token",status:400},status:400};let u;if(h)u=JSON.parse(decodeURIComponent(h));else {l.setItem(d.ACCESS_TOKEN,s);let p=await e.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${s}`}});if(!p.data)return {data:null,error:{message:"OAuth callback failed: unable to fetch user info",status:p.status||500},status:p.status||500};u=p.data;}if(n(u,s),window.history&&window.history.replaceState){let p=window.location.pathname+window.location.search;window.history.replaceState(null,"",p);}else window.location.hash="";let c=A(o);return {data:R({user:u,accessToken:s},c),error:null,status:200}}catch(a){return {data:null,error:{message:`OAuth callback failed: ${a instanceof Error?a.message:String(a)}`,status:400},status:400}}},async loginWithMiniProgram(a){let s=await e.request({url:"/api/auth/miniprogram/login",method:"post",headers:{"Content-Type":"application/json"},data:{code:a}});if(s.data?.user&&s.data?.accessToken){n(s.data.user,s.data.accessToken);let h=A(o);s.data=R(s.data,h);}return s},async getMiniProgramPhoneNumber(a){let s=l.getItem("amaster_access_token");return s?e.request({url:"/api/auth/miniprogram/phone",method:"post",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},data:{code:a}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async logout(){let a=l.getItem("amaster_access_token"),s=await e.request({url:"/api/auth/logout",method:"post",headers:a?{Authorization:`Bearer ${a}`}:void 0});return m(),r(),s},async refreshToken(){let a=await e.request({url:"/api/auth/refresh",method:"post"});return a.data?.accessToken&&l.setItem("amaster_access_token",a.data.accessToken),a}}}function b(t){let{getCurrentUser:e}=t;return {hasRole(n){let r=e();return !r||!r.roles?false:r.roles.includes(n)},hasPermission(n,r){let o=e();if(!o||!o.permissions)return false;let l=`${n}.${r}`;return o.permissions.includes(l)},hasAnyPermission(n){return n.some(({resource:r,action:o})=>this.hasPermission(r,o))},hasAllPermissions(n){return n.every(({resource:r,action:o})=>this.hasPermission(r,o))}}}function M(t){let{http:e,storage:n,onUserUpdate:r}=t;return {async getMe(){let o=n.getItem("amaster_access_token");if(!o)return {data:null,error:{message:"Not authenticated",status:401},status:401};let l=await e.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${o}`}});return l.data&&r(l.data),l},async updateMe(o){let l=n.getItem("amaster_access_token");if(!l)return {data:null,error:{message:"Not authenticated",status:401},status:401};let m=await e.request({url:"/api/auth/me",method:"put",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},data:o});return m.data&&r(m.data),m},async changePassword(o){let l=n.getItem("amaster_access_token");return l?e.request({url:"/api/auth/change-password",method:"post",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},data:o}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function U(t){let{http:e,storage:n}=t;return {async getOAuthBindings(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/oauth-bindings",method:"get",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},bindOAuth(r){if(typeof window>"u"){console.error("[AuthClient] OAuth binding is only available in browser environment");return}window.location.href=`/api/auth/oauth/${r}/bind`;},async unbindOAuth(r){let o=n.getItem("amaster_access_token");return o?e.request({url:`/api/auth/oauth/${r}/unbind`,method:"delete",headers:{Authorization:`Bearer ${o}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function I(t){let{http:e,storage:n}=t;return {async getSession(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/sessions/current",method:"get",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async getSessions(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/sessions",method:"get",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeSession(r){let o=n.getItem("amaster_access_token");return o?r?e.request({url:`/api/auth/sessions/${r}`,method:"delete",headers:{Authorization:`Bearer ${o}`}}):{data:null,error:{message:"Session ID is required",status:400},status:400}:{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeAllSessions(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/sessions",method:"delete",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function Z(t={},e){let {baseURL:n,headers:r,onTokenExpired:o,onUnauthorized:l,autoHandleOAuthCallback:m=true,autoRedirectAfterLogin:a=true}=t,s=e||createHttpClient({...k,baseURL:n,headers:r}),u=300,c=P(),p=new S,C=new v,y=null;try{let i=c.getItem(d.USER);i&&(y=JSON.parse(i));}catch(i){console.error("[AuthClient] Failed to load user from storage:",i);}let f;C.setRefreshCallback(async()=>{let i=await f.refreshToken();i.data?(await f.getMe(),p.emit("tokenRefreshed",i.data.accessToken)):(p.emit("tokenExpired"),o?.());});function L(i,g){c.setItem(d.ACCESS_TOKEN,g),c.setItem(d.USER,JSON.stringify(i)),y=i,C.scheduleRefreshFromToken(g,u),p.emit("login",i);}function _(i){y=i,c.setItem(d.USER,JSON.stringify(i));}function x(){p.emit("logout");}function w(){c.clear(),y=null,C.clearSchedule();}function H(){return y}let N=O({http:s,onLoginSuccess:L,onLogout:x,autoRedirectAfterLogin:a,storage:c,clearAuth:w}),$=b({getCurrentUser:H}),q=M({http:s,storage:c,onUserUpdate:_}),B=U({http:s,storage:c}),F=I({http:s,storage:c});if(f={...N,...$,...q,...B,...F,on(i,g){p.on(i,g);},off(i,g){p.off(i,g);},isAuthenticated(){return !!c.getItem(d.ACCESS_TOKEN)},getAccessToken(){return c.getItem(d.ACCESS_TOKEN)},setAccessToken(i){c.setItem(d.ACCESS_TOKEN,i),C.scheduleRefreshFromToken(i,u);},clearAuth:w},f.on("unauthorized",()=>{l?.();}),f.isAuthenticated()&&f.getMe().catch(i=>{console.warn("[AuthClient] Failed to sync user info on init:",i);}),m&&typeof window<"u"){let i=window.location.hash;i&&(i.includes("access_token")||i.includes("accessToken"))&&f.handleOAuthCallback().then(g=>{g.error&&console.error("[AuthClient] Auto OAuth callback failed:",g.error);}).catch(g=>{console.error("[AuthClient] Auto OAuth callback error:",g);});}return f}export{Z as createAuthClient,k as defaultHttpClientOptions,E as transformAmasterResponse};//# sourceMappingURL=index.js.map
|
|
1
|
+
import {createHttpClient}from'@amaster.ai/http-client';var S=class{constructor(){this.events={};}on(e,n){this.events[e]||(this.events[e]=[]),this.events[e].push(n);}off(e,n){this.events[e]&&(this.events[e]=this.events[e].filter(r=>r!==n));}emit(e,...n){this.events[e]&&this.events[e].forEach(r=>{try{r(...n);}catch(o){console.error(`[AuthClient] Error in event handler for "${e}":`,o);}});}removeAllListeners(){this.events={};}};var d={ACCESS_TOKEN:"amaster_access_token",REFRESH_TOKEN:"amaster_refresh_token",USER:"amaster_user"};function z(){return typeof wx<"u"&&wx.getStorageSync?"wechat-miniprogram":typeof tt<"u"&&tt.getStorageSync?"douyin-miniprogram":typeof window<"u"&&typeof window.localStorage<"u"?"browser":"node"}function P(){switch(z()){case "wechat-miniprogram":return T(wx,"WeChat");case "douyin-miniprogram":return T(tt,"Douyin");case "browser":return K();case "node":return j()}}function K(){let t=window.localStorage;return {getItem(e){try{return t.getItem(e)}catch(n){return console.error("[AuthClient] Failed to get item from localStorage:",n),null}},setItem(e,n){try{t.setItem(e,n);}catch(r){console.error("[AuthClient] Failed to set item in localStorage:",r);}},removeItem(e){try{t.removeItem(e);}catch(n){console.error("[AuthClient] Failed to remove item from localStorage:",n);}},clear(){try{t.removeItem(d.ACCESS_TOKEN),t.removeItem(d.REFRESH_TOKEN),t.removeItem(d.USER);}catch(e){console.error("[AuthClient] Failed to clear localStorage:",e);}}}}function T(t,e){return {getItem(n){try{return t.getStorageSync(n)||null}catch(r){return console.error(`[AuthClient] Failed to get item from ${e} storage:`,r),null}},setItem(n,r){try{t.setStorageSync(n,r);}catch(o){console.error(`[AuthClient] Failed to set item in ${e} storage:`,o);}},removeItem(n){try{t.removeStorageSync(n);}catch(r){console.error(`[AuthClient] Failed to remove item from ${e} storage:`,r);}},clear(){try{t.removeStorageSync(d.ACCESS_TOKEN),t.removeStorageSync(d.REFRESH_TOKEN),t.removeStorageSync(d.USER);}catch(n){console.error(`[AuthClient] Failed to clear ${e} storage:`,n);}}}}function j(){let t=new Map;return {getItem(e){return t.get(e)??null},setItem(e,n){t.set(e,n);},removeItem(e){t.delete(e);},clear(){t.clear();}}}function D(t){try{let e=t.split(".");if(e.length!==3)return null;let r=(e[1]||"").replace(/-/g,"+").replace(/_/g,"/");if(typeof atob<"u"){let o=decodeURIComponent(atob(r).split("").map(l=>"%"+("00"+l.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(o)}if(typeof Buffer<"u"){let o=Buffer.from(r,"base64").toString("utf-8");return JSON.parse(o)}return null}catch(e){return console.error("[AuthClient] Failed to parse JWT token:",e),null}}var v=class{constructor(){this.refreshTimer=null;this.isRefreshing=false;this.refreshCallback=null;}setRefreshCallback(e){this.refreshCallback=e;}scheduleRefresh(e){this.clearSchedule(),!(e<=0)&&(this.refreshTimer=setTimeout(()=>{this.refresh();},e));}scheduleRefreshFromToken(e,n=300){let r=D(e);if(!r||!r.exp){console.warn("[AuthClient] Cannot schedule refresh: invalid token or missing exp claim");return}let o=r.exp*1e3,l=Date.now(),a=o-l-n*1e3;a<=0?(console.warn("[AuthClient] Token already expired or expiring soon, refreshing immediately"),this.refresh()):this.scheduleRefresh(a);}async refresh(){if(!this.isRefreshing){if(!this.refreshCallback){console.error("[AuthClient] No refresh callback set");return}this.isRefreshing=true;try{await this.refreshCallback();}catch(e){console.error("[AuthClient] Token refresh failed:",e);}finally{this.isRefreshing=false;}}}clearSchedule(){this.refreshTimer&&(clearTimeout(this.refreshTimer),this.refreshTimer=null);}isCurrentlyRefreshing(){return this.isRefreshing}destroy(){this.clearSchedule(),this.refreshCallback=null,this.isRefreshing=false;}};function E(t){return t&&typeof t=="object"&&("statusCode"in t||"status"in t)&&"data"in t?t.data:t}var k={transformResponse:E,logErrors:true};function J(t){if(t.email)return "email";if(t.username)return "username";if(t.phone)return "phone"}function W(t){if(t.email)return "email";if(t.phone)return "phone"}function G(t){let e=new URLSearchParams(t);return e.get("access_token")||e.get("accessToken")}function Y(t){return new URLSearchParams(t).get("user")}function Q(){if(typeof window>"u")return null;try{let t=new URLSearchParams(window.location.search).get("redirect");if(!t)return null;let e=new URL(t,window.location.origin);return e.origin!==window.location.origin?(console.warn("[AuthClient] Ignored cross-origin redirect target:",t),null):`${e.pathname}${e.search}${e.hash}`}catch(t){return console.warn("[AuthClient] Failed to resolve redirect target:",t),null}}var V={replace(t){window.location.replace(t);}};function R(t,e){return e.handled?{...t,redirectHandled:true,redirectTarget:e.target}:t}function A(t){if(!t||typeof window>"u"||window.opener)return {handled:false};let e=Q();return e?(V.replace(e),{handled:true,target:e}):{handled:false}}function M(t){let{http:e,onLoginSuccess:n,onLogout:r,autoRedirectAfterLogin:o,storage:l,clearAuth:m}=t;return {async register(a){let s=await e.request({url:"/api/auth/register",method:"post",headers:{"Content-Type":"application/json"},data:a});if(s.data?.user&&s.data?.accessToken){n(s.data.user,s.data.accessToken);let h=A(o);s.data=R(s.data,h);}return s},async login(a){let s=a.loginType||J(a);if(!s)return {data:null,error:{message:"Unable to determine login type. Please provide email, username, or phone.",status:400},status:400};let h={...a,loginType:s},u=await e.request({url:"/api/auth/login",method:"post",headers:{"Content-Type":"application/json"},data:h});if(u.data?.user&&u.data?.accessToken){n(u.data.user,u.data.accessToken);let c=A(o);u.data=R(u.data,c);}return u},async loginWithCode(a){let s=a.loginType||W(a);if(!s)return {data:null,error:{message:"Unable to determine login type. Please provide email or phone.",status:400},status:400};let h={...a,loginType:s},u=await e.request({url:"/api/auth/login-with-code",method:"post",headers:{"Content-Type":"application/json"},data:h});if(u.data?.user&&u.data?.accessToken){n(u.data.user,u.data.accessToken);let c=A(o);u.data=R(u.data,c);}return u},async sendCode(a){return e.request({url:"/api/auth/send-code",method:"post",headers:{"Content-Type":"application/json"},data:a})},async getCaptcha(){return e.request({url:"/api/auth/captcha",method:"get"})},loginWithOAuth(a,s){if(typeof window>"u"){console.error("[AuthClient] OAuth login is only available in browser environment");return}let h=s?`/api/auth/oauth/${a}?redirect_url=${encodeURIComponent(s)}`:`/api/auth/oauth/${a}`;window.location.href=h;},async handleOAuthCallback(){if(typeof window>"u")return {data:null,error:{message:"OAuth callback is only available in browser environment",status:400},status:400};try{let a=window.location.hash.substring(1),s=G(a),h=Y(a);if(!s)return {data:null,error:{message:"OAuth callback failed: missing access token",status:400},status:400};let u;if(h)u=JSON.parse(decodeURIComponent(h));else {l.setItem(d.ACCESS_TOKEN,s);let p=await e.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${s}`}});if(!p.data)return {data:null,error:{message:"OAuth callback failed: unable to fetch user info",status:p.status||500},status:p.status||500};u=p.data;}if(n(u,s),window.history&&window.history.replaceState){let p=window.location.pathname+window.location.search;window.history.replaceState(null,"",p);}else window.location.hash="";let c=A(o);return {data:R({user:u,accessToken:s},c),error:null,status:200}}catch(a){return {data:null,error:{message:`OAuth callback failed: ${a instanceof Error?a.message:String(a)}`,status:400},status:400}}},async loginWithMiniProgram(a){let s=await e.request({url:"/api/auth/miniprogram/login",method:"post",headers:{"Content-Type":"application/json"},data:{code:a}});if(s.data?.user&&s.data?.accessToken){n(s.data.user,s.data.accessToken);let h=A(o);s.data=R(s.data,h);}return s},async getMiniProgramPhoneNumber(a){let s=l.getItem("amaster_access_token");return s?e.request({url:"/api/auth/miniprogram/phone",method:"post",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},data:{code:a}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async logout(){let a=l.getItem("amaster_access_token"),s=await e.request({url:"/api/auth/logout",method:"post",headers:a?{Authorization:`Bearer ${a}`}:void 0});return m(),r(),s},async refreshToken(){let a=await e.request({url:"/api/auth/refresh",method:"post"});return a.data?.accessToken&&l.setItem("amaster_access_token",a.data.accessToken),a}}}function O(t){let{getCurrentUser:e}=t;return {hasRole(n){let r=e();return !r||!r.roles?false:r.roles.includes(n)},hasPermission(n,r){let o=e();if(!o||!o.permissions)return false;let l=`${n}.${r}`;return o.permissions.includes(l)},hasAnyPermission(n){return n.some(({resource:r,action:o})=>this.hasPermission(r,o))},hasAllPermissions(n){return n.every(({resource:r,action:o})=>this.hasPermission(r,o))}}}function b(t){let{http:e,storage:n,onUserUpdate:r}=t;return {async getMe(){let o=n.getItem("amaster_access_token");if(!o)return {data:null,error:{message:"Not authenticated",status:401},status:401};let l=await e.request({url:"/api/auth/me",method:"get",headers:{Authorization:`Bearer ${o}`}});return l.data&&r(l.data),l},async updateMe(o){let l=n.getItem("amaster_access_token");if(!l)return {data:null,error:{message:"Not authenticated",status:401},status:401};let m=await e.request({url:"/api/auth/me",method:"put",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},data:o});return m.data&&r(m.data),m},async changePassword(o){let l=n.getItem("amaster_access_token");return l?e.request({url:"/api/auth/change-password",method:"post",headers:{Authorization:`Bearer ${l}`,"Content-Type":"application/json"},data:o}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function U(t){let{http:e,storage:n}=t;return {async getOAuthBindings(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/oauth-bindings",method:"get",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},bindOAuth(r){if(typeof window>"u"){console.error("[AuthClient] OAuth binding is only available in browser environment");return}window.location.href=`/api/auth/oauth/${r}/bind`;},async unbindOAuth(r){let o=n.getItem("amaster_access_token");return o?e.request({url:`/api/auth/oauth/${r}/unbind`,method:"delete",headers:{Authorization:`Bearer ${o}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function I(t){let{http:e,storage:n}=t;return {async getSession(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/sessions/current",method:"get",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async getSessions(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/sessions",method:"get",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeSession(r){let o=n.getItem("amaster_access_token");return o?r?e.request({url:`/api/auth/sessions/${r}`,method:"delete",headers:{Authorization:`Bearer ${o}`}}):{data:null,error:{message:"Session ID is required",status:400},status:400}:{data:null,error:{message:"Not authenticated",status:401},status:401}},async revokeAllSessions(){let r=n.getItem("amaster_access_token");return r?e.request({url:"/api/auth/sessions",method:"delete",headers:{Authorization:`Bearer ${r}`}}):{data:null,error:{message:"Not authenticated",status:401},status:401}}}}function Z(t={},e){let {baseURL:n,headers:r,onTokenExpired:o,onUnauthorized:l,autoHandleOAuthCallback:m=true,autoRedirectAfterLogin:a=true}=t,s=e||createHttpClient({...k,baseURL:n,headers:r}),u=300,c=P(),p=new S,C=new v,y=null;try{let i=c.getItem(d.USER);i&&(y=JSON.parse(i));}catch(i){console.error("[AuthClient] Failed to load user from storage:",i);}let f;C.setRefreshCallback(async()=>{let i=await f.refreshToken();i.data?(await f.getMe(),p.emit("tokenRefreshed",i.data.accessToken)):(p.emit("tokenExpired"),o?.());});function L(i,g){c.setItem(d.ACCESS_TOKEN,g),c.setItem(d.USER,JSON.stringify(i)),y=i,C.scheduleRefreshFromToken(g,u),p.emit("login",i);}function _(i){y=i,c.setItem(d.USER,JSON.stringify(i));}function x(){p.emit("logout");}function w(){c.clear(),y=null,C.clearSchedule();}function H(){return y}let N=M({http:s,onLoginSuccess:L,onLogout:x,autoRedirectAfterLogin:a,storage:c,clearAuth:w}),$=O({getCurrentUser:H}),q=b({http:s,storage:c,onUserUpdate:_}),B=U({http:s,storage:c}),F=I({http:s,storage:c});if(f={...N,...$,...q,...B,...F,on(i,g){p.on(i,g);},off(i,g){p.off(i,g);},isAuthenticated(){return !!c.getItem(d.ACCESS_TOKEN)},getAccessToken(){return c.getItem(d.ACCESS_TOKEN)},setAccessToken(i){c.setItem(d.ACCESS_TOKEN,i),C.scheduleRefreshFromToken(i,u);},clearAuth:w},f.on("unauthorized",()=>{l?.();}),f.isAuthenticated()&&f.getMe().catch(i=>{console.warn("[AuthClient] Failed to sync user info on init:",i);}),m&&typeof window<"u"){let i=window.location.hash;i&&(i.includes("access_token")||i.includes("accessToken"))&&f.handleOAuthCallback().then(g=>{g.error&&console.error("[AuthClient] Auto OAuth callback failed:",g.error);}).catch(g=>{console.error("[AuthClient] Auto OAuth callback error:",g);});}return f}export{Z as createAuthClient,k as defaultHttpClientOptions,E as transformAmasterResponse};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/oauth.d.cts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* ============================================================================
|
|
15
15
|
*/
|
|
16
16
|
import { HttpClient, ClientResult } from '@amaster.ai/http-client';
|
|
17
|
-
import { O as OAuthBinding,
|
|
17
|
+
import { O as OAuthBinding, i as OAuthProvider, r as SuccessResponse } from './types-YfiSfMTJ.cjs';
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* OAuth Module
|
package/dist/oauth.d.ts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* ============================================================================
|
|
15
15
|
*/
|
|
16
16
|
import { HttpClient, ClientResult } from '@amaster.ai/http-client';
|
|
17
|
-
import { O as OAuthBinding,
|
|
17
|
+
import { O as OAuthBinding, i as OAuthProvider, r as SuccessResponse } from './types-YfiSfMTJ.js';
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* OAuth Module
|
package/dist/permissions.d.cts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* ============================================================================
|
|
15
15
|
*/
|
|
16
16
|
import { HttpClient } from '@amaster.ai/http-client';
|
|
17
|
-
import {
|
|
17
|
+
import { s as User } from './types-YfiSfMTJ.cjs';
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* Permissions Module
|
package/dist/permissions.d.ts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* ============================================================================
|
|
15
15
|
*/
|
|
16
16
|
import { HttpClient } from '@amaster.ai/http-client';
|
|
17
|
-
import {
|
|
17
|
+
import { s as User } from './types-YfiSfMTJ.js';
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* Permissions Module
|
package/dist/sessions.d.cts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* ============================================================================
|
|
15
15
|
*/
|
|
16
16
|
import { HttpClient, ClientResult } from '@amaster.ai/http-client';
|
|
17
|
-
import {
|
|
17
|
+
import { q as Session, r as SuccessResponse, m as RevokeAllSessionsResponse } from './types-YfiSfMTJ.cjs';
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* Sessions Module
|
package/dist/sessions.d.ts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* ============================================================================
|
|
15
15
|
*/
|
|
16
16
|
import { HttpClient, ClientResult } from '@amaster.ai/http-client';
|
|
17
|
-
import {
|
|
17
|
+
import { q as Session, r as SuccessResponse, m as RevokeAllSessionsResponse } from './types-YfiSfMTJ.js';
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* Sessions Module
|
|
@@ -418,6 +418,46 @@ interface OAuthBinding {
|
|
|
418
418
|
avatarUrl: string | null;
|
|
419
419
|
createdAt: string;
|
|
420
420
|
}
|
|
421
|
+
/**
|
|
422
|
+
* WeChat Mini Program login parameters
|
|
423
|
+
* @example
|
|
424
|
+
* ```typescript
|
|
425
|
+
* // 1. Get code from WeChat
|
|
426
|
+
* wx.login({
|
|
427
|
+
* success: async (res) => {
|
|
428
|
+
* if (res.code) {
|
|
429
|
+
* await authClient.loginWithMiniProgram(res.code);
|
|
430
|
+
* }
|
|
431
|
+
* }
|
|
432
|
+
* });
|
|
433
|
+
* ```
|
|
434
|
+
*/
|
|
435
|
+
interface MiniProgramLoginParams {
|
|
436
|
+
/** Code from wx.login() API, valid for 5 minutes */
|
|
437
|
+
code: string;
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* WeChat Mini Program phone number parameters
|
|
441
|
+
* @example
|
|
442
|
+
* ```typescript
|
|
443
|
+
* // WXML
|
|
444
|
+
* <button open-type="getPhoneNumber" bindgetphonenumber="onGetPhoneNumber">
|
|
445
|
+
* Get Phone Number
|
|
446
|
+
* </button>
|
|
447
|
+
*
|
|
448
|
+
* // JS
|
|
449
|
+
* async onGetPhoneNumber(e) {
|
|
450
|
+
* const { code } = e.detail;
|
|
451
|
+
* if (code) {
|
|
452
|
+
* await authClient.getMiniProgramPhoneNumber(code);
|
|
453
|
+
* }
|
|
454
|
+
* }
|
|
455
|
+
* ```
|
|
456
|
+
*/
|
|
457
|
+
interface MiniProgramPhoneParams {
|
|
458
|
+
/** Code from getPhoneNumber button event */
|
|
459
|
+
code: string;
|
|
460
|
+
}
|
|
421
461
|
/**
|
|
422
462
|
* WeChat Mini Program phone number response
|
|
423
463
|
*/
|
|
@@ -499,4 +539,4 @@ interface RevokeAllSessionsResponse {
|
|
|
499
539
|
revokedCount: number;
|
|
500
540
|
}
|
|
501
541
|
|
|
502
|
-
export type { AuthClientOptions as A, ChangePasswordParams as C, EventHandler as E, LoginParams as L,
|
|
542
|
+
export type { AuthClientOptions as A, ChangePasswordParams as C, EventHandler as E, LoginParams as L, MiniProgramLoginParams as M, OAuthBinding as O, Permission as P, RefreshTokenResponse as R, SendCodeParams as S, UpdateMeParams as U, AuthEvent as a, CaptchaResponse as b, CodeLoginParams as c, CodeLoginType as d, LoginResponse as e, LoginType as f, MiniProgramPhoneParams as g, MiniProgramPhoneResponse as h, OAuthProvider as i, PermissionDetail as j, RegisterParams as k, RegisterResponse as l, RevokeAllSessionsResponse as m, Role as n, RoleDetail as o, SendCodeType as p, Session as q, SuccessResponse as r, User as s };
|
|
@@ -418,6 +418,46 @@ interface OAuthBinding {
|
|
|
418
418
|
avatarUrl: string | null;
|
|
419
419
|
createdAt: string;
|
|
420
420
|
}
|
|
421
|
+
/**
|
|
422
|
+
* WeChat Mini Program login parameters
|
|
423
|
+
* @example
|
|
424
|
+
* ```typescript
|
|
425
|
+
* // 1. Get code from WeChat
|
|
426
|
+
* wx.login({
|
|
427
|
+
* success: async (res) => {
|
|
428
|
+
* if (res.code) {
|
|
429
|
+
* await authClient.loginWithMiniProgram(res.code);
|
|
430
|
+
* }
|
|
431
|
+
* }
|
|
432
|
+
* });
|
|
433
|
+
* ```
|
|
434
|
+
*/
|
|
435
|
+
interface MiniProgramLoginParams {
|
|
436
|
+
/** Code from wx.login() API, valid for 5 minutes */
|
|
437
|
+
code: string;
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* WeChat Mini Program phone number parameters
|
|
441
|
+
* @example
|
|
442
|
+
* ```typescript
|
|
443
|
+
* // WXML
|
|
444
|
+
* <button open-type="getPhoneNumber" bindgetphonenumber="onGetPhoneNumber">
|
|
445
|
+
* Get Phone Number
|
|
446
|
+
* </button>
|
|
447
|
+
*
|
|
448
|
+
* // JS
|
|
449
|
+
* async onGetPhoneNumber(e) {
|
|
450
|
+
* const { code } = e.detail;
|
|
451
|
+
* if (code) {
|
|
452
|
+
* await authClient.getMiniProgramPhoneNumber(code);
|
|
453
|
+
* }
|
|
454
|
+
* }
|
|
455
|
+
* ```
|
|
456
|
+
*/
|
|
457
|
+
interface MiniProgramPhoneParams {
|
|
458
|
+
/** Code from getPhoneNumber button event */
|
|
459
|
+
code: string;
|
|
460
|
+
}
|
|
421
461
|
/**
|
|
422
462
|
* WeChat Mini Program phone number response
|
|
423
463
|
*/
|
|
@@ -499,4 +539,4 @@ interface RevokeAllSessionsResponse {
|
|
|
499
539
|
revokedCount: number;
|
|
500
540
|
}
|
|
501
541
|
|
|
502
|
-
export type { AuthClientOptions as A, ChangePasswordParams as C, EventHandler as E, LoginParams as L,
|
|
542
|
+
export type { AuthClientOptions as A, ChangePasswordParams as C, EventHandler as E, LoginParams as L, MiniProgramLoginParams as M, OAuthBinding as O, Permission as P, RefreshTokenResponse as R, SendCodeParams as S, UpdateMeParams as U, AuthEvent as a, CaptchaResponse as b, CodeLoginParams as c, CodeLoginType as d, LoginResponse as e, LoginType as f, MiniProgramPhoneParams as g, MiniProgramPhoneResponse as h, OAuthProvider as i, PermissionDetail as j, RegisterParams as k, RegisterResponse as l, RevokeAllSessionsResponse as m, Role as n, RoleDetail as o, SendCodeType as p, Session as q, SuccessResponse as r, User as s };
|
package/dist/user.d.cts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* ============================================================================
|
|
15
15
|
*/
|
|
16
16
|
import { HttpClient, ClientResult } from '@amaster.ai/http-client';
|
|
17
|
-
import {
|
|
17
|
+
import { s as User, U as UpdateMeParams, C as ChangePasswordParams, r as SuccessResponse } from './types-YfiSfMTJ.cjs';
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* User Management Module
|
package/dist/user.d.ts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* ============================================================================
|
|
15
15
|
*/
|
|
16
16
|
import { HttpClient, ClientResult } from '@amaster.ai/http-client';
|
|
17
|
-
import {
|
|
17
|
+
import { s as User, U as UpdateMeParams, C as ChangePasswordParams, r as SuccessResponse } from './types-YfiSfMTJ.js';
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* User Management Module
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amaster.ai/auth-client",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.2",
|
|
4
4
|
"description": "Authentication SDK for Amaster platform",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"registry": "https://registry.npmjs.org/"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@amaster.ai/http-client": "1.1.
|
|
50
|
+
"@amaster.ai/http-client": "1.1.2"
|
|
51
51
|
},
|
|
52
52
|
"peerDependencies": {
|
|
53
53
|
"axios": "^1.11.0"
|