@veroxm/react-sdk 0.1.1 → 0.2.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 CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0
4
+
5
+ - `VeroxmAuthProvider`, `useAuth()` and `<SignedIn>` for signed-in end users, with `@veroxm/sdk`'s `app.auth`.
6
+ - `VeroxmClient`'s `getAccessToken` option: reads as the signed-in person when there is one, so collection access
7
+ rules such as "owner only" apply.
8
+
3
9
  ## 0.1.1
4
10
 
5
11
  - First release published from CI with npm trusted publishing. No code changes.
package/README.md CHANGED
@@ -206,6 +206,36 @@ function Avatar({ mediaId }: { mediaId: number }) {
206
206
  `alt` defaults to the media item's own `caption`, then an empty string --
207
207
  pass an explicit `alt` to override either.
208
208
 
209
+ ## Signed-in people
210
+
211
+ Pair with `@veroxm/sdk`'s `app.auth` (built-in accounts or social sign-in):
212
+
213
+ ```tsx
214
+ import { VeroXMApp } from '@veroxm/sdk';
215
+ import { VeroxmAuthProvider, VeroxmProvider, VeroxmClient, useAuth, SignedIn } from '@veroxm/react-sdk';
216
+
217
+ const app = VeroXMApp.initializeApp({ baseUrl, projectId });
218
+ // Reads as the signed-in person when there is one, so "owner only" collections work.
219
+ const client = new VeroxmClient({ apiBase: baseUrl, apiKey: readKey, getAccessToken: () => app.auth.getAccessToken().catch(() => null) });
220
+
221
+ <VeroxmAuthProvider auth={app.auth}>
222
+ <VeroxmProvider client={client}>
223
+ <App />
224
+ </VeroxmProvider>
225
+ </VeroxmAuthProvider>;
226
+
227
+ function Account() {
228
+ const { user, ready, auth, hasRole } = useAuth<typeof app.auth>();
229
+ if (!ready) return null;
230
+ if (!user) return <button onClick={() => auth.signInWithRedirect('google', { redirectUri: `${location.origin}/auth/done` })}>Sign in with Google</button>;
231
+ return <p>Hi {user.name}{hasRole('staff') ? ' (staff)' : ''}</p>;
232
+ }
233
+
234
+ <SignedIn roles={['member']} fallback={<JoinButton />}>
235
+ <MembersArea />
236
+ </SignedIn>;
237
+ ```
238
+
209
239
  ## Visitor tracking
210
240
 
211
241
  Pair with `@veroxm/sdk`'s `createTracker()` (see that package's README for
package/dist/auth.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import { type ReactElement, type ReactNode } from 'react';
2
+ /** The signed-in person (as @veroxm/sdk's AuthUser). */
3
+ export interface VeroxmAuthUser {
4
+ id: number;
5
+ email: string | null;
6
+ name: string | null;
7
+ roles: string[];
8
+ emailVerified: boolean;
9
+ }
10
+ /** What the hooks need from @veroxm/sdk's `app.auth`. */
11
+ export interface VeroxmAuthLike {
12
+ currentUser(): VeroxmAuthUser | null;
13
+ onAuthStateChange(listener: (user: VeroxmAuthUser | null) => void): () => void;
14
+ signOut(): Promise<void>;
15
+ }
16
+ export interface AuthState<A extends VeroxmAuthLike = VeroxmAuthLike> {
17
+ /** The signed-in person, or null. */
18
+ user: VeroxmAuthUser | null;
19
+ /** False until a stored session (from a previous visit) has been read. */
20
+ ready: boolean;
21
+ /** The auth object itself, for signIn, signUp, verifyEmail, signInWithRedirect... */
22
+ auth: A;
23
+ /** Whether the person has at least one of these roles. */
24
+ hasRole(...roles: string[]): boolean;
25
+ }
26
+ export interface VeroxmAuthProviderProps {
27
+ /** `app.auth` from @veroxm/sdk's VeroXMApp.initializeApp(). */
28
+ auth: VeroxmAuthLike;
29
+ children: ReactNode;
30
+ }
31
+ /**
32
+ * Makes end-user sign-in available to useAuth():
33
+ *
34
+ * ```tsx
35
+ * const app = VeroXMApp.initializeApp({ baseUrl, projectId });
36
+ * <VeroxmAuthProvider auth={app.auth}><App /></VeroxmAuthProvider>
37
+ * ```
38
+ */
39
+ export declare function VeroxmAuthProvider({ auth, children }: VeroxmAuthProviderProps): ReactElement;
40
+ /** The signed-in person, kept up to date as they sign in, change and sign out. */
41
+ export declare function useAuth<A extends VeroxmAuthLike = VeroxmAuthLike>(): AuthState<A>;
42
+ /** Shows `children` to signed-in people (optionally with one of `roles`), `fallback` to everyone else. */
43
+ export declare function SignedIn({ children, fallback, roles }: {
44
+ children: ReactNode;
45
+ fallback?: ReactNode;
46
+ roles?: string[];
47
+ }): ReactElement | null;
package/dist/auth.js ADDED
@@ -0,0 +1,36 @@
1
+ import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { createContext, useContext, useEffect, useState } from 'react';
3
+ const AuthContext = createContext(null);
4
+ /**
5
+ * Makes end-user sign-in available to useAuth():
6
+ *
7
+ * ```tsx
8
+ * const app = VeroXMApp.initializeApp({ baseUrl, projectId });
9
+ * <VeroxmAuthProvider auth={app.auth}><App /></VeroxmAuthProvider>
10
+ * ```
11
+ */
12
+ export function VeroxmAuthProvider({ auth, children }) {
13
+ return _jsx(AuthContext.Provider, { value: auth, children: children });
14
+ }
15
+ /** The signed-in person, kept up to date as they sign in, change and sign out. */
16
+ export function useAuth() {
17
+ const auth = useContext(AuthContext);
18
+ if (!auth)
19
+ throw new Error('useAuth() was called outside a <VeroxmAuthProvider> -- mount one near your app root.');
20
+ const [state, setState] = useState(() => ({ user: auth.currentUser(), ready: false }));
21
+ useEffect(() => auth.onAuthStateChange((user) => setState({ user, ready: true })), [auth]);
22
+ return {
23
+ user: state.user,
24
+ ready: state.ready,
25
+ auth,
26
+ hasRole: (...roles) => !!state.user && roles.some((r) => state.user.roles.includes(r)),
27
+ };
28
+ }
29
+ /** Shows `children` to signed-in people (optionally with one of `roles`), `fallback` to everyone else. */
30
+ export function SignedIn({ children, fallback = null, roles }) {
31
+ const { user, ready, hasRole } = useAuth();
32
+ if (!ready)
33
+ return null;
34
+ const allowed = !!user && (!roles?.length || hasRole(...roles));
35
+ return _jsx(_Fragment, { children: allowed ? children : fallback });
36
+ }
package/dist/client.d.ts CHANGED
@@ -23,6 +23,13 @@ export interface VeroxmClientOptions {
23
23
  projectUuid?: string;
24
24
  /** Tuning for this client's request cache (docs/REACT-SDK-GRAPHQL-IMPLEMENTATION-PLAN.md §5.3) -- see CacheOptions. Omit for the default 30s staleTimeMs. */
25
25
  cache?: CacheOptions;
26
+ /**
27
+ * Reads as the signed-in end user when there is one: return their access token (e.g. `() =>
28
+ * app.auth.getAccessToken().catch(() => null)` with @veroxm/sdk), or null to use `apiKey`. Collection access rules
29
+ * then apply to them, such as "owner only". Cached results are per client, so call cache.invalidateAll() when the
30
+ * person signs in or out.
31
+ */
32
+ getAccessToken?: () => Promise<string | null> | string | null;
26
33
  }
27
34
  /**
28
35
  * Thin wrapper over graphql-request's GraphQLClient -- one method per
@@ -40,6 +47,7 @@ export declare class VeroxmClient {
40
47
  readonly projectUuid: string | undefined;
41
48
  /** This client's request cache -- read directly by every hook in ./hooks (via useVeroxmClient()) and by the SSR helpers in ./ssr.ts, so a server fetch and a client-side hook agree on exactly one cache instance per VeroxmClient. Call cache.invalidateCollection()/invalidateMedia()/invalidateAll() yourself once you know content changed -- see VeroxmCache's own doc comment for why this API is queries-only and has no auto-invalidation. */
42
49
  readonly cache: VeroxmCache;
50
+ private readonly getAccessToken?;
43
51
  constructor(options: VeroxmClientOptions);
44
52
  /** Escape hatch for a custom GraphQL document against this same authenticated endpoint -- e.g. a query that only needs a subset of an object's fields, or combines more than one of this class's own queries into a single round trip. Errors are normalized the same way as every typed method below (see VeroxmGraphQLError). */
45
53
  request<T = unknown>(document: string, variables?: Variables): Promise<T>;
package/dist/client.js CHANGED
@@ -16,6 +16,7 @@ const MEDIA_FIELDS = `id fileName fullUrl thumbUrl thumbWebpUrl fullWebpUrl capt
16
16
  */
17
17
  export class VeroxmClient {
18
18
  constructor(options) {
19
+ this.getAccessToken = options.getAccessToken;
19
20
  const endpoint = `${options.apiBase.replace(/\/$/, '')}/public/v2/graphql`;
20
21
  this.gql = new GraphQLClient(endpoint, {
21
22
  headers: { Authorization: `Bearer ${options.apiKey}` },
@@ -26,7 +27,8 @@ export class VeroxmClient {
26
27
  /** Escape hatch for a custom GraphQL document against this same authenticated endpoint -- e.g. a query that only needs a subset of an object's fields, or combines more than one of this class's own queries into a single round trip. Errors are normalized the same way as every typed method below (see VeroxmGraphQLError). */
27
28
  async request(document, variables) {
28
29
  try {
29
- return await this.gql.request(document, variables);
30
+ const token = this.getAccessToken ? await this.getAccessToken() : null;
31
+ return token ? await this.gql.request(document, variables, { Authorization: `Bearer ${token}` }) : await this.gql.request(document, variables);
30
32
  }
31
33
  catch (cause) {
32
34
  throw VeroxmGraphQLError.from(cause);
package/dist/index.d.ts CHANGED
@@ -2,6 +2,8 @@ export { VeroxmProvider, useVeroxmClient } from './provider.js';
2
2
  export type { VeroxmProviderProps } from './provider.js';
3
3
  export { VeroxmClient } from './client.js';
4
4
  export type { VeroxmClientOptions } from './client.js';
5
+ export { VeroxmAuthProvider, useAuth, SignedIn } from './auth.js';
6
+ export type { VeroxmAuthProviderProps, VeroxmAuthLike, VeroxmAuthUser, AuthState } from './auth.js';
5
7
  export { VeroxmCache } from './cache.js';
6
8
  export type { CacheOptions } from './cache.js';
7
9
  export { VeroxmGraphQLError } from './errors.js';
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
1
  export { VeroxmProvider, useVeroxmClient } from './provider.js';
2
2
  export { VeroxmClient } from './client.js';
3
+ // End-user sign-in -- pair with @veroxm/sdk's app.auth.
4
+ export { VeroxmAuthProvider, useAuth, SignedIn } from './auth.js';
3
5
  export { VeroxmCache } from './cache.js';
4
6
  export { VeroxmGraphQLError } from './errors.js';
5
7
  export { useCollection } from './hooks/use-collection.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veroxm/react-sdk",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "React and Next.js SDK for VeroXM: content hooks, visual slots with A/B tests, the on-page editor, llms.txt and structured data.",
5
5
  "keywords": [
6
6
  "veroxm",