@oxog/authkeeper 1.4.0 → 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.
Files changed (55) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +72 -0
  3. package/dist/{auth-source-BaZ_-Fu7.d.cts → auth-source-CXqrhLDO.d.ts} +15 -2
  4. package/dist/{auth-source-Cm0R6C6I.d.ts → auth-source-rjMWiP1Q.d.cts} +15 -2
  5. package/dist/{chunk-EXV2RG6T.cjs → chunk-47JWRVTL.cjs} +21 -16
  6. package/dist/chunk-47JWRVTL.cjs.map +1 -0
  7. package/dist/{chunk-KE7V52DI.js → chunk-ANGR5HRJ.js} +11 -6
  8. package/dist/chunk-ANGR5HRJ.js.map +1 -0
  9. package/dist/{chunk-CYCWWUCJ.js → chunk-DLCD3SBV.js} +2 -2
  10. package/dist/chunk-DLCD3SBV.js.map +1 -0
  11. package/dist/{chunk-KLT44YR2.cjs → chunk-LGZGECYE.cjs} +35 -8
  12. package/dist/chunk-LGZGECYE.cjs.map +1 -0
  13. package/dist/{chunk-SUGFPZ6O.js → chunk-UUQDRHGF.js} +33 -9
  14. package/dist/chunk-UUQDRHGF.js.map +1 -0
  15. package/dist/{chunk-62XK5QLP.cjs → chunk-XGKVBZSF.cjs} +2 -2
  16. package/dist/chunk-XGKVBZSF.cjs.map +1 -0
  17. package/dist/{index-CuvfPscu.d.cts → index-C4pGS-TI.d.cts} +1 -1
  18. package/dist/{index-BF4j_buH.d.ts → index-CQwGO-Wk.d.ts} +1 -1
  19. package/dist/index.cjs +51 -55
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +3 -3
  22. package/dist/index.d.ts +3 -3
  23. package/dist/index.js +7 -11
  24. package/dist/index.js.map +1 -1
  25. package/dist/plugins/index.cjs +15 -15
  26. package/dist/plugins/index.d.cts +2 -2
  27. package/dist/plugins/index.d.ts +2 -2
  28. package/dist/plugins/index.js +2 -2
  29. package/dist/react/index.cjs +92 -8
  30. package/dist/react/index.cjs.map +1 -1
  31. package/dist/react/index.d.cts +98 -4
  32. package/dist/react/index.d.ts +98 -4
  33. package/dist/react/index.js +87 -7
  34. package/dist/react/index.js.map +1 -1
  35. package/dist/svelte/index.cjs +25 -9
  36. package/dist/svelte/index.cjs.map +1 -1
  37. package/dist/svelte/index.d.cts +40 -9
  38. package/dist/svelte/index.d.ts +40 -9
  39. package/dist/svelte/index.js +24 -10
  40. package/dist/svelte/index.js.map +1 -1
  41. package/dist/{types-Bmo8S8O4.d.cts → types-DMPBl-Ym.d.cts} +1 -1
  42. package/dist/{types-Bmo8S8O4.d.ts → types-DMPBl-Ym.d.ts} +1 -1
  43. package/dist/vue/index.cjs +36 -7
  44. package/dist/vue/index.cjs.map +1 -1
  45. package/dist/vue/index.d.cts +51 -3
  46. package/dist/vue/index.d.ts +51 -3
  47. package/dist/vue/index.js +35 -8
  48. package/dist/vue/index.js.map +1 -1
  49. package/package.json +5 -4
  50. package/dist/chunk-62XK5QLP.cjs.map +0 -1
  51. package/dist/chunk-CYCWWUCJ.js.map +0 -1
  52. package/dist/chunk-EXV2RG6T.cjs.map +0 -1
  53. package/dist/chunk-KE7V52DI.js.map +0 -1
  54. package/dist/chunk-KLT44YR2.cjs.map +0 -1
  55. package/dist/chunk-SUGFPZ6O.js.map +0 -1
@@ -1,6 +1,6 @@
1
- import { ReactNode, ReactElement } from 'react';
2
- import { A as AuthKeeper, T as TokenSet, L as LogoutOptions } from '../types-Bmo8S8O4.js';
3
- import { A as AuthState } from '../auth-source-Cm0R6C6I.js';
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
4
 
5
5
  /**
6
6
  * React bindings: <AuthProvider> and useAuth()
@@ -43,4 +43,98 @@ interface UseAuthReturn extends AuthState {
43
43
  */
44
44
  declare function useAuth(auth?: AuthKeeper): UseAuthReturn;
45
45
 
46
- export { AuthProvider, type AuthProviderProps, AuthState, type UseAuthReturn, useAuth, useAuthKeeper };
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
+ }
57
+ /**
58
+ * Subscribe a component to the tokens.
59
+ *
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)`.
137
+ */
138
+ declare function withAuth<C extends ComponentType<any>>(Component: C, options?: WithAuthOptions): ForwardRefExoticComponent<ComponentPropsWithRef<C>>;
139
+
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 };
@@ -1,6 +1,6 @@
1
- import { AuthError } from '../chunk-CYCWWUCJ.js';
2
- import { createAuthSource, SIGNED_OUT_STATE } from '../chunk-SUGFPZ6O.js';
3
- import { createContext, createElement, useContext, useMemo, useSyncExternalStore } from 'react';
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';
4
4
 
5
5
  var AuthContext = createContext(null);
6
6
  function AuthProvider({ auth, children }) {
@@ -14,16 +14,23 @@ function useAuthKeeper() {
14
14
  return auth;
15
15
  }
16
16
  var getServerState = () => SIGNED_OUT_STATE;
17
- function useAuth(auth) {
17
+ function useAuthInstance(auth, caller) {
18
18
  const fromContext = useContext(AuthContext);
19
19
  const instance = auth ?? fromContext;
20
20
  if (!instance) {
21
21
  throw new AuthError(
22
22
  "CONFIG_ERROR",
23
- "useAuth() needs an AuthKeeper instance: pass it or render inside <AuthProvider auth={...}>"
23
+ `${caller} needs an AuthKeeper instance: pass it or render inside <AuthProvider auth={...}>`
24
24
  );
25
25
  }
26
- const source = useMemo(() => createAuthSource(instance), [instance]);
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);
27
34
  const state = useSyncExternalStore(source.subscribe, source.getState, getServerState);
28
35
  const actions = useMemo(
29
36
  () => ({
@@ -35,7 +42,80 @@ function useAuth(auth) {
35
42
  );
36
43
  return useMemo(() => ({ ...state, ...actions }), [state, actions]);
37
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
+ }
38
118
 
39
- export { AuthProvider, useAuth, useAuthKeeper };
119
+ export { AuthProvider, RequireAuth, useAuth, useAuthKeeper, useToken, useUser, withAuth };
40
120
  //# sourceMappingURL=index.js.map
41
121
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/adapters/react/use-auth.ts"],"names":[],"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;AAWjC,SAAS,QAAQ,IAAA,EAAkC;AACxD,EAAA,MAAM,WAAA,GAAc,WAAW,WAAW,CAAA;AAC1C,EAAA,MAAM,WAAW,IAAA,IAAQ,WAAA;AACzB,EAAA,IAAI,CAAC,QAAA,EAAU;AACb,IAAA,MAAM,IAAI,SAAA;AAAA,MACR,cAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AAEA,EAAA,MAAM,MAAA,GAAS,QAAQ,MAAM,gBAAA,CAAiB,QAAQ,CAAA,EAAG,CAAC,QAAQ,CAAC,CAAA;AACnE,EAAA,MAAM,QAAQ,oBAAA,CAAqB,MAAA,CAAO,SAAA,EAAW,MAAA,CAAO,UAAU,cAAc,CAAA;AAEpF,EAAA,MAAM,OAAA,GAAU,OAAA;AAAA,IACd,OAAO;AAAA,MACL,SAAA,EAAW,CAAC,MAAA,KAAqB,QAAA,CAAS,UAAU,MAAM,CAAA;AAAA,MAC1D,MAAA,EAAQ,CAAC,OAAA,KAA4B,QAAA,CAAS,OAAO,OAAO,CAAA;AAAA,MAC5D,OAAA,EAAS,MAAM,QAAA,CAAS,OAAA;AAAQ,KAClC,CAAA;AAAA,IACA,CAAC,QAAQ;AAAA,GACX;AAEA,EAAA,OAAO,OAAA,CAAQ,OAAO,EAAE,GAAG,KAAA,EAAO,GAAG,OAAA,EAAQ,CAAA,EAAI,CAAC,KAAA,EAAO,OAAO,CAAC,CAAA;AACnE","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 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 * 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 fromContext = useContext(AuthContext)\n const instance = auth ?? fromContext\n if (!instance) {\n throw new AuthError(\n 'CONFIG_ERROR',\n 'useAuth() needs an AuthKeeper instance: pass it or render inside <AuthProvider auth={...}>'\n )\n }\n\n const source = useMemo(() => createAuthSource(instance), [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"]}
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,MAA8B,MAAA,EAA4B;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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"]}
@@ -1,19 +1,18 @@
1
1
  'use strict';
2
2
 
3
- var chunkKLT44YR2_cjs = require('../chunk-KLT44YR2.cjs');
3
+ var chunkLGZGECYE_cjs = require('../chunk-LGZGECYE.cjs');
4
4
 
5
5
  // src/adapters/svelte/auth-store.ts
6
- function createAuthStore(auth) {
7
- const source = chunkKLT44YR2_cjs.createAuthSource(auth);
6
+ function readable(source, read) {
8
7
  const subscribers = /* @__PURE__ */ new Set();
9
8
  let stop = null;
10
- let value = source.getState();
11
- function subscribe(run) {
9
+ let value = read(source);
10
+ return function subscribe(run) {
12
11
  const entry = { run };
13
12
  if (subscribers.size === 0) {
14
- value = source.getState();
13
+ value = read(source);
15
14
  stop = source.subscribe(() => {
16
- const next = source.getState();
15
+ const next = read(source);
17
16
  if (next === value) return;
18
17
  value = next;
19
18
  Array.from(subscribers).forEach((subscriber) => subscriber.run(value));
@@ -28,15 +27,32 @@ function createAuthStore(auth) {
28
27
  stop = null;
29
28
  }
30
29
  };
31
- }
30
+ };
31
+ }
32
+ function createAuthStore(auth) {
32
33
  return {
33
- subscribe,
34
+ subscribe: readable(chunkLGZGECYE_cjs.createAuthSource(auth), (source) => source.getState()),
34
35
  setTokens: (tokens) => auth.setTokens(tokens),
35
36
  logout: (options) => auth.logout(options),
36
37
  refresh: () => auth.refresh()
37
38
  };
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
+ }
39
53
 
40
54
  exports.createAuthStore = createAuthStore;
55
+ exports.createTokenStore = createTokenStore;
56
+ exports.createUserStore = createUserStore;
41
57
  //# sourceMappingURL=index.cjs.map
42
58
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/adapters/svelte/auth-store.ts"],"names":["createAuthSource"],"mappings":";;;;;AAyBO,SAAS,gBAAgB,IAAA,EAA6B;AAC3D,EAAA,MAAM,MAAA,GAASA,mCAAiB,IAAI,CAAA;AACpC,EAAA,MAAM,WAAA,uBAAkB,GAAA,EAAyC;AACjE,EAAA,IAAI,IAAA,GAA4B,IAAA;AAChC,EAAA,IAAI,KAAA,GAAQ,OAAO,QAAA,EAAS;AAE5B,EAAA,SAAS,UAAU,GAAA,EAA6C;AAC9D,IAAA,MAAM,KAAA,GAAQ,EAAE,GAAA,EAAI;AACpB,IAAA,IAAI,WAAA,CAAY,SAAS,CAAA,EAAG;AAC1B,MAAA,KAAA,GAAQ,OAAO,QAAA,EAAS;AACxB,MAAA,IAAA,GAAO,MAAA,CAAO,UAAU,MAAM;AAC5B,QAAA,MAAM,IAAA,GAAO,OAAO,QAAA,EAAS;AAC7B,QAAA,IAAI,SAAS,KAAA,EAAO;AACpB,QAAA,KAAA,GAAQ,IAAA;AACR,QAAA,KAAA,CAAM,IAAA,CAAK,WAAW,CAAA,CAAE,OAAA,CAAQ,CAAC,UAAA,KAAe,UAAA,CAAW,GAAA,CAAI,KAAK,CAAC,CAAA;AAAA,MACvE,CAAC,CAAA;AAAA,IACH;AACA,IAAA,WAAA,CAAY,IAAI,KAAK,CAAA;AACrB,IAAA,GAAA,CAAI,KAAK,CAAA;AACT,IAAA,OAAO,MAAM;AACX,MAAA,IAAI,CAAC,WAAA,CAAY,MAAA,CAAO,KAAK,CAAA,EAAG;AAChC,MAAA,IAAI,WAAA,CAAY,IAAA,KAAS,CAAA,IAAK,IAAA,EAAM;AAClC,QAAA,IAAA,EAAK;AACL,QAAA,IAAA,GAAO,IAAA;AAAA,MACT;AAAA,IACF,CAAA;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,SAAA;AAAA,IACA,SAAA,EAAW,CAAC,MAAA,KAAW,IAAA,CAAK,UAAU,MAAM,CAAA;AAAA,IAC5C,MAAA,EAAQ,CAAC,OAAA,KAAY,IAAA,CAAK,OAAO,OAAO,CAAA;AAAA,IACxC,OAAA,EAAS,MAAM,IAAA,CAAK,OAAA;AAAQ,GAC9B;AACF","file":"index.cjs","sourcesContent":["/**\n * Svelte bindings: a readable auth store\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 { AuthKeeper, LogoutOptions, TokenSet } from '../../types'\nimport { createAuthSource, type AuthState } from '../auth-source'\n\n/**\n * Readable store of the auth state, plus actions\n */\nexport interface AuthStore {\n /** Svelte store contract: `run` is called now and on every change */\n subscribe(run: (value: AuthState) => void, invalidate?: () => void): () => void\n setTokens: (tokens: TokenSet) => void\n logout: (options?: LogoutOptions) => void\n refresh: () => Promise<TokenSet>\n}\n\n/**\n * Create a readable store for an AuthKeeper instance. It listens to the\n * instance only while it has subscribers.\n */\nexport function createAuthStore(auth: AuthKeeper): AuthStore {\n const source = createAuthSource(auth)\n const subscribers = new Set<{ run: (value: AuthState) => void }>()\n let stop: (() => void) | null = null\n let value = source.getState()\n\n function subscribe(run: (value: AuthState) => void): () => void {\n const entry = { run }\n if (subscribers.size === 0) {\n value = source.getState()\n stop = source.subscribe(() => {\n const next = source.getState()\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 return {\n subscribe,\n setTokens: (tokens) => auth.setTokens(tokens),\n logout: (options) => auth.logout(options),\n refresh: () => auth.refresh(),\n }\n}\n"]}
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,MAAA,KAAA,GAAQ,KAAK,MAAM,CAAA;AACnB,MAAA,IAAA,GAAO,MAAA,CAAO,UAAU,MAAM;AAC5B,QAAA,MAAM,IAAA,GAAO,KAAK,MAAM,CAAA;AACxB,QAAA,IAAI,SAAS,KAAA,EAAO;AACpB,QAAA,KAAA,GAAQ,IAAA;AACR,QAAA,KAAA,CAAM,IAAA,CAAK,WAAW,CAAA,CAAE,OAAA,CAAQ,CAAC,UAAA,KAAe,UAAA,CAAW,GAAA,CAAI,KAAK,CAAC,CAAA;AAAA,MACvE,CAAC,CAAA;AAAA,IACH;AACA,IAAA,WAAA,CAAY,IAAI,KAAK,CAAA;AACrB,IAAA,GAAA,CAAI,KAAK,CAAA;AACT,IAAA,OAAO,MAAM;AACX,MAAA,IAAI,CAAC,WAAA,CAAY,MAAA,CAAO,KAAK,CAAA,EAAG;AAChC,MAAA,IAAI,WAAA,CAAY,IAAA,KAAS,CAAA,IAAK,IAAA,EAAM;AAClC,QAAA,IAAA,EAAK;AACL,QAAA,IAAA,GAAO,IAAA;AAAA,MACT;AAAA,IACF,CAAA;AAAA,EACF,CAAA;AACF;AAMO,SAAS,gBAAgB,IAAA,EAA6B;AAC3D,EAAA,OAAO;AAAA,IACL,SAAA,EAAW,SAASA,kCAAA,CAAiB,IAAI,GAAG,CAAC,MAAA,KAAW,MAAA,CAAO,QAAA,EAAU,CAAA;AAAA,IACzE,SAAA,EAAW,CAAC,MAAA,KAAW,IAAA,CAAK,UAAU,MAAM,CAAA;AAAA,IAC5C,MAAA,EAAQ,CAAC,OAAA,KAAY,IAAA,CAAK,OAAO,OAAO,CAAA;AAAA,IACxC,OAAA,EAAS,MAAM,IAAA,CAAK,OAAA;AAAQ,GAC9B;AACF;AAMO,SAAS,iBAAiB,IAAA,EAA8B;AAC7D,EAAA,OAAO;AAAA,IACL,SAAA,EAAW,SAASA,kCAAA,CAAiB,IAAI,GAAG,CAAC,MAAA,KAAW,MAAA,CAAO,aAAA,EAAe,CAAA;AAAA,IAC9E,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"]}
@@ -1,27 +1,58 @@
1
- import { T as TokenSet, L as LogoutOptions, A as AuthKeeper } from '../types-Bmo8S8O4.cjs';
2
- import { A as AuthState } from '../auth-source-BaZ_-Fu7.cjs';
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
3
 
4
4
  /**
5
- * Svelte bindings: a readable auth store
5
+ * Svelte bindings: readable auth, token and user stores
6
6
  *
7
7
  * Implements the Svelte store contract directly (no runtime import of
8
8
  * `svelte`), so it works with Svelte 3, 4 and 5 (`$auth` in components).
9
9
  */
10
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
+ }
11
18
  /**
12
19
  * Readable store of the auth state, plus actions
13
20
  */
14
- interface AuthStore {
15
- /** Svelte store contract: `run` is called now and on every change */
16
- subscribe(run: (value: AuthState) => void, invalidate?: () => void): () => void;
21
+ interface AuthStore extends Readable<AuthState> {
17
22
  setTokens: (tokens: TokenSet) => void;
18
23
  logout: (options?: LogoutOptions) => void;
19
24
  refresh: () => Promise<TokenSet>;
20
25
  }
21
26
  /**
22
- * Create a readable store for an AuthKeeper instance. It listens to the
23
- * instance only while it has subscribers.
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.
24
44
  */
25
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.
55
+ */
56
+ declare function createUserStore(auth: AuthKeeper): UserStore;
26
57
 
27
- export { AuthState, type AuthStore, createAuthStore };
58
+ export { AuthState, type AuthStore, type Readable, TokenState, type TokenStore, type UserStore, createAuthStore, createTokenStore, createUserStore };
@@ -1,27 +1,58 @@
1
- import { T as TokenSet, L as LogoutOptions, A as AuthKeeper } from '../types-Bmo8S8O4.js';
2
- import { A as AuthState } from '../auth-source-Cm0R6C6I.js';
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
3
 
4
4
  /**
5
- * Svelte bindings: a readable auth store
5
+ * Svelte bindings: readable auth, token and user stores
6
6
  *
7
7
  * Implements the Svelte store contract directly (no runtime import of
8
8
  * `svelte`), so it works with Svelte 3, 4 and 5 (`$auth` in components).
9
9
  */
10
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
+ }
11
18
  /**
12
19
  * Readable store of the auth state, plus actions
13
20
  */
14
- interface AuthStore {
15
- /** Svelte store contract: `run` is called now and on every change */
16
- subscribe(run: (value: AuthState) => void, invalidate?: () => void): () => void;
21
+ interface AuthStore extends Readable<AuthState> {
17
22
  setTokens: (tokens: TokenSet) => void;
18
23
  logout: (options?: LogoutOptions) => void;
19
24
  refresh: () => Promise<TokenSet>;
20
25
  }
21
26
  /**
22
- * Create a readable store for an AuthKeeper instance. It listens to the
23
- * instance only while it has subscribers.
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.
24
44
  */
25
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.
55
+ */
56
+ declare function createUserStore(auth: AuthKeeper): UserStore;
26
57
 
27
- export { AuthState, type AuthStore, createAuthStore };
58
+ export { AuthState, type AuthStore, type Readable, TokenState, type TokenStore, type UserStore, createAuthStore, createTokenStore, createUserStore };
@@ -1,17 +1,16 @@
1
- import { createAuthSource } from '../chunk-SUGFPZ6O.js';
1
+ import { createAuthSource, readClaim } from '../chunk-UUQDRHGF.js';
2
2
 
3
3
  // src/adapters/svelte/auth-store.ts
4
- function createAuthStore(auth) {
5
- const source = createAuthSource(auth);
4
+ function readable(source, read) {
6
5
  const subscribers = /* @__PURE__ */ new Set();
7
6
  let stop = null;
8
- let value = source.getState();
9
- function subscribe(run) {
7
+ let value = read(source);
8
+ return function subscribe(run) {
10
9
  const entry = { run };
11
10
  if (subscribers.size === 0) {
12
- value = source.getState();
11
+ value = read(source);
13
12
  stop = source.subscribe(() => {
14
- const next = source.getState();
13
+ const next = read(source);
15
14
  if (next === value) return;
16
15
  value = next;
17
16
  Array.from(subscribers).forEach((subscriber) => subscriber.run(value));
@@ -26,15 +25,30 @@ function createAuthStore(auth) {
26
25
  stop = null;
27
26
  }
28
27
  };
29
- }
28
+ };
29
+ }
30
+ function createAuthStore(auth) {
30
31
  return {
31
- subscribe,
32
+ subscribe: readable(createAuthSource(auth), (source) => source.getState()),
32
33
  setTokens: (tokens) => auth.setTokens(tokens),
33
34
  logout: (options) => auth.logout(options),
34
35
  refresh: () => auth.refresh()
35
36
  };
36
37
  }
38
+ function createTokenStore(auth) {
39
+ return {
40
+ subscribe: readable(createAuthSource(auth), (source) => source.getTokenState()),
41
+ authFetch: auth.createFetch()
42
+ };
43
+ }
44
+ function createUserStore(auth) {
45
+ const source = createAuthSource(auth);
46
+ return {
47
+ subscribe: readable(source, () => source.getState().user),
48
+ getClaim: (key) => readClaim(source.getState().user, key)
49
+ };
50
+ }
37
51
 
38
- export { createAuthStore };
52
+ export { createAuthStore, createTokenStore, createUserStore };
39
53
  //# sourceMappingURL=index.js.map
40
54
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/adapters/svelte/auth-store.ts"],"names":[],"mappings":";;;AAyBO,SAAS,gBAAgB,IAAA,EAA6B;AAC3D,EAAA,MAAM,MAAA,GAAS,iBAAiB,IAAI,CAAA;AACpC,EAAA,MAAM,WAAA,uBAAkB,GAAA,EAAyC;AACjE,EAAA,IAAI,IAAA,GAA4B,IAAA;AAChC,EAAA,IAAI,KAAA,GAAQ,OAAO,QAAA,EAAS;AAE5B,EAAA,SAAS,UAAU,GAAA,EAA6C;AAC9D,IAAA,MAAM,KAAA,GAAQ,EAAE,GAAA,EAAI;AACpB,IAAA,IAAI,WAAA,CAAY,SAAS,CAAA,EAAG;AAC1B,MAAA,KAAA,GAAQ,OAAO,QAAA,EAAS;AACxB,MAAA,IAAA,GAAO,MAAA,CAAO,UAAU,MAAM;AAC5B,QAAA,MAAM,IAAA,GAAO,OAAO,QAAA,EAAS;AAC7B,QAAA,IAAI,SAAS,KAAA,EAAO;AACpB,QAAA,KAAA,GAAQ,IAAA;AACR,QAAA,KAAA,CAAM,IAAA,CAAK,WAAW,CAAA,CAAE,OAAA,CAAQ,CAAC,UAAA,KAAe,UAAA,CAAW,GAAA,CAAI,KAAK,CAAC,CAAA;AAAA,MACvE,CAAC,CAAA;AAAA,IACH;AACA,IAAA,WAAA,CAAY,IAAI,KAAK,CAAA;AACrB,IAAA,GAAA,CAAI,KAAK,CAAA;AACT,IAAA,OAAO,MAAM;AACX,MAAA,IAAI,CAAC,WAAA,CAAY,MAAA,CAAO,KAAK,CAAA,EAAG;AAChC,MAAA,IAAI,WAAA,CAAY,IAAA,KAAS,CAAA,IAAK,IAAA,EAAM;AAClC,QAAA,IAAA,EAAK;AACL,QAAA,IAAA,GAAO,IAAA;AAAA,MACT;AAAA,IACF,CAAA;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,SAAA;AAAA,IACA,SAAA,EAAW,CAAC,MAAA,KAAW,IAAA,CAAK,UAAU,MAAM,CAAA;AAAA,IAC5C,MAAA,EAAQ,CAAC,OAAA,KAAY,IAAA,CAAK,OAAO,OAAO,CAAA;AAAA,IACxC,OAAA,EAAS,MAAM,IAAA,CAAK,OAAA;AAAQ,GAC9B;AACF","file":"index.js","sourcesContent":["/**\n * Svelte bindings: a readable auth store\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 { AuthKeeper, LogoutOptions, TokenSet } from '../../types'\nimport { createAuthSource, type AuthState } from '../auth-source'\n\n/**\n * Readable store of the auth state, plus actions\n */\nexport interface AuthStore {\n /** Svelte store contract: `run` is called now and on every change */\n subscribe(run: (value: AuthState) => void, invalidate?: () => void): () => void\n setTokens: (tokens: TokenSet) => void\n logout: (options?: LogoutOptions) => void\n refresh: () => Promise<TokenSet>\n}\n\n/**\n * Create a readable store for an AuthKeeper instance. It listens to the\n * instance only while it has subscribers.\n */\nexport function createAuthStore(auth: AuthKeeper): AuthStore {\n const source = createAuthSource(auth)\n const subscribers = new Set<{ run: (value: AuthState) => void }>()\n let stop: (() => void) | null = null\n let value = source.getState()\n\n function subscribe(run: (value: AuthState) => void): () => void {\n const entry = { run }\n if (subscribers.size === 0) {\n value = source.getState()\n stop = source.subscribe(() => {\n const next = source.getState()\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 return {\n subscribe,\n setTokens: (tokens) => auth.setTokens(tokens),\n logout: (options) => auth.logout(options),\n refresh: () => auth.refresh(),\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/adapters/svelte/auth-store.ts"],"names":[],"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,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C9E,SAAA,EAAW,KAAK,WAAA;AAAY,GAC9B;AACF;AAOO,SAAS,gBAAgB,IAAA,EAA6B;AAC3D,EAAA,MAAM,MAAA,GAAS,iBAAiB,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,KAAQ,SAAA,CAAU,OAAO,QAAA,EAAS,CAAE,MAAM,GAAG;AAAA,GAC1D;AACF","file":"index.js","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"]}
@@ -418,4 +418,4 @@ interface AuthKeeper {
418
418
  getOptions(): KernelOptions;
419
419
  }
420
420
 
421
- export { type AuthKeeper as A, type EventType as E, type FetchInterceptorOptions as F, type KernelOptions as K, type LogoutOptions as L, type Plugin as P, type RefreshEvent as R, type StorageAdapter as S, type TokenSet as T, type Unsubscribe as U, type TokenPayload as a, AuthError as b, type EventHandler as c, type AuthEvent as d, type PluginInfo as e, type AuthFetch as f, type TokenHeader as g, type AuthErrorCode as h, type AuthErrorOptions as i, type ErrorEvent as j, type ExpiredEvent as k, type LoginEvent as l, type LoginOptions as m, type LogoutEvent as n, type RefreshTokenFn as o, type StorageChangeEvent as p, type StorageType as q, type StoredTokens as r, type TabSyncEvent as s, type TokenInfo as t, type UserInfo as u };
421
+ export { type AuthFetch as A, type EventType as E, type FetchInterceptorOptions as F, type KernelOptions as K, type LogoutOptions as L, type Plugin as P, type RefreshEvent as R, type StorageAdapter as S, type TokenSet as T, type Unsubscribe as U, type TokenPayload as a, type AuthKeeper as b, AuthError as c, type EventHandler as d, type AuthEvent as e, type PluginInfo as f, type TokenHeader as g, type AuthErrorCode as h, type AuthErrorOptions as i, type ErrorEvent as j, type ExpiredEvent as k, type LoginEvent as l, type LoginOptions as m, type LogoutEvent as n, type RefreshTokenFn as o, type StorageChangeEvent as p, type StorageType as q, type StoredTokens as r, type TabSyncEvent as s, type TokenInfo as t, type UserInfo as u };
@@ -418,4 +418,4 @@ interface AuthKeeper {
418
418
  getOptions(): KernelOptions;
419
419
  }
420
420
 
421
- export { type AuthKeeper as A, type EventType as E, type FetchInterceptorOptions as F, type KernelOptions as K, type LogoutOptions as L, type Plugin as P, type RefreshEvent as R, type StorageAdapter as S, type TokenSet as T, type Unsubscribe as U, type TokenPayload as a, AuthError as b, type EventHandler as c, type AuthEvent as d, type PluginInfo as e, type AuthFetch as f, type TokenHeader as g, type AuthErrorCode as h, type AuthErrorOptions as i, type ErrorEvent as j, type ExpiredEvent as k, type LoginEvent as l, type LoginOptions as m, type LogoutEvent as n, type RefreshTokenFn as o, type StorageChangeEvent as p, type StorageType as q, type StoredTokens as r, type TabSyncEvent as s, type TokenInfo as t, type UserInfo as u };
421
+ export { type AuthFetch as A, type EventType as E, type FetchInterceptorOptions as F, type KernelOptions as K, type LogoutOptions as L, type Plugin as P, type RefreshEvent as R, type StorageAdapter as S, type TokenSet as T, type Unsubscribe as U, type TokenPayload as a, type AuthKeeper as b, AuthError as c, type EventHandler as d, type AuthEvent as e, type PluginInfo as f, type TokenHeader as g, type AuthErrorCode as h, type AuthErrorOptions as i, type ErrorEvent as j, type ExpiredEvent as k, type LoginEvent as l, type LoginOptions as m, type LogoutEvent as n, type RefreshTokenFn as o, type StorageChangeEvent as p, type StorageType as q, type StoredTokens as r, type TabSyncEvent as s, type TokenInfo as t, type UserInfo as u };