@oxog/authkeeper 1.3.1 → 1.5.0
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/CHANGELOG.md +24 -0
- package/README.md +152 -2
- package/dist/auth-source-CXqrhLDO.d.ts +37 -0
- package/dist/auth-source-rjMWiP1Q.d.cts +37 -0
- package/dist/{chunk-NZPSW4M7.cjs → chunk-47JWRVTL.cjs} +21 -29
- package/dist/chunk-47JWRVTL.cjs.map +1 -0
- package/dist/{chunk-XUTTHBMF.js → chunk-ANGR5HRJ.js} +12 -19
- package/dist/chunk-ANGR5HRJ.js.map +1 -0
- package/dist/chunk-DLCD3SBV.js +17 -0
- package/dist/chunk-DLCD3SBV.js.map +1 -0
- package/dist/chunk-LGZGECYE.cjs +96 -0
- package/dist/chunk-LGZGECYE.cjs.map +1 -0
- package/dist/chunk-UUQDRHGF.js +90 -0
- package/dist/chunk-UUQDRHGF.js.map +1 -0
- package/dist/chunk-XGKVBZSF.cjs +19 -0
- package/dist/chunk-XGKVBZSF.cjs.map +1 -0
- package/dist/index-C4pGS-TI.d.cts +488 -0
- package/dist/index-CQwGO-Wk.d.ts +488 -0
- package/dist/index.cjs +71 -60
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -3
- package/dist/index.d.ts +9 -3
- package/dist/index.js +24 -12
- package/dist/index.js.map +1 -1
- package/dist/plugins/index.cjs +15 -14
- package/dist/plugins/index.d.cts +2 -1
- package/dist/plugins/index.d.ts +2 -1
- package/dist/plugins/index.js +2 -1
- package/dist/react/index.cjs +124 -3
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +136 -5
- package/dist/react/index.d.ts +136 -5
- package/dist/react/index.js +118 -3
- package/dist/react/index.js.map +1 -1
- package/dist/svelte/index.cjs +53 -3
- package/dist/svelte/index.cjs.map +1 -1
- package/dist/svelte/index.d.cts +54 -5
- package/dist/svelte/index.d.ts +54 -5
- package/dist/svelte/index.js +51 -3
- package/dist/svelte/index.js.map +1 -1
- package/dist/types-DMPBl-Ym.d.cts +421 -0
- package/dist/types-DMPBl-Ym.d.ts +421 -0
- package/dist/vue/index.cjs +75 -3
- package/dist/vue/index.cjs.map +1 -1
- package/dist/vue/index.d.cts +93 -5
- package/dist/vue/index.d.ts +93 -5
- package/dist/vue/index.js +70 -3
- package/dist/vue/index.js.map +1 -1
- package/package.json +14 -8
- package/dist/chunk-NZPSW4M7.cjs.map +0 -1
- package/dist/chunk-XUTTHBMF.js.map +0 -1
- package/dist/index-BakvZ2rC.d.cts +0 -906
- package/dist/index-BakvZ2rC.d.ts +0 -906
package/dist/react/index.d.cts
CHANGED
|
@@ -1,9 +1,140 @@
|
|
|
1
|
+
import { ReactNode, ReactElement, ComponentType, ForwardRefExoticComponent, ComponentPropsWithRef } from 'react';
|
|
2
|
+
import { b as AuthKeeper, T as TokenSet, L as LogoutOptions, A as AuthFetch, a as TokenPayload } from '../types-DMPBl-Ym.cjs';
|
|
3
|
+
import { A as AuthState, T as TokenState } from '../auth-source-rjMWiP1Q.cjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* React bindings: <AuthProvider> and useAuth()
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* <AuthProvider> props
|
|
11
|
+
*/
|
|
12
|
+
interface AuthProviderProps {
|
|
13
|
+
/** Instance returned by `createAuthKeeper()` */
|
|
14
|
+
auth: AuthKeeper;
|
|
15
|
+
children?: ReactNode;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Make an AuthKeeper instance available to `useAuth()` / `useAuthKeeper()`
|
|
19
|
+
*/
|
|
20
|
+
declare function AuthProvider({ auth, children }: AuthProviderProps): ReactElement;
|
|
21
|
+
/**
|
|
22
|
+
* The AuthKeeper instance from the nearest <AuthProvider>
|
|
23
|
+
* @throws {AuthError} CONFIG_ERROR outside an <AuthProvider>
|
|
24
|
+
*/
|
|
25
|
+
declare function useAuthKeeper(): AuthKeeper;
|
|
26
|
+
/**
|
|
27
|
+
* useAuth() return value: the auth state plus actions
|
|
28
|
+
*/
|
|
29
|
+
interface UseAuthReturn extends AuthState {
|
|
30
|
+
/** Store tokens (e.g. after your login request) */
|
|
31
|
+
setTokens: (tokens: TokenSet) => void;
|
|
32
|
+
logout: (options?: LogoutOptions) => void;
|
|
33
|
+
refresh: () => Promise<TokenSet>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Subscribe a component to the auth state.
|
|
37
|
+
*
|
|
38
|
+
* Re-renders after login, logout, refresh and error events and when the
|
|
39
|
+
* access token expires. On the server and during hydration the state is
|
|
40
|
+
* signed out; the client state follows right after hydration.
|
|
41
|
+
*
|
|
42
|
+
* @param auth - Instance to use (default: the one from <AuthProvider>)
|
|
43
|
+
*/
|
|
44
|
+
declare function useAuth(auth?: AuthKeeper): UseAuthReturn;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* React bindings: useToken() and useUser()
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* useToken() return value: the token state plus an authenticated fetch
|
|
52
|
+
*/
|
|
53
|
+
interface UseTokenReturn extends TokenState {
|
|
54
|
+
/** `fetch` that adds the access token (and refreshes on 401): `auth.createFetch()` */
|
|
55
|
+
authFetch: AuthFetch;
|
|
56
|
+
}
|
|
1
57
|
/**
|
|
2
|
-
*
|
|
58
|
+
* Subscribe a component to the tokens.
|
|
3
59
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
60
|
+
* Re-renders only when a token or the expiry changes (login, refresh, logout,
|
|
61
|
+
* expiry). On the server and during hydration there are no tokens.
|
|
62
|
+
*
|
|
63
|
+
* @param auth - Instance to use (default: the one from <AuthProvider>)
|
|
64
|
+
*/
|
|
65
|
+
declare function useToken(auth?: AuthKeeper): UseTokenReturn;
|
|
66
|
+
/**
|
|
67
|
+
* useUser() return value
|
|
68
|
+
*/
|
|
69
|
+
interface UseUserReturn {
|
|
70
|
+
/** Decoded access token payload (null when signed out or for opaque tokens) */
|
|
71
|
+
user: TokenPayload | null;
|
|
72
|
+
/** The payload's claims (empty when there is no user) */
|
|
73
|
+
claims: TokenPayload;
|
|
74
|
+
/** One claim of the payload */
|
|
75
|
+
getClaim: <K extends keyof TokenPayload>(key: K) => TokenPayload[K] | undefined;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Subscribe a component to the decoded access token payload.
|
|
79
|
+
*
|
|
80
|
+
* Re-renders only when the access token changes. On the server and during
|
|
81
|
+
* hydration there is no user.
|
|
82
|
+
*
|
|
83
|
+
* @param auth - Instance to use (default: the one from <AuthProvider>)
|
|
84
|
+
*/
|
|
85
|
+
declare function useUser(auth?: AuthKeeper): UseUserReturn;
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* React bindings: <RequireAuth> and withAuth()
|
|
89
|
+
*/
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Why <RequireAuth> did not render its children: signed out, or signed in
|
|
93
|
+
* without the required roles / permissions
|
|
94
|
+
*/
|
|
95
|
+
type UnauthorizedReason = 'unauthenticated' | 'forbidden';
|
|
96
|
+
/**
|
|
97
|
+
* <RequireAuth> props
|
|
98
|
+
*/
|
|
99
|
+
interface RequireAuthProps {
|
|
100
|
+
/** Rendered only while authorized */
|
|
101
|
+
children?: ReactNode;
|
|
102
|
+
/** Rendered while signed out or not allowed (default: nothing) */
|
|
103
|
+
fallback?: ReactNode;
|
|
104
|
+
/**
|
|
105
|
+
* Rendered on the server and during hydration, before the client auth state
|
|
106
|
+
* is known (default: nothing)
|
|
107
|
+
*/
|
|
108
|
+
loadingFallback?: ReactNode;
|
|
109
|
+
/** The user needs at least one of these roles (`roles` claim) */
|
|
110
|
+
roles?: readonly string[];
|
|
111
|
+
/** The user needs every one of these permissions (`permissions` claim) */
|
|
112
|
+
permissions?: readonly string[];
|
|
113
|
+
/**
|
|
114
|
+
* Called after rendering the fallback, once each time access is lost (e.g.
|
|
115
|
+
* to redirect to a login page)
|
|
116
|
+
*/
|
|
117
|
+
onUnauthorized?: (reason: UnauthorizedReason) => void;
|
|
118
|
+
/** Instance to use (default: the one from <AuthProvider>) */
|
|
119
|
+
auth?: AuthKeeper;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Render `children` only while the user is signed in (and has the required
|
|
123
|
+
* roles / permissions), else `fallback`.
|
|
124
|
+
*
|
|
125
|
+
* Re-renders only when access changes. On the server and during hydration it
|
|
126
|
+
* renders `loadingFallback`, so protected content never appears before the
|
|
127
|
+
* client state is known and the server markup matches the hydration render.
|
|
128
|
+
*/
|
|
129
|
+
declare function RequireAuth({ children, fallback, loadingFallback, roles, permissions, onUnauthorized, auth, }: RequireAuthProps): ReactElement;
|
|
130
|
+
/**
|
|
131
|
+
* withAuth() options: <RequireAuth> props
|
|
132
|
+
*/
|
|
133
|
+
type WithAuthOptions = Omit<RequireAuthProps, 'children'>;
|
|
134
|
+
/**
|
|
135
|
+
* Wrap a component in <RequireAuth>. The wrapper forwards its ref to the
|
|
136
|
+
* component and is named `withAuth(Name)`.
|
|
6
137
|
*/
|
|
7
|
-
declare
|
|
138
|
+
declare function withAuth<C extends ComponentType<any>>(Component: C, options?: WithAuthOptions): ForwardRefExoticComponent<ComponentPropsWithRef<C>>;
|
|
8
139
|
|
|
9
|
-
export {
|
|
140
|
+
export { AuthProvider, type AuthProviderProps, AuthState, RequireAuth, type RequireAuthProps, TokenState, type UnauthorizedReason, type UseAuthReturn, type UseTokenReturn, type UseUserReturn, type WithAuthOptions, useAuth, useAuthKeeper, useToken, useUser, withAuth };
|
package/dist/react/index.d.ts
CHANGED
|
@@ -1,9 +1,140 @@
|
|
|
1
|
+
import { ReactNode, ReactElement, ComponentType, ForwardRefExoticComponent, ComponentPropsWithRef } from 'react';
|
|
2
|
+
import { b as AuthKeeper, T as TokenSet, L as LogoutOptions, A as AuthFetch, a as TokenPayload } from '../types-DMPBl-Ym.js';
|
|
3
|
+
import { A as AuthState, T as TokenState } from '../auth-source-CXqrhLDO.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* React bindings: <AuthProvider> and useAuth()
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* <AuthProvider> props
|
|
11
|
+
*/
|
|
12
|
+
interface AuthProviderProps {
|
|
13
|
+
/** Instance returned by `createAuthKeeper()` */
|
|
14
|
+
auth: AuthKeeper;
|
|
15
|
+
children?: ReactNode;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Make an AuthKeeper instance available to `useAuth()` / `useAuthKeeper()`
|
|
19
|
+
*/
|
|
20
|
+
declare function AuthProvider({ auth, children }: AuthProviderProps): ReactElement;
|
|
21
|
+
/**
|
|
22
|
+
* The AuthKeeper instance from the nearest <AuthProvider>
|
|
23
|
+
* @throws {AuthError} CONFIG_ERROR outside an <AuthProvider>
|
|
24
|
+
*/
|
|
25
|
+
declare function useAuthKeeper(): AuthKeeper;
|
|
26
|
+
/**
|
|
27
|
+
* useAuth() return value: the auth state plus actions
|
|
28
|
+
*/
|
|
29
|
+
interface UseAuthReturn extends AuthState {
|
|
30
|
+
/** Store tokens (e.g. after your login request) */
|
|
31
|
+
setTokens: (tokens: TokenSet) => void;
|
|
32
|
+
logout: (options?: LogoutOptions) => void;
|
|
33
|
+
refresh: () => Promise<TokenSet>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Subscribe a component to the auth state.
|
|
37
|
+
*
|
|
38
|
+
* Re-renders after login, logout, refresh and error events and when the
|
|
39
|
+
* access token expires. On the server and during hydration the state is
|
|
40
|
+
* signed out; the client state follows right after hydration.
|
|
41
|
+
*
|
|
42
|
+
* @param auth - Instance to use (default: the one from <AuthProvider>)
|
|
43
|
+
*/
|
|
44
|
+
declare function useAuth(auth?: AuthKeeper): UseAuthReturn;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* React bindings: useToken() and useUser()
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* useToken() return value: the token state plus an authenticated fetch
|
|
52
|
+
*/
|
|
53
|
+
interface UseTokenReturn extends TokenState {
|
|
54
|
+
/** `fetch` that adds the access token (and refreshes on 401): `auth.createFetch()` */
|
|
55
|
+
authFetch: AuthFetch;
|
|
56
|
+
}
|
|
1
57
|
/**
|
|
2
|
-
*
|
|
58
|
+
* Subscribe a component to the tokens.
|
|
3
59
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
60
|
+
* Re-renders only when a token or the expiry changes (login, refresh, logout,
|
|
61
|
+
* expiry). On the server and during hydration there are no tokens.
|
|
62
|
+
*
|
|
63
|
+
* @param auth - Instance to use (default: the one from <AuthProvider>)
|
|
64
|
+
*/
|
|
65
|
+
declare function useToken(auth?: AuthKeeper): UseTokenReturn;
|
|
66
|
+
/**
|
|
67
|
+
* useUser() return value
|
|
68
|
+
*/
|
|
69
|
+
interface UseUserReturn {
|
|
70
|
+
/** Decoded access token payload (null when signed out or for opaque tokens) */
|
|
71
|
+
user: TokenPayload | null;
|
|
72
|
+
/** The payload's claims (empty when there is no user) */
|
|
73
|
+
claims: TokenPayload;
|
|
74
|
+
/** One claim of the payload */
|
|
75
|
+
getClaim: <K extends keyof TokenPayload>(key: K) => TokenPayload[K] | undefined;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Subscribe a component to the decoded access token payload.
|
|
79
|
+
*
|
|
80
|
+
* Re-renders only when the access token changes. On the server and during
|
|
81
|
+
* hydration there is no user.
|
|
82
|
+
*
|
|
83
|
+
* @param auth - Instance to use (default: the one from <AuthProvider>)
|
|
84
|
+
*/
|
|
85
|
+
declare function useUser(auth?: AuthKeeper): UseUserReturn;
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* React bindings: <RequireAuth> and withAuth()
|
|
89
|
+
*/
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Why <RequireAuth> did not render its children: signed out, or signed in
|
|
93
|
+
* without the required roles / permissions
|
|
94
|
+
*/
|
|
95
|
+
type UnauthorizedReason = 'unauthenticated' | 'forbidden';
|
|
96
|
+
/**
|
|
97
|
+
* <RequireAuth> props
|
|
98
|
+
*/
|
|
99
|
+
interface RequireAuthProps {
|
|
100
|
+
/** Rendered only while authorized */
|
|
101
|
+
children?: ReactNode;
|
|
102
|
+
/** Rendered while signed out or not allowed (default: nothing) */
|
|
103
|
+
fallback?: ReactNode;
|
|
104
|
+
/**
|
|
105
|
+
* Rendered on the server and during hydration, before the client auth state
|
|
106
|
+
* is known (default: nothing)
|
|
107
|
+
*/
|
|
108
|
+
loadingFallback?: ReactNode;
|
|
109
|
+
/** The user needs at least one of these roles (`roles` claim) */
|
|
110
|
+
roles?: readonly string[];
|
|
111
|
+
/** The user needs every one of these permissions (`permissions` claim) */
|
|
112
|
+
permissions?: readonly string[];
|
|
113
|
+
/**
|
|
114
|
+
* Called after rendering the fallback, once each time access is lost (e.g.
|
|
115
|
+
* to redirect to a login page)
|
|
116
|
+
*/
|
|
117
|
+
onUnauthorized?: (reason: UnauthorizedReason) => void;
|
|
118
|
+
/** Instance to use (default: the one from <AuthProvider>) */
|
|
119
|
+
auth?: AuthKeeper;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Render `children` only while the user is signed in (and has the required
|
|
123
|
+
* roles / permissions), else `fallback`.
|
|
124
|
+
*
|
|
125
|
+
* Re-renders only when access changes. On the server and during hydration it
|
|
126
|
+
* renders `loadingFallback`, so protected content never appears before the
|
|
127
|
+
* client state is known and the server markup matches the hydration render.
|
|
128
|
+
*/
|
|
129
|
+
declare function RequireAuth({ children, fallback, loadingFallback, roles, permissions, onUnauthorized, auth, }: RequireAuthProps): ReactElement;
|
|
130
|
+
/**
|
|
131
|
+
* withAuth() options: <RequireAuth> props
|
|
132
|
+
*/
|
|
133
|
+
type WithAuthOptions = Omit<RequireAuthProps, 'children'>;
|
|
134
|
+
/**
|
|
135
|
+
* Wrap a component in <RequireAuth>. The wrapper forwards its ref to the
|
|
136
|
+
* component and is named `withAuth(Name)`.
|
|
6
137
|
*/
|
|
7
|
-
declare
|
|
138
|
+
declare function withAuth<C extends ComponentType<any>>(Component: C, options?: WithAuthOptions): ForwardRefExoticComponent<ComponentPropsWithRef<C>>;
|
|
8
139
|
|
|
9
|
-
export {
|
|
140
|
+
export { AuthProvider, type AuthProviderProps, AuthState, RequireAuth, type RequireAuthProps, TokenState, type UnauthorizedReason, type UseAuthReturn, type UseTokenReturn, type UseUserReturn, type WithAuthOptions, useAuth, useAuthKeeper, useToken, useUser, withAuth };
|
package/dist/react/index.js
CHANGED
|
@@ -1,6 +1,121 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { AuthError } from '../chunk-DLCD3SBV.js';
|
|
2
|
+
import { SIGNED_OUT_STATE, NO_TOKEN_STATE, readClaim, NO_CLAIMS, createAuthSource } from '../chunk-UUQDRHGF.js';
|
|
3
|
+
import { createContext, createElement, useContext, useSyncExternalStore, useMemo, useCallback, useRef, useEffect, Fragment, forwardRef } from 'react';
|
|
3
4
|
|
|
4
|
-
|
|
5
|
+
var AuthContext = createContext(null);
|
|
6
|
+
function AuthProvider({ auth, children }) {
|
|
7
|
+
return createElement(AuthContext.Provider, { value: auth }, children);
|
|
8
|
+
}
|
|
9
|
+
function useAuthKeeper() {
|
|
10
|
+
const auth = useContext(AuthContext);
|
|
11
|
+
if (!auth) {
|
|
12
|
+
throw new AuthError("CONFIG_ERROR", "useAuthKeeper() must be used inside <AuthProvider>");
|
|
13
|
+
}
|
|
14
|
+
return auth;
|
|
15
|
+
}
|
|
16
|
+
var getServerState = () => SIGNED_OUT_STATE;
|
|
17
|
+
function useAuthInstance(auth, caller) {
|
|
18
|
+
const fromContext = useContext(AuthContext);
|
|
19
|
+
const instance = auth ?? fromContext;
|
|
20
|
+
if (!instance) {
|
|
21
|
+
throw new AuthError(
|
|
22
|
+
"CONFIG_ERROR",
|
|
23
|
+
`${caller} needs an AuthKeeper instance: pass it or render inside <AuthProvider auth={...}>`
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
return instance;
|
|
27
|
+
}
|
|
28
|
+
function useAuthSource(instance) {
|
|
29
|
+
return useMemo(() => createAuthSource(instance), [instance]);
|
|
30
|
+
}
|
|
31
|
+
function useAuth(auth) {
|
|
32
|
+
const instance = useAuthInstance(auth, "useAuth()");
|
|
33
|
+
const source = useAuthSource(instance);
|
|
34
|
+
const state = useSyncExternalStore(source.subscribe, source.getState, getServerState);
|
|
35
|
+
const actions = useMemo(
|
|
36
|
+
() => ({
|
|
37
|
+
setTokens: (tokens) => instance.setTokens(tokens),
|
|
38
|
+
logout: (options) => instance.logout(options),
|
|
39
|
+
refresh: () => instance.refresh()
|
|
40
|
+
}),
|
|
41
|
+
[instance]
|
|
42
|
+
);
|
|
43
|
+
return useMemo(() => ({ ...state, ...actions }), [state, actions]);
|
|
44
|
+
}
|
|
45
|
+
var getServerTokenState = () => NO_TOKEN_STATE;
|
|
46
|
+
var getServerUser = () => null;
|
|
47
|
+
function useToken(auth) {
|
|
48
|
+
const instance = useAuthInstance(auth, "useToken()");
|
|
49
|
+
const source = useAuthSource(instance);
|
|
50
|
+
const state = useSyncExternalStore(source.subscribe, source.getTokenState, getServerTokenState);
|
|
51
|
+
const authFetch = useMemo(() => instance.createFetch(), [instance]);
|
|
52
|
+
return useMemo(() => ({ ...state, authFetch }), [state, authFetch]);
|
|
53
|
+
}
|
|
54
|
+
function useUser(auth) {
|
|
55
|
+
const instance = useAuthInstance(auth, "useUser()");
|
|
56
|
+
const source = useAuthSource(instance);
|
|
57
|
+
const user = useSyncExternalStore(source.subscribe, () => source.getState().user, getServerUser);
|
|
58
|
+
const getClaim = useCallback(
|
|
59
|
+
(key) => readClaim(user, key),
|
|
60
|
+
[user]
|
|
61
|
+
);
|
|
62
|
+
return useMemo(() => ({ user, claims: user ?? NO_CLAIMS, getClaim }), [user, getClaim]);
|
|
63
|
+
}
|
|
64
|
+
function claimList(user, key) {
|
|
65
|
+
const value = user?.[key];
|
|
66
|
+
return Array.isArray(value) ? value : [];
|
|
67
|
+
}
|
|
68
|
+
function checkAccess(state, roles, permissions) {
|
|
69
|
+
if (!state.isAuthenticated) return "unauthenticated";
|
|
70
|
+
const userRoles = claimList(state.user, "roles");
|
|
71
|
+
const userPermissions = claimList(state.user, "permissions");
|
|
72
|
+
if (roles?.length && !roles.some((role) => userRoles.includes(role))) return "forbidden";
|
|
73
|
+
if (permissions && !permissions.every((p) => userPermissions.includes(p))) return "forbidden";
|
|
74
|
+
return "authorized";
|
|
75
|
+
}
|
|
76
|
+
var getServerAccess = () => "pending";
|
|
77
|
+
function RequireAuth({
|
|
78
|
+
children,
|
|
79
|
+
fallback = null,
|
|
80
|
+
loadingFallback = null,
|
|
81
|
+
roles,
|
|
82
|
+
permissions,
|
|
83
|
+
onUnauthorized,
|
|
84
|
+
auth
|
|
85
|
+
}) {
|
|
86
|
+
const instance = useAuthInstance(auth, "<RequireAuth>");
|
|
87
|
+
const source = useAuthSource(instance);
|
|
88
|
+
const access = useSyncExternalStore(
|
|
89
|
+
source.subscribe,
|
|
90
|
+
() => checkAccess(source.getState(), roles, permissions),
|
|
91
|
+
getServerAccess
|
|
92
|
+
);
|
|
93
|
+
const reported = useRef(null);
|
|
94
|
+
useEffect(() => {
|
|
95
|
+
if (access === "authorized" || access === "pending") {
|
|
96
|
+
reported.current = null;
|
|
97
|
+
} else if (reported.current !== access) {
|
|
98
|
+
reported.current = access;
|
|
99
|
+
onUnauthorized?.(access);
|
|
100
|
+
}
|
|
101
|
+
}, [access]);
|
|
102
|
+
const content = access === "authorized" ? children : access === "pending" ? loadingFallback : fallback;
|
|
103
|
+
return createElement(Fragment, null, content);
|
|
104
|
+
}
|
|
105
|
+
function nameOf(component) {
|
|
106
|
+
const { displayName, name, render, type } = component;
|
|
107
|
+
const inner = render ?? type;
|
|
108
|
+
return displayName || name || inner && nameOf(inner);
|
|
109
|
+
}
|
|
110
|
+
function withAuth(Component, options = {}) {
|
|
111
|
+
const Inner = Component;
|
|
112
|
+
const Wrapped = forwardRef(
|
|
113
|
+
(props, ref) => createElement(RequireAuth, options, createElement(Inner, { ...props, ref }))
|
|
114
|
+
);
|
|
115
|
+
Wrapped.displayName = `withAuth(${nameOf(Component) || "Component"})`;
|
|
116
|
+
return Wrapped;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export { AuthProvider, RequireAuth, useAuth, useAuthKeeper, useToken, useUser, withAuth };
|
|
5
120
|
//# sourceMappingURL=index.js.map
|
|
6
121
|
//# sourceMappingURL=index.js.map
|
package/dist/react/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/react/index.ts"],"names":[],"mappings":";AAQO,IAAM,6BAAA,GAAgC","file":"index.js","sourcesContent":["/**\n * React Adapter\n *\n * React hooks and components for AuthKeeper.\n * Will be implemented in Phase 7.\n */\n\n// Placeholder export to prevent build errors\nexport const __REACT_ADAPTER_PLACEHOLDER__ = true\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/react/use-auth.ts","../../src/adapters/react/use-token.ts","../../src/adapters/react/require-auth.ts"],"names":["useSyncExternalStore","useMemo","createElement"],"mappings":";;;;AAgBA,IAAM,WAAA,GAAc,cAAiC,IAAI,CAAA;AAclD,SAAS,YAAA,CAAa,EAAE,IAAA,EAAM,QAAA,EAAS,EAAoC;AAChF,EAAA,OAAO,cAAc,WAAA,CAAY,QAAA,EAAU,EAAE,KAAA,EAAO,IAAA,IAAQ,QAAQ,CAAA;AACtE;AAMO,SAAS,aAAA,GAA4B;AAC1C,EAAA,MAAM,IAAA,GAAO,WAAW,WAAW,CAAA;AACnC,EAAA,IAAI,CAAC,IAAA,EAAM;AACT,IAAA,MAAM,IAAI,SAAA,CAAU,cAAA,EAAgB,oDAAoD,CAAA;AAAA,EAC1F;AACA,EAAA,OAAO,IAAA;AACT;AAYA,IAAM,iBAAiB,MAAiB,gBAAA;AAMjC,SAAS,eAAA,CAAgB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AW,QAAA,CAAS,OAAA,KAAY,MAAA,EAAQ;AACtC,MAAA,QAAA,CAAS,OAAA,GAAU,MAAA;AACnB,MAAA,cAAA,GAAiB,MAAM,CAAA;AAAA,IACzB;AAAA,EAEF,CAAA,EAAG,CAAC,MAAM,CAAC,CAAA;AAEX,EAAA,MAAM,UACJ,MAAA,KAAW,YAAA,GAAe,QAAA,GAAW,MAAA,KAAW,YAAY,eAAA,GAAkB,QAAA;AAChF,EAAA,OAAOE,aAAAA,CAAc,QAAA,EAAU,IAAA,EAAM,OAAO,CAAA;AAC9C;AAQA,SAAS,OAAO,SAAA,EAAuC;AACrD,EAAA,MAAM,EAAE,WAAA,EAAa,IAAA,EAAM,MAAA,EAAQ,MAAK,GAAI,SAAA;AAM5C,EAAA,MAAM,QAAQ,MAAA,IAAU,IAAA;AACxB,EAAA,OAAO,WAAA,IAAe,IAAA,IAAS,KAAA,IAAS,MAAA,CAAO,KAAK,CAAA;AACtD;AAMO,SAAS,QAAA,CAId,SAAA,EACA,OAAA,GAA2B,EAAC,EACyB;AACrD,EAAA,MAAM,KAAA,GAAqB,SAAA;AAC3B,EAAA,MAAM,OAAA,GAAU,UAAA;AAAA,IAA4B,CAAC,KAAA,EAAO,GAAA,KAClDA,aAAAA,CAAc,WAAA,EAAa,OAAA,EAASA,aAAAA,CAAc,KAAA,EAAO,EAAE,GAAG,KAAA,EAAO,GAAA,EAAK,CAAC;AAAA,GAC7E;AACA,EAAA,OAAA,CAAQ,WAAA,GAAc,CAAA,SAAA,EAAY,MAAA,CAAO,SAAS,KAAK,WAAW,CAAA,CAAA,CAAA;AAClE,EAAA,OAAO,OAAA;AACT","file":"index.js","sourcesContent":["/**\n * React bindings: <AuthProvider> and useAuth()\n */\n\nimport {\n createContext,\n createElement,\n useContext,\n useMemo,\n useSyncExternalStore,\n type ReactElement,\n type ReactNode,\n} from 'react'\nimport { AuthError, type AuthKeeper, type LogoutOptions, type TokenSet } from '../../types'\nimport { createAuthSource, SIGNED_OUT_STATE, type AuthSource, type AuthState } from '../auth-source'\n\nconst AuthContext = createContext<AuthKeeper | null>(null)\n\n/**\n * <AuthProvider> props\n */\nexport interface AuthProviderProps {\n /** Instance returned by `createAuthKeeper()` */\n auth: AuthKeeper\n children?: ReactNode\n}\n\n/**\n * Make an AuthKeeper instance available to `useAuth()` / `useAuthKeeper()`\n */\nexport function AuthProvider({ auth, children }: AuthProviderProps): ReactElement {\n return createElement(AuthContext.Provider, { value: auth }, children)\n}\n\n/**\n * The AuthKeeper instance from the nearest <AuthProvider>\n * @throws {AuthError} CONFIG_ERROR outside an <AuthProvider>\n */\nexport function useAuthKeeper(): AuthKeeper {\n const auth = useContext(AuthContext)\n if (!auth) {\n throw new AuthError('CONFIG_ERROR', 'useAuthKeeper() must be used inside <AuthProvider>')\n }\n return auth\n}\n\n/**\n * useAuth() return value: the auth state plus actions\n */\nexport interface UseAuthReturn extends AuthState {\n /** Store tokens (e.g. after your login request) */\n setTokens: (tokens: TokenSet) => void\n logout: (options?: LogoutOptions) => void\n refresh: () => Promise<TokenSet>\n}\n\nconst getServerState = (): AuthState => SIGNED_OUT_STATE\n\n/**\n * The given instance, else the one from <AuthProvider>\n * @internal\n */\nexport function useAuthInstance(auth: AuthKeeper | undefined, caller: string): AuthKeeper {\n const fromContext = useContext(AuthContext)\n const instance = auth ?? fromContext\n if (!instance) {\n throw new AuthError(\n 'CONFIG_ERROR',\n `${caller} needs an AuthKeeper instance: pass it or render inside <AuthProvider auth={...}>`,\n )\n }\n return instance\n}\n\n/**\n * The snapshot source of an instance, kept for the component's lifetime\n * @internal\n */\nexport function useAuthSource(instance: AuthKeeper): AuthSource {\n return useMemo(() => createAuthSource(instance), [instance])\n}\n\n/**\n * Subscribe a component to the auth state.\n *\n * Re-renders after login, logout, refresh and error events and when the\n * access token expires. On the server and during hydration the state is\n * signed out; the client state follows right after hydration.\n *\n * @param auth - Instance to use (default: the one from <AuthProvider>)\n */\nexport function useAuth(auth?: AuthKeeper): UseAuthReturn {\n const instance = useAuthInstance(auth, 'useAuth()')\n const source = useAuthSource(instance)\n const state = useSyncExternalStore(source.subscribe, source.getState, getServerState)\n\n const actions = useMemo(\n () => ({\n setTokens: (tokens: TokenSet) => instance.setTokens(tokens),\n logout: (options?: LogoutOptions) => instance.logout(options),\n refresh: () => instance.refresh(),\n }),\n [instance],\n )\n\n return useMemo(() => ({ ...state, ...actions }), [state, actions])\n}\n","/**\n * React bindings: useToken() and useUser()\n */\n\nimport { useCallback, useMemo, useSyncExternalStore } from 'react'\nimport type { AuthFetch, AuthKeeper, TokenPayload } from '../../types'\nimport { NO_CLAIMS, NO_TOKEN_STATE, readClaim, type TokenState } from '../auth-source'\nimport { useAuthInstance, useAuthSource } from './use-auth'\n\n/**\n * useToken() return value: the token state plus an authenticated fetch\n */\nexport interface UseTokenReturn extends TokenState {\n /** `fetch` that adds the access token (and refreshes on 401): `auth.createFetch()` */\n authFetch: AuthFetch\n}\n\nconst getServerTokenState = (): TokenState => NO_TOKEN_STATE\nconst getServerUser = (): TokenPayload | null => null\n\n/**\n * Subscribe a component to the tokens.\n *\n * Re-renders only when a token or the expiry changes (login, refresh, logout,\n * expiry). On the server and during hydration there are no tokens.\n *\n * @param auth - Instance to use (default: the one from <AuthProvider>)\n */\nexport function useToken(auth?: AuthKeeper): UseTokenReturn {\n const instance = useAuthInstance(auth, 'useToken()')\n const source = useAuthSource(instance)\n const state = useSyncExternalStore(source.subscribe, source.getTokenState, getServerTokenState)\n const authFetch = useMemo(() => instance.createFetch(), [instance])\n return useMemo(() => ({ ...state, authFetch }), [state, authFetch])\n}\n\n/**\n * useUser() return value\n */\nexport interface UseUserReturn {\n /** Decoded access token payload (null when signed out or for opaque tokens) */\n user: TokenPayload | null\n /** The payload's claims (empty when there is no user) */\n claims: TokenPayload\n /** One claim of the payload */\n getClaim: <K extends keyof TokenPayload>(key: K) => TokenPayload[K] | undefined\n}\n\n/**\n * Subscribe a component to the decoded access token payload.\n *\n * Re-renders only when the access token changes. On the server and during\n * hydration there is no user.\n *\n * @param auth - Instance to use (default: the one from <AuthProvider>)\n */\nexport function useUser(auth?: AuthKeeper): UseUserReturn {\n const instance = useAuthInstance(auth, 'useUser()')\n const source = useAuthSource(instance)\n const user = useSyncExternalStore(source.subscribe, () => source.getState().user, getServerUser)\n const getClaim = useCallback(\n <K extends keyof TokenPayload>(key: K) => readClaim(user, key),\n [user],\n )\n return useMemo(() => ({ user, claims: user ?? NO_CLAIMS, getClaim }), [user, getClaim])\n}\n","/**\n * React bindings: <RequireAuth> and withAuth()\n */\n\nimport {\n createElement,\n forwardRef,\n Fragment,\n useEffect,\n useRef,\n useSyncExternalStore,\n type ComponentPropsWithRef,\n type ComponentType,\n type ElementType,\n type ForwardRefExoticComponent,\n type ReactElement,\n type ReactNode,\n} from 'react'\nimport type { AuthKeeper, TokenPayload } from '../../types'\nimport type { AuthState } from '../auth-source'\nimport { useAuthInstance, useAuthSource } from './use-auth'\n\n/**\n * Why <RequireAuth> did not render its children: signed out, or signed in\n * without the required roles / permissions\n */\nexport type UnauthorizedReason = 'unauthenticated' | 'forbidden'\n\n/** 'pending' on the server and during hydration, before the client state is known */\ntype Access = 'pending' | 'authorized' | UnauthorizedReason\n\n/**\n * <RequireAuth> props\n */\nexport interface RequireAuthProps {\n /** Rendered only while authorized */\n children?: ReactNode\n /** Rendered while signed out or not allowed (default: nothing) */\n fallback?: ReactNode\n /**\n * Rendered on the server and during hydration, before the client auth state\n * is known (default: nothing)\n */\n loadingFallback?: ReactNode\n /** The user needs at least one of these roles (`roles` claim) */\n roles?: readonly string[]\n /** The user needs every one of these permissions (`permissions` claim) */\n permissions?: readonly string[]\n /**\n * Called after rendering the fallback, once each time access is lost (e.g.\n * to redirect to a login page)\n */\n onUnauthorized?: (reason: UnauthorizedReason) => void\n /** Instance to use (default: the one from <AuthProvider>) */\n auth?: AuthKeeper\n}\n\nfunction claimList(user: TokenPayload | null, key: 'roles' | 'permissions'): readonly unknown[] {\n const value = user?.[key]\n return Array.isArray(value) ? value : []\n}\n\nfunction checkAccess(\n state: AuthState,\n roles: readonly string[] | undefined,\n permissions: readonly string[] | undefined,\n): Access {\n if (!state.isAuthenticated) return 'unauthenticated'\n const userRoles = claimList(state.user, 'roles')\n const userPermissions = claimList(state.user, 'permissions')\n if (roles?.length && !roles.some((role) => userRoles.includes(role))) return 'forbidden'\n if (permissions && !permissions.every((p) => userPermissions.includes(p))) return 'forbidden'\n return 'authorized'\n}\n\nconst getServerAccess = (): Access => 'pending'\n\n/**\n * Render `children` only while the user is signed in (and has the required\n * roles / permissions), else `fallback`.\n *\n * Re-renders only when access changes. On the server and during hydration it\n * renders `loadingFallback`, so protected content never appears before the\n * client state is known and the server markup matches the hydration render.\n */\nexport function RequireAuth({\n children,\n fallback = null,\n loadingFallback = null,\n roles,\n permissions,\n onUnauthorized,\n auth,\n}: RequireAuthProps): ReactElement {\n const instance = useAuthInstance(auth, '<RequireAuth>')\n const source = useAuthSource(instance)\n const access = useSyncExternalStore(\n source.subscribe,\n () => checkAccess(source.getState(), roles, permissions),\n getServerAccess,\n )\n\n // The reason last reported, so StrictMode's repeated effects report it once\n const reported = useRef<UnauthorizedReason | null>(null)\n useEffect(() => {\n if (access === 'authorized' || access === 'pending') {\n reported.current = null\n } else if (reported.current !== access) {\n reported.current = access\n onUnauthorized?.(access)\n }\n // A new onUnauthorized (e.g. an inline arrow) is no reason to report again\n }, [access])\n\n const content =\n access === 'authorized' ? children : access === 'pending' ? loadingFallback : fallback\n return createElement(Fragment, null, content)\n}\n\n/**\n * withAuth() options: <RequireAuth> props\n */\nexport type WithAuthOptions = Omit<RequireAuthProps, 'children'>\n\n/** A component's name; forwardRef() / memo() components are named after the inner one */\nfunction nameOf(component: object): string | undefined {\n const { displayName, name, render, type } = component as {\n displayName?: string\n name?: string\n render?: object\n type?: object\n }\n const inner = render ?? type\n return displayName || name || (inner && nameOf(inner))\n}\n\n/**\n * Wrap a component in <RequireAuth>. The wrapper forwards its ref to the\n * component and is named `withAuth(Name)`.\n */\nexport function withAuth<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- accepts any component's props\n C extends ComponentType<any>,\n>(\n Component: C,\n options: WithAuthOptions = {},\n): ForwardRefExoticComponent<ComponentPropsWithRef<C>> {\n const Inner: ElementType = Component\n const Wrapped = forwardRef<unknown, object>((props, ref) =>\n createElement(RequireAuth, options, createElement(Inner, { ...props, ref })),\n )\n Wrapped.displayName = `withAuth(${nameOf(Component) || 'Component'})`\n return Wrapped as unknown as ForwardRefExoticComponent<ComponentPropsWithRef<C>>\n}\n"]}
|
package/dist/svelte/index.cjs
CHANGED
|
@@ -1,8 +1,58 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
var __SVELTE_ADAPTER_PLACEHOLDER__ = true;
|
|
3
|
+
var chunkLGZGECYE_cjs = require('../chunk-LGZGECYE.cjs');
|
|
5
4
|
|
|
6
|
-
|
|
5
|
+
// src/adapters/svelte/auth-store.ts
|
|
6
|
+
function readable(source, read) {
|
|
7
|
+
const subscribers = /* @__PURE__ */ new Set();
|
|
8
|
+
let stop = null;
|
|
9
|
+
let value = read(source);
|
|
10
|
+
return function subscribe(run) {
|
|
11
|
+
const entry = { run };
|
|
12
|
+
if (subscribers.size === 0) {
|
|
13
|
+
value = read(source);
|
|
14
|
+
stop = source.subscribe(() => {
|
|
15
|
+
const next = read(source);
|
|
16
|
+
if (next === value) return;
|
|
17
|
+
value = next;
|
|
18
|
+
Array.from(subscribers).forEach((subscriber) => subscriber.run(value));
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
subscribers.add(entry);
|
|
22
|
+
run(value);
|
|
23
|
+
return () => {
|
|
24
|
+
if (!subscribers.delete(entry)) return;
|
|
25
|
+
if (subscribers.size === 0 && stop) {
|
|
26
|
+
stop();
|
|
27
|
+
stop = null;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function createAuthStore(auth) {
|
|
33
|
+
return {
|
|
34
|
+
subscribe: readable(chunkLGZGECYE_cjs.createAuthSource(auth), (source) => source.getState()),
|
|
35
|
+
setTokens: (tokens) => auth.setTokens(tokens),
|
|
36
|
+
logout: (options) => auth.logout(options),
|
|
37
|
+
refresh: () => auth.refresh()
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function createTokenStore(auth) {
|
|
41
|
+
return {
|
|
42
|
+
subscribe: readable(chunkLGZGECYE_cjs.createAuthSource(auth), (source) => source.getTokenState()),
|
|
43
|
+
authFetch: auth.createFetch()
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function createUserStore(auth) {
|
|
47
|
+
const source = chunkLGZGECYE_cjs.createAuthSource(auth);
|
|
48
|
+
return {
|
|
49
|
+
subscribe: readable(source, () => source.getState().user),
|
|
50
|
+
getClaim: (key) => chunkLGZGECYE_cjs.readClaim(source.getState().user, key)
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
exports.createAuthStore = createAuthStore;
|
|
55
|
+
exports.createTokenStore = createTokenStore;
|
|
56
|
+
exports.createUserStore = createUserStore;
|
|
7
57
|
//# sourceMappingURL=index.cjs.map
|
|
8
58
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/adapters/svelte/
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/svelte/auth-store.ts"],"names":["createAuthSource","readClaim"],"mappings":";;;;;AAsDA,SAAS,QAAA,CACP,QACA,IAAA,EAC0B;AAC1B,EAAA,MAAM,WAAA,uBAAkB,GAAA,EAAiC;AACzD,EAAA,IAAI,IAAA,GAA4B,IAAA;AAChC,EAAA,IAAI,KAAA,GAAQ,KAAK,MAAM,CAAA;AAEvB,EAAA,OAAO,SAAS,UAAU,GAAA,EAAqC;AAC7D,IAAA,MAAM,KAAA,GAAQ,EAAE,GAAA,EAAI;AACpB,IAAA,IAAI,WAAA,CAAY,SAAS,CAAA,EAAG;AAC1B,MA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E,SAAA,EAAW,KAAK,WAAA;AAAY,GAC9B;AACF;AAOO,SAAS,gBAAgB,IAAA,EAA6B;AAC3D,EAAA,MAAM,MAAA,GAASA,mCAAiB,IAAI,CAAA;AACpC,EAAA,OAAO;AAAA,IACL,WAAW,QAAA,CAAS,MAAA,EAAQ,MAAM,MAAA,CAAO,QAAA,GAAW,IAAI,CAAA;AAAA,IACxD,QAAA,EAAU,CAAC,GAAA,KAAQC,2BAAA,CAAU,OAAO,QAAA,EAAS,CAAE,MAAM,GAAG;AAAA,GAC1D;AACF","file":"index.cjs","sourcesContent":["/**\n * Svelte bindings: readable auth, token and user stores\n *\n * Implements the Svelte store contract directly (no runtime import of\n * `svelte`), so it works with Svelte 3, 4 and 5 (`$auth` in components).\n */\n\nimport type { AuthFetch, AuthKeeper, LogoutOptions, TokenPayload, TokenSet } from '../../types'\nimport {\n createAuthSource,\n readClaim,\n type AuthSource,\n type AuthState,\n type TokenState,\n} from '../auth-source'\n\n/**\n * Svelte readable store contract\n */\nexport interface Readable<T> {\n /** `run` is called now and on every change; returns the unsubscribe function */\n subscribe(run: (value: T) => void, invalidate?: () => void): () => void\n}\n\n/**\n * Readable store of the auth state, plus actions\n */\nexport interface AuthStore extends Readable<AuthState> {\n setTokens: (tokens: TokenSet) => void\n logout: (options?: LogoutOptions) => void\n refresh: () => Promise<TokenSet>\n}\n\n/**\n * Readable store of the tokens, plus an authenticated fetch\n */\nexport interface TokenStore extends Readable<TokenState> {\n /** `fetch` that adds the access token (and refreshes on 401): `auth.createFetch()` */\n authFetch: AuthFetch\n}\n\n/**\n * Readable store of the decoded access token payload (null when signed out or\n * for opaque tokens)\n */\nexport interface UserStore extends Readable<TokenPayload | null> {\n /** One claim of the current payload */\n getClaim: <K extends keyof TokenPayload>(key: K) => TokenPayload[K] | undefined\n}\n\n/**\n * Store of `read(source)` that listens to the instance only while it has\n * subscribers and notifies them only when the snapshot changes\n */\nfunction readable<T>(\n source: AuthSource,\n read: (source: AuthSource) => T,\n): Readable<T>['subscribe'] {\n const subscribers = new Set<{ run: (value: T) => void }>()\n let stop: (() => void) | null = null\n let value = read(source)\n\n return function subscribe(run: (value: T) => void): () => void {\n const entry = { run }\n if (subscribers.size === 0) {\n value = read(source)\n stop = source.subscribe(() => {\n const next = read(source)\n if (next === value) return\n value = next\n Array.from(subscribers).forEach((subscriber) => subscriber.run(value))\n })\n }\n subscribers.add(entry)\n run(value)\n return () => {\n if (!subscribers.delete(entry)) return\n if (subscribers.size === 0 && stop) {\n stop()\n stop = null\n }\n }\n }\n}\n\n/**\n * Create a readable store of the auth state for an AuthKeeper instance. It\n * listens to the instance only while it has subscribers.\n */\nexport function createAuthStore(auth: AuthKeeper): AuthStore {\n return {\n subscribe: readable(createAuthSource(auth), (source) => source.getState()),\n setTokens: (tokens) => auth.setTokens(tokens),\n logout: (options) => auth.logout(options),\n refresh: () => auth.refresh(),\n }\n}\n\n/**\n * Create a readable store of the tokens. It updates when a token or the expiry\n * changes and listens to the instance only while it has subscribers.\n */\nexport function createTokenStore(auth: AuthKeeper): TokenStore {\n return {\n subscribe: readable(createAuthSource(auth), (source) => source.getTokenState()),\n authFetch: auth.createFetch(),\n }\n}\n\n/**\n * Create a readable store of the decoded access token payload. It updates when\n * the access token changes and listens to the instance only while it has\n * subscribers.\n */\nexport function createUserStore(auth: AuthKeeper): UserStore {\n const source = createAuthSource(auth)\n return {\n subscribe: readable(source, () => source.getState().user),\n getClaim: (key) => readClaim(source.getState().user, key),\n }\n}\n"]}
|
package/dist/svelte/index.d.cts
CHANGED
|
@@ -1,9 +1,58 @@
|
|
|
1
|
+
import { T as TokenSet, L as LogoutOptions, A as AuthFetch, a as TokenPayload, b as AuthKeeper } from '../types-DMPBl-Ym.cjs';
|
|
2
|
+
import { A as AuthState, T as TokenState } from '../auth-source-rjMWiP1Q.cjs';
|
|
3
|
+
|
|
1
4
|
/**
|
|
2
|
-
* Svelte
|
|
5
|
+
* Svelte bindings: readable auth, token and user stores
|
|
3
6
|
*
|
|
4
|
-
* Svelte
|
|
5
|
-
*
|
|
7
|
+
* Implements the Svelte store contract directly (no runtime import of
|
|
8
|
+
* `svelte`), so it works with Svelte 3, 4 and 5 (`$auth` in components).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Svelte readable store contract
|
|
13
|
+
*/
|
|
14
|
+
interface Readable<T> {
|
|
15
|
+
/** `run` is called now and on every change; returns the unsubscribe function */
|
|
16
|
+
subscribe(run: (value: T) => void, invalidate?: () => void): () => void;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Readable store of the auth state, plus actions
|
|
20
|
+
*/
|
|
21
|
+
interface AuthStore extends Readable<AuthState> {
|
|
22
|
+
setTokens: (tokens: TokenSet) => void;
|
|
23
|
+
logout: (options?: LogoutOptions) => void;
|
|
24
|
+
refresh: () => Promise<TokenSet>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Readable store of the tokens, plus an authenticated fetch
|
|
28
|
+
*/
|
|
29
|
+
interface TokenStore extends Readable<TokenState> {
|
|
30
|
+
/** `fetch` that adds the access token (and refreshes on 401): `auth.createFetch()` */
|
|
31
|
+
authFetch: AuthFetch;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Readable store of the decoded access token payload (null when signed out or
|
|
35
|
+
* for opaque tokens)
|
|
36
|
+
*/
|
|
37
|
+
interface UserStore extends Readable<TokenPayload | null> {
|
|
38
|
+
/** One claim of the current payload */
|
|
39
|
+
getClaim: <K extends keyof TokenPayload>(key: K) => TokenPayload[K] | undefined;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Create a readable store of the auth state for an AuthKeeper instance. It
|
|
43
|
+
* listens to the instance only while it has subscribers.
|
|
44
|
+
*/
|
|
45
|
+
declare function createAuthStore(auth: AuthKeeper): AuthStore;
|
|
46
|
+
/**
|
|
47
|
+
* Create a readable store of the tokens. It updates when a token or the expiry
|
|
48
|
+
* changes and listens to the instance only while it has subscribers.
|
|
49
|
+
*/
|
|
50
|
+
declare function createTokenStore(auth: AuthKeeper): TokenStore;
|
|
51
|
+
/**
|
|
52
|
+
* Create a readable store of the decoded access token payload. It updates when
|
|
53
|
+
* the access token changes and listens to the instance only while it has
|
|
54
|
+
* subscribers.
|
|
6
55
|
*/
|
|
7
|
-
declare
|
|
56
|
+
declare function createUserStore(auth: AuthKeeper): UserStore;
|
|
8
57
|
|
|
9
|
-
export {
|
|
58
|
+
export { AuthState, type AuthStore, type Readable, TokenState, type TokenStore, type UserStore, createAuthStore, createTokenStore, createUserStore };
|
package/dist/svelte/index.d.ts
CHANGED
|
@@ -1,9 +1,58 @@
|
|
|
1
|
+
import { T as TokenSet, L as LogoutOptions, A as AuthFetch, a as TokenPayload, b as AuthKeeper } from '../types-DMPBl-Ym.js';
|
|
2
|
+
import { A as AuthState, T as TokenState } from '../auth-source-CXqrhLDO.js';
|
|
3
|
+
|
|
1
4
|
/**
|
|
2
|
-
* Svelte
|
|
5
|
+
* Svelte bindings: readable auth, token and user stores
|
|
3
6
|
*
|
|
4
|
-
* Svelte
|
|
5
|
-
*
|
|
7
|
+
* Implements the Svelte store contract directly (no runtime import of
|
|
8
|
+
* `svelte`), so it works with Svelte 3, 4 and 5 (`$auth` in components).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Svelte readable store contract
|
|
13
|
+
*/
|
|
14
|
+
interface Readable<T> {
|
|
15
|
+
/** `run` is called now and on every change; returns the unsubscribe function */
|
|
16
|
+
subscribe(run: (value: T) => void, invalidate?: () => void): () => void;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Readable store of the auth state, plus actions
|
|
20
|
+
*/
|
|
21
|
+
interface AuthStore extends Readable<AuthState> {
|
|
22
|
+
setTokens: (tokens: TokenSet) => void;
|
|
23
|
+
logout: (options?: LogoutOptions) => void;
|
|
24
|
+
refresh: () => Promise<TokenSet>;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Readable store of the tokens, plus an authenticated fetch
|
|
28
|
+
*/
|
|
29
|
+
interface TokenStore extends Readable<TokenState> {
|
|
30
|
+
/** `fetch` that adds the access token (and refreshes on 401): `auth.createFetch()` */
|
|
31
|
+
authFetch: AuthFetch;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Readable store of the decoded access token payload (null when signed out or
|
|
35
|
+
* for opaque tokens)
|
|
36
|
+
*/
|
|
37
|
+
interface UserStore extends Readable<TokenPayload | null> {
|
|
38
|
+
/** One claim of the current payload */
|
|
39
|
+
getClaim: <K extends keyof TokenPayload>(key: K) => TokenPayload[K] | undefined;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Create a readable store of the auth state for an AuthKeeper instance. It
|
|
43
|
+
* listens to the instance only while it has subscribers.
|
|
44
|
+
*/
|
|
45
|
+
declare function createAuthStore(auth: AuthKeeper): AuthStore;
|
|
46
|
+
/**
|
|
47
|
+
* Create a readable store of the tokens. It updates when a token or the expiry
|
|
48
|
+
* changes and listens to the instance only while it has subscribers.
|
|
49
|
+
*/
|
|
50
|
+
declare function createTokenStore(auth: AuthKeeper): TokenStore;
|
|
51
|
+
/**
|
|
52
|
+
* Create a readable store of the decoded access token payload. It updates when
|
|
53
|
+
* the access token changes and listens to the instance only while it has
|
|
54
|
+
* subscribers.
|
|
6
55
|
*/
|
|
7
|
-
declare
|
|
56
|
+
declare function createUserStore(auth: AuthKeeper): UserStore;
|
|
8
57
|
|
|
9
|
-
export {
|
|
58
|
+
export { AuthState, type AuthStore, type Readable, TokenState, type TokenStore, type UserStore, createAuthStore, createTokenStore, createUserStore };
|