@supatype/react-auth 0.3.6 → 0.7.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 (72) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +11 -4
  3. package/.turbo/turbo-typecheck.log +2 -2
  4. package/LICENSE +1 -1
  5. package/README.md +103 -0
  6. package/dist/EmailLinkForm.d.ts +42 -0
  7. package/dist/EmailLinkForm.d.ts.map +1 -0
  8. package/dist/EmailLinkForm.js +14 -0
  9. package/dist/EmailLinkForm.js.map +1 -0
  10. package/dist/ForgotPasswordForm.d.ts +19 -0
  11. package/dist/ForgotPasswordForm.d.ts.map +1 -0
  12. package/dist/ForgotPasswordForm.js +33 -0
  13. package/dist/ForgotPasswordForm.js.map +1 -0
  14. package/dist/LoginForm.d.ts +4 -1
  15. package/dist/LoginForm.d.ts.map +1 -1
  16. package/dist/LoginForm.js +8 -24
  17. package/dist/LoginForm.js.map +1 -1
  18. package/dist/MagicLinkForm.d.ts +19 -0
  19. package/dist/MagicLinkForm.d.ts.map +1 -0
  20. package/dist/MagicLinkForm.js +33 -0
  21. package/dist/MagicLinkForm.js.map +1 -0
  22. package/dist/OAuthButton.d.ts +3 -2
  23. package/dist/OAuthButton.d.ts.map +1 -1
  24. package/dist/OAuthButton.js +79 -42
  25. package/dist/OAuthButton.js.map +1 -1
  26. package/dist/SignUpForm.d.ts +4 -1
  27. package/dist/SignUpForm.d.ts.map +1 -1
  28. package/dist/SignUpForm.js +13 -32
  29. package/dist/SignUpForm.js.map +1 -1
  30. package/dist/UpdatePasswordForm.d.ts +38 -0
  31. package/dist/UpdatePasswordForm.d.ts.map +1 -0
  32. package/dist/UpdatePasswordForm.js +36 -0
  33. package/dist/UpdatePasswordForm.js.map +1 -0
  34. package/dist/classNames.d.ts +36 -0
  35. package/dist/classNames.d.ts.map +1 -0
  36. package/dist/classNames.js +8 -0
  37. package/dist/classNames.js.map +1 -0
  38. package/dist/formParts.d.ts +68 -0
  39. package/dist/formParts.d.ts.map +1 -0
  40. package/dist/formParts.js +72 -0
  41. package/dist/formParts.js.map +1 -0
  42. package/dist/index.d.ts +9 -0
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +4 -0
  45. package/dist/index.js.map +1 -1
  46. package/dist/usePasswordRecovery.d.ts +18 -0
  47. package/dist/usePasswordRecovery.d.ts.map +1 -0
  48. package/dist/usePasswordRecovery.js +27 -0
  49. package/dist/usePasswordRecovery.js.map +1 -0
  50. package/package.json +6 -4
  51. package/src/EmailLinkForm.tsx +62 -0
  52. package/src/ForgotPasswordForm.tsx +43 -0
  53. package/src/LoginForm.tsx +35 -62
  54. package/src/MagicLinkForm.tsx +43 -0
  55. package/src/OAuthButton.tsx +84 -60
  56. package/src/SignUpForm.tsx +40 -74
  57. package/src/UpdatePasswordForm.tsx +74 -0
  58. package/src/classNames.ts +41 -0
  59. package/src/formParts.tsx +153 -0
  60. package/src/index.ts +14 -0
  61. package/src/usePasswordRecovery.ts +32 -0
  62. package/tests/auth-ui.test.tsx +48 -0
  63. package/tests/email-link-forms.test.tsx +214 -0
  64. package/tests/helpers.tsx +41 -0
  65. package/tests/login-form.test.tsx +63 -0
  66. package/tests/oauth-button.test.tsx +75 -0
  67. package/tests/password-recovery.test.tsx +62 -0
  68. package/tests/props.ts +24 -0
  69. package/tests/signup-confirmation.test.tsx +50 -0
  70. package/tests/tsconfig.json +9 -0
  71. package/tsconfig.json +1 -1
  72. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,74 @@
1
+ import React, { useState } from "react"
2
+ import type { SupatypeError, User } from "@supatype/client"
3
+ import { useSupatype } from "@supatype/react"
4
+ import type { AuthFormClassNames } from "./classNames.js"
5
+ import { FormField, FormShell, FormMessage, useAuthSubmit, withDefaults, type Filled } from "./formParts.js"
6
+
7
+ export interface UpdatePasswordFormLabels {
8
+ title?: string | undefined
9
+ password?: string | undefined
10
+ submit?: string | undefined
11
+ /** Shown in place of the form once the new password is set. */
12
+ successMessage?: string | undefined
13
+ }
14
+
15
+ export interface UpdatePasswordFormProps {
16
+ /** Called with the updated user once the new password is set. */
17
+ onSuccess?: ((user: User) => void) | undefined
18
+ /** Called with the error returned by the auth service. */
19
+ onError?: ((error: SupatypeError) => void) | undefined
20
+ /** CSS class applied to the outermost <form> element. */
21
+ className?: string | undefined
22
+ /** Override display labels. */
23
+ labels?: UpdatePasswordFormLabels | undefined
24
+ /** Class names for the elements inside the form, so an app can style them with its own classes. */
25
+ classNames?: AuthFormClassNames | undefined
26
+ }
27
+
28
+ const DEFAULT_LABELS: Filled<UpdatePasswordFormLabels> = {
29
+ title: "Set a new password",
30
+ password: "New password",
31
+ submit: "Update password",
32
+ successMessage: "Your password has been updated.",
33
+ }
34
+
35
+ /**
36
+ * Sets a new password for the signed-in user (`updateUser`, `PUT /user`).
37
+ * Must be rendered inside a `<SupatypeProvider>`.
38
+ *
39
+ * The landing for a password reset link: the link signs the user in and the client emits
40
+ * `PASSWORD_RECOVERY`, which `usePasswordRecovery` turns into state: show this form while it is active. With no session it reports
41
+ * "Not authenticated" through `onError`.
42
+ *
43
+ * @example
44
+ * ```tsx
45
+ * const recovery = usePasswordRecovery()
46
+ * if (recovery.active) return <UpdatePasswordForm onSuccess={recovery.finish} />
47
+ * ```
48
+ */
49
+ export function UpdatePasswordForm({ onSuccess, onError, className, classNames, labels }: UpdatePasswordFormProps): React.ReactElement {
50
+ const { auth } = useSupatype()
51
+ const l = withDefaults(DEFAULT_LABELS, labels)
52
+ const [password, setPassword] = useState("")
53
+ const onDone = ({ user }: { user: User | null }): void => { if (user !== null) onSuccess?.(user) }
54
+ const request = useAuthSubmit(() => auth.updateUser({ password }), { onDone, onError })
55
+
56
+ if (request.done) return <FormMessage text={l.successMessage} classNames={classNames} />
57
+
58
+ return (
59
+ <FormShell request={request} text={{ title: l.title, submit: l.submit, busy: "Updating password…" }} className={className} classNames={classNames}>
60
+ <FormField
61
+ id="st-update-password"
62
+ label={l.password}
63
+ classNames={classNames}
64
+ type="password"
65
+ autoComplete="new-password"
66
+ required
67
+ minLength={8}
68
+ value={password}
69
+ onChange={(e) => setPassword(e.target.value)}
70
+ disabled={request.loading}
71
+ />
72
+ </FormShell>
73
+ )
74
+ }
@@ -0,0 +1,41 @@
1
+ import type React from "react"
2
+
3
+ /**
4
+ * Class names for each element an auth form renders.
5
+ *
6
+ * The forms ship no stylesheet, so an app styles them with its own classes. `className` on the form
7
+ * only reaches the outer `<form>`; without these slots a class-based design system cannot reach the
8
+ * labels, inputs or button except through descendant selectors written for this one component.
9
+ */
10
+ export interface AuthFormClassNames {
11
+ /** The `<h2>` heading. */
12
+ title?: string | undefined
13
+ /** The error message shown when the auth service rejects the request. */
14
+ error?: string | undefined
15
+ /** The wrapper around each label and input pair. */
16
+ field?: string | undefined
17
+ /** Each `<label>`. */
18
+ label?: string | undefined
19
+ /** Each `<input>`. */
20
+ input?: string | undefined
21
+ /** The submit `<button>`. */
22
+ submit?: string | undefined
23
+ /**
24
+ * The line a form shows in its place when done: `SignUpForm` awaiting confirmation,
25
+ * `ForgotPasswordForm` and `MagicLinkForm` once the email is sent, `UpdatePasswordForm` once the
26
+ * password is set.
27
+ */
28
+ message?: string | undefined
29
+ }
30
+
31
+ /** Applied to the error message only when the app gives it no class of its own. */
32
+ export const DEFAULT_ERROR_STYLE: React.CSSProperties = { color: "red" }
33
+
34
+ /** Props for the error element: the app's class when given, the default colour otherwise. */
35
+ export function errorProps(classNames: AuthFormClassNames | undefined): {
36
+ className?: string
37
+ style?: React.CSSProperties
38
+ } {
39
+ const className = classNames?.error
40
+ return className !== undefined ? { className } : { style: DEFAULT_ERROR_STYLE }
41
+ }
@@ -0,0 +1,153 @@
1
+ import React, { useState, type FormEvent, type InputHTMLAttributes } from "react"
2
+ import { transportFailure, type SupatypeError } from "@supatype/client"
3
+ import { errorProps, type AuthFormClassNames } from "./classNames.js"
4
+
5
+ /** The auth service's refusal, shown above the fields; nothing while there is none. */
6
+ function FormError({
7
+ message,
8
+ classNames,
9
+ }: {
10
+ message: string | null
11
+ classNames: AuthFormClassNames | undefined
12
+ }): React.ReactElement | null {
13
+ if (message === null) return null
14
+ return (
15
+ <p role="alert" aria-live="polite" {...errorProps(classNames)}>
16
+ {message}
17
+ </p>
18
+ )
19
+ }
20
+
21
+ /** The message a form shows in its place once the request has gone through. */
22
+ export function FormMessage({
23
+ text,
24
+ classNames,
25
+ }: {
26
+ text: string
27
+ classNames: AuthFormClassNames | undefined
28
+ }): React.ReactElement {
29
+ return (
30
+ <p role="status" aria-live="polite" className={classNames?.message}>
31
+ {text}
32
+ </p>
33
+ )
34
+ }
35
+
36
+ export type FormFieldProps = {
37
+ id: string
38
+ label: string
39
+ classNames: AuthFormClassNames | undefined
40
+ } & Omit<InputHTMLAttributes<HTMLInputElement>, "className" | "id">
41
+
42
+ /** One label and input pair, each carrying its `classNames` slot. */
43
+ export function FormField({ id, label, classNames, ...input }: FormFieldProps): React.ReactElement {
44
+ return (
45
+ <div className={classNames?.field}>
46
+ <label className={classNames?.label} htmlFor={id}>{label}</label>
47
+ <input className={classNames?.input} id={id} {...input} />
48
+ </div>
49
+ )
50
+ }
51
+
52
+ /** The words of a form's frame: its heading, its button, and the button while the request runs. */
53
+ export interface FormShellText {
54
+ title: string
55
+ submit: string
56
+ busy: string
57
+ }
58
+
59
+ /**
60
+ * The frame every form shares: heading, refusal, the form's own fields, then the submit button.
61
+ *
62
+ * `errorMessage` overrides the request's refusal text, for a form that words it differently.
63
+ */
64
+ export function FormShell({ request, text, className, classNames, errorMessage, children }: {
65
+ request: AuthSubmit
66
+ text: FormShellText
67
+ className: string | undefined
68
+ classNames: AuthFormClassNames | undefined
69
+ errorMessage?: string | null | undefined
70
+ children: React.ReactNode
71
+ }): React.ReactElement {
72
+ return (
73
+ <form onSubmit={request.onSubmit} className={className} noValidate>
74
+ <h2 className={classNames?.title}>{text.title}</h2>
75
+ <FormError message={errorMessage ?? request.errorMessage} classNames={classNames} />
76
+ {children}
77
+ <button type="submit" className={classNames?.submit} disabled={request.loading}>
78
+ {request.loading ? text.busy : text.submit}
79
+ </button>
80
+ </form>
81
+ )
82
+ }
83
+
84
+ export interface AuthSubmit {
85
+ loading: boolean
86
+ /** The refusal to show, or null. */
87
+ errorMessage: string | null
88
+ /** True once the request has succeeded. */
89
+ done: boolean
90
+ onSubmit: (e: FormEvent<HTMLFormElement>) => void
91
+ }
92
+
93
+ export interface AuthSubmitHandlers<T> {
94
+ onDone: (data: T) => void
95
+ onError?: ((error: SupatypeError) => void) | undefined
96
+ }
97
+
98
+ type Settled<T> = { data: T; error: null } | { error: SupatypeError }
99
+
100
+ /** The request's answer, with a request that threw (the network, not the server) as its refusal. */
101
+ async function settle<T>(send: () => Promise<{ data: T; error: SupatypeError | null }>): Promise<Settled<T>> {
102
+ try {
103
+ const { data, error } = await send()
104
+ return error === null ? { data, error } : { error }
105
+ } catch (err) {
106
+ return { error: transportFailure(err) }
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Submit a form's one auth request: loading while it runs, then the refusal or `done`.
112
+ *
113
+ * A refusal keeps the form so the user can correct it; `onError` hears both a refusal and a request
114
+ * that never reached the server. The app's own handlers run after the request, outside its error
115
+ * handling, so a throw in `onSuccess` is not shown as the server's refusal.
116
+ */
117
+ export function useAuthSubmit<T>(
118
+ send: () => Promise<{ data: T; error: SupatypeError | null }>,
119
+ handlers: AuthSubmitHandlers<T>,
120
+ ): AuthSubmit {
121
+ const [loading, setLoading] = useState(false)
122
+ const [errorMessage, setErrorMessage] = useState<string | null>(null)
123
+ const [done, setDone] = useState(false)
124
+
125
+ async function run(): Promise<void> {
126
+ setErrorMessage(null)
127
+ setLoading(true)
128
+ const result = await settle(send)
129
+ setLoading(false)
130
+ if (result.error !== null) {
131
+ setErrorMessage(result.error.message)
132
+ handlers.onError?.(result.error)
133
+ return
134
+ }
135
+ setDone(true)
136
+ handlers.onDone(result.data)
137
+ }
138
+
139
+ return { loading, errorMessage, done, onSubmit: (e) => { e.preventDefault(); void run() } }
140
+ }
141
+
142
+ /**
143
+ * The form's labels: each one the app gives, else the default.
144
+ *
145
+ * A plain spread would let `labels={{ title: undefined }}` blank the heading out.
146
+ */
147
+ export function withDefaults<T extends object>(defaults: Filled<T>, overrides: T | undefined): Filled<T> {
148
+ const given = Object.entries(overrides ?? {}).filter(([, value]) => value !== undefined)
149
+ return { ...defaults, ...Object.fromEntries(given) }
150
+ }
151
+
152
+ /** Every label present and a string: `Required` keeps an explicit `| undefined`. */
153
+ export type Filled<T> = { [K in keyof T]-?: Exclude<T[K], undefined> }
package/src/index.ts CHANGED
@@ -4,5 +4,19 @@ export type { LoginFormProps, LoginFormLabels } from "./LoginForm.js"
4
4
  export { SignUpForm } from "./SignUpForm.js"
5
5
  export type { SignUpFormProps, SignUpFormLabels } from "./SignUpForm.js"
6
6
 
7
+ export { ForgotPasswordForm } from "./ForgotPasswordForm.js"
8
+ export type { ForgotPasswordFormProps, ForgotPasswordFormLabels } from "./ForgotPasswordForm.js"
9
+
10
+ export { MagicLinkForm } from "./MagicLinkForm.js"
11
+ export type { MagicLinkFormProps, MagicLinkFormLabels } from "./MagicLinkForm.js"
12
+
13
+ export { UpdatePasswordForm } from "./UpdatePasswordForm.js"
14
+ export type { UpdatePasswordFormProps, UpdatePasswordFormLabels } from "./UpdatePasswordForm.js"
15
+
16
+ export { usePasswordRecovery } from "./usePasswordRecovery.js"
17
+ export type { PasswordRecovery } from "./usePasswordRecovery.js"
18
+
7
19
  export { OAuthButton } from "./OAuthButton.js"
8
20
  export type { OAuthButtonProps } from "./OAuthButton.js"
21
+
22
+ export type { AuthFormClassNames } from "./classNames.js"
@@ -0,0 +1,32 @@
1
+ import { useEffect, useState } from "react"
2
+ import { useSupatype } from "@supatype/react"
3
+
4
+ export interface PasswordRecovery {
5
+ /** True from the moment a password reset link signs the user in until `finish` or a sign-out. */
6
+ active: boolean
7
+ /** Call once the new password is set, so the app shows itself again. */
8
+ finish: () => void
9
+ }
10
+
11
+ /**
12
+ * Whether the user arrived through a password reset link and still has to choose a new password.
13
+ *
14
+ * The link signs the user in and the client emits `PASSWORD_RECOVERY` after `SIGNED_IN`. Without
15
+ * this an app that renders whenever there is a user drops them inside it, signed in with the
16
+ * password they forgot. Show `UpdatePasswordForm` while `active`.
17
+ *
18
+ * Must be rendered inside a `<SupatypeProvider>`, mounted from the first render (beside `useAuth`),
19
+ * because the event is emitted once while the client finishes the link on start.
20
+ */
21
+ export function usePasswordRecovery(): PasswordRecovery {
22
+ const client = useSupatype()
23
+ const [active, setActive] = useState(false)
24
+ useEffect(() => {
25
+ const { data } = client.auth.onAuthStateChange((event) => {
26
+ if (event === "PASSWORD_RECOVERY") setActive(true)
27
+ if (event === "SIGNED_OUT") setActive(false)
28
+ })
29
+ return () => data.subscription.unsubscribe()
30
+ }, [client])
31
+ return { active, finish: () => setActive(false) }
32
+ }
@@ -0,0 +1,48 @@
1
+ import React from "react"
2
+ import { describe, it, expect, vi } from "vitest"
3
+ import { create } from "react-test-renderer"
4
+ import { LoginForm, SignUpForm, type AuthFormClassNames } from "../src/index.js"
5
+ import { DEFAULT_ERROR_STYLE, errorProps } from "../src/classNames.js"
6
+ import { classesOf } from "./helpers.js"
7
+
8
+ vi.mock("@supatype/react", () => ({
9
+ useAuth: () => ({ error: null, signIn: vi.fn(), signUp: vi.fn(), signInWithOAuth: vi.fn() }),
10
+ }))
11
+
12
+ const classNames: AuthFormClassNames = {
13
+ title: "t-title",
14
+ field: "t-field",
15
+ label: "t-label",
16
+ input: "t-input",
17
+ submit: "t-submit",
18
+ }
19
+
20
+ describe.each([
21
+ ["LoginForm", LoginForm],
22
+ ["SignUpForm", SignUpForm],
23
+ ] as const)("%s classNames", (_name, Form) => {
24
+ it("puts each slot's class on the element it names", () => {
25
+ const root = create(<Form className="t-form" classNames={classNames} />).root
26
+ expect(classesOf(root, "form")).toEqual(["t-form"])
27
+ expect(classesOf(root, "h2")).toEqual(["t-title"])
28
+ expect(classesOf(root, "div")).toEqual(["t-field", "t-field"])
29
+ expect(classesOf(root, "label")).toEqual(["t-label", "t-label"])
30
+ expect(classesOf(root, "input")).toEqual(["t-input", "t-input"])
31
+ expect(classesOf(root, "button")).toEqual(["t-submit"])
32
+ })
33
+
34
+ it("leaves the markup unclassed when no classNames are given", () => {
35
+ const root = create(<Form />).root
36
+ expect(classesOf(root, "input")).toEqual([undefined, undefined])
37
+ })
38
+ })
39
+
40
+ describe("errorProps", () => {
41
+ it("gives the error the app's class and no inline colour when a class is set", () => {
42
+ expect(errorProps({ error: "t-error" })).toEqual({ className: "t-error" })
43
+ })
44
+
45
+ it("falls back to a red message when the app sets no class", () => {
46
+ expect(errorProps(undefined)).toEqual({ style: DEFAULT_ERROR_STYLE })
47
+ })
48
+ })
@@ -0,0 +1,214 @@
1
+ /**
2
+ * ForgotPasswordForm, MagicLinkForm and UpdatePasswordForm, over the real client.
3
+ *
4
+ * Each form is rendered inside a `SupatypeProvider` holding a real `createClient`, with only `fetch`
5
+ * stubbed, so what is asserted is the request the auth server would receive (endpoint, method,
6
+ * `redirect_to`, body) and what the form makes of the server's answer.
7
+ */
8
+
9
+ import React from "react"
10
+ import { afterEach, describe, expect, it, vi } from "vitest"
11
+ import type { Session } from "@supatype/client"
12
+ import {
13
+ ForgotPasswordForm,
14
+ MagicLinkForm,
15
+ UpdatePasswordForm,
16
+ type AuthFormClassNames,
17
+ } from "../src/index.js"
18
+ import { classesOf, render, submit, textOf, type } from "./helpers.js"
19
+
20
+ const USER = {
21
+ id: "user-1",
22
+ email: "ada@example.com",
23
+ created_at: "2024-01-01T00:00:00Z",
24
+ updated_at: "2024-01-02T00:00:00Z",
25
+ app_metadata: { provider: "email" },
26
+ user_metadata: {},
27
+ }
28
+
29
+ const RECOVERY_SESSION: Session = {
30
+ accessToken: "recovery-access-token",
31
+ tokenType: "bearer",
32
+ expiresIn: 3600,
33
+ refreshToken: "recovery-refresh-token",
34
+ user: { id: "user-1", email: "ada@example.com", appMetadata: {}, userMetadata: {}, createdAt: "", updatedAt: "" },
35
+ }
36
+
37
+ const CLASS_NAMES: AuthFormClassNames = {
38
+ title: "t-title",
39
+ error: "t-error",
40
+ field: "t-field",
41
+ label: "t-label",
42
+ input: "t-input",
43
+ submit: "t-submit",
44
+ message: "t-message",
45
+ }
46
+
47
+ interface SentRequest {
48
+ url: URL
49
+ method: string
50
+ body: unknown
51
+ authorization: string | null
52
+ }
53
+
54
+ /** Stub `fetch` with one answer and record every request the client sends. */
55
+ function stubFetch(status: number, body: unknown): SentRequest[] {
56
+ const sent: SentRequest[] = []
57
+ vi.stubGlobal("fetch", vi.fn(async (input: string, init?: RequestInit) => {
58
+ const headers = new Headers(init?.headers)
59
+ sent.push({
60
+ url: new URL(input),
61
+ method: init?.method ?? "GET",
62
+ body: typeof init?.body === "string" ? JSON.parse(init.body) as unknown : null,
63
+ authorization: headers.get("Authorization"),
64
+ })
65
+ return new Response(JSON.stringify(body), { status })
66
+ }))
67
+ return sent
68
+ }
69
+
70
+ afterEach(() => {
71
+ vi.unstubAllGlobals()
72
+ })
73
+
74
+ describe("ForgotPasswordForm", () => {
75
+ it("asks /recover to email a reset link that returns to redirectTo, then says to check the email", async () => {
76
+ const sent = stubFetch(200, {})
77
+ const onSuccess = vi.fn()
78
+ const renderer = render(<ForgotPasswordForm redirectTo="https://app.example/reset" onSuccess={onSuccess} />)
79
+ type(renderer, "st-forgot-email", "ada@example.com")
80
+ await submit(renderer)
81
+
82
+ expect(sent).toHaveLength(1)
83
+ expect(sent[0]!.method).toBe("POST")
84
+ expect(sent[0]!.url.pathname).toBe("/auth/v1/recover")
85
+ expect(sent[0]!.url.searchParams.get("redirect_to")).toBe("https://app.example/reset")
86
+ expect(sent[0]!.body).toEqual({ email: "ada@example.com" })
87
+ expect(onSuccess).toHaveBeenCalledWith("ada@example.com")
88
+ expect(textOf(renderer.root.findByProps({ role: "status" }))).toBe("Check your email for the password reset link.")
89
+ })
90
+
91
+ it("shows the server's refusal, calls onError and keeps the form", async () => {
92
+ stubFetch(429, { code: 429, error_code: "over_email_send_rate_limit", msg: "Email rate limit exceeded" })
93
+ const onError = vi.fn()
94
+ const renderer = render(<ForgotPasswordForm onError={onError} classNames={CLASS_NAMES} />)
95
+ type(renderer, "st-forgot-email", "ada@example.com")
96
+ await submit(renderer)
97
+
98
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: "Email rate limit exceeded", code: "over_email_send_rate_limit" }))
99
+ const alert = renderer.root.findByProps({ role: "alert" })
100
+ expect(textOf(alert)).toBe("Email rate limit exceeded")
101
+ expect(alert.props["className"]).toBe("t-error")
102
+ expect(renderer.root.findAllByType("form")).toHaveLength(1)
103
+ })
104
+
105
+ it("puts each slot's class on the element it names, the message included", async () => {
106
+ stubFetch(200, {})
107
+ const renderer = render(<ForgotPasswordForm className="t-form" classNames={CLASS_NAMES} />)
108
+ const root = renderer.root
109
+ expect(classesOf(root, "form")).toEqual(["t-form"])
110
+ expect(classesOf(root, "h2")).toEqual(["t-title"])
111
+ expect(classesOf(root, "div")).toEqual(["t-field"])
112
+ expect(classesOf(root, "label")).toEqual(["t-label"])
113
+ expect(classesOf(root, "input")).toEqual(["t-input"])
114
+ expect(classesOf(root, "button")).toEqual(["t-submit"])
115
+ type(renderer, "st-forgot-email", "ada@example.com")
116
+ await submit(renderer)
117
+ expect(root.findByProps({ role: "status" }).props["className"]).toBe("t-message")
118
+ })
119
+ })
120
+
121
+ describe("labels", () => {
122
+ it("replaces a default with the app's label and keeps one the app leaves undefined", () => {
123
+ const root = render(<ForgotPasswordForm labels={{ title: undefined, submit: "Email me a reset link" }} />).root
124
+ expect(textOf(root.findByType("h2"))).toBe("Reset your password")
125
+ expect(textOf(root.findByType("button"))).toBe("Email me a reset link")
126
+ })
127
+ })
128
+
129
+ describe("MagicLinkForm", () => {
130
+ it("asks /otp for a sign-in link that returns to redirectTo, then says to check the email", async () => {
131
+ const sent = stubFetch(200, {})
132
+ const onSuccess = vi.fn()
133
+ const renderer = render(<MagicLinkForm redirectTo="https://app.example/" onSuccess={onSuccess} />)
134
+ type(renderer, "st-magic-email", "ada@example.com")
135
+ await submit(renderer)
136
+
137
+ expect(sent).toHaveLength(1)
138
+ expect(sent[0]!.method).toBe("POST")
139
+ expect(sent[0]!.url.pathname).toBe("/auth/v1/otp")
140
+ expect(sent[0]!.url.searchParams.get("redirect_to")).toBe("https://app.example/")
141
+ expect(sent[0]!.body).toEqual({ email: "ada@example.com", create_user: true })
142
+ expect(onSuccess).toHaveBeenCalledWith("ada@example.com")
143
+ expect(textOf(renderer.root.findByProps({ role: "status" }))).toBe("Check your email for the magic link.")
144
+ })
145
+
146
+ it("shows the server's refusal and calls onError", async () => {
147
+ stubFetch(422, { code: 422, error_code: "otp_disabled", msg: "Signups not allowed for otp" })
148
+ const onError = vi.fn()
149
+ const renderer = render(<MagicLinkForm onError={onError} />)
150
+ type(renderer, "st-magic-email", "ada@example.com")
151
+ await submit(renderer)
152
+
153
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ code: "otp_disabled" }))
154
+ expect(textOf(renderer.root.findByProps({ role: "alert" }))).toBe("Signups not allowed for otp")
155
+ })
156
+
157
+ it("puts each slot's class on the element it names", () => {
158
+ const root = render(<MagicLinkForm className="t-form" classNames={CLASS_NAMES} />).root
159
+ expect(classesOf(root, "form")).toEqual(["t-form"])
160
+ expect(classesOf(root, "h2")).toEqual(["t-title"])
161
+ expect(classesOf(root, "label")).toEqual(["t-label"])
162
+ expect(classesOf(root, "input")).toEqual(["t-input"])
163
+ expect(classesOf(root, "button")).toEqual(["t-submit"])
164
+ })
165
+ })
166
+
167
+ describe("UpdatePasswordForm", () => {
168
+ it("sets the new password with PUT /user on the recovery session, then says it is updated", async () => {
169
+ const sent = stubFetch(200, USER)
170
+ const onSuccess = vi.fn()
171
+ const renderer = render(<UpdatePasswordForm onSuccess={onSuccess} />, RECOVERY_SESSION)
172
+ type(renderer, "st-update-password", "a-new-password")
173
+ await submit(renderer)
174
+
175
+ expect(sent).toHaveLength(1)
176
+ expect(sent[0]!.method).toBe("PUT")
177
+ expect(sent[0]!.url.pathname).toBe("/auth/v1/user")
178
+ expect(sent[0]!.authorization).toBe("Bearer recovery-access-token")
179
+ expect(sent[0]!.body).toEqual({ password: "a-new-password" })
180
+ expect(onSuccess).toHaveBeenCalledWith(expect.objectContaining({ id: "user-1", email: "ada@example.com" }))
181
+ expect(textOf(renderer.root.findByProps({ role: "status" }))).toBe("Your password has been updated.")
182
+ })
183
+
184
+ it("shows the server's refusal and calls onError", async () => {
185
+ stubFetch(422, { code: 422, error_code: "weak_password", msg: "Password should be at least 8 characters." })
186
+ const onError = vi.fn()
187
+ const renderer = render(<UpdatePasswordForm onError={onError} />, RECOVERY_SESSION)
188
+ type(renderer, "st-update-password", "short")
189
+ await submit(renderer)
190
+
191
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ code: "weak_password" }))
192
+ expect(textOf(renderer.root.findByProps({ role: "alert" }))).toBe("Password should be at least 8 characters.")
193
+ })
194
+
195
+ it("says so without a request when there is no session to update", async () => {
196
+ const sent = stubFetch(200, USER)
197
+ const onError = vi.fn()
198
+ const renderer = render(<UpdatePasswordForm onError={onError} />)
199
+ type(renderer, "st-update-password", "a-new-password")
200
+ await submit(renderer)
201
+
202
+ expect(sent).toHaveLength(0)
203
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: "Not authenticated" }))
204
+ })
205
+
206
+ it("puts each slot's class on the element it names", () => {
207
+ const root = render(<UpdatePasswordForm className="t-form" classNames={CLASS_NAMES} />, RECOVERY_SESSION).root
208
+ expect(classesOf(root, "form")).toEqual(["t-form"])
209
+ expect(classesOf(root, "h2")).toEqual(["t-title"])
210
+ expect(classesOf(root, "label")).toEqual(["t-label"])
211
+ expect(classesOf(root, "input")).toEqual(["t-input"])
212
+ expect(classesOf(root, "button")).toEqual(["t-submit"])
213
+ })
214
+ })
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Rendering a form inside a provider over the real client, and driving it as a user would.
3
+ */
4
+
5
+ import React from "react"
6
+ import { act, create, type ReactTestInstance, type ReactTestRenderer } from "react-test-renderer"
7
+ import { createClient, type Session } from "@supatype/client"
8
+ import { SupatypeProvider } from "@supatype/react"
9
+ import { fire, stringProp } from "./props.js"
10
+
11
+ export const API = "http://localhost:9999"
12
+
13
+ /** Render `ui` inside a `SupatypeProvider` holding a real client, signed in when given a session. */
14
+ export function render(ui: React.ReactElement, session?: Session): ReactTestRenderer {
15
+ const client = createClient({ url: API, anonKey: "anon", ...(session !== undefined && { initialSession: session }) })
16
+ let renderer: ReactTestRenderer | null = null
17
+ act(() => { renderer = create(<SupatypeProvider client={client}>{ui}</SupatypeProvider>) })
18
+ return renderer!
19
+ }
20
+
21
+ /** Type `value` into the input with this id. */
22
+ export function type(renderer: ReactTestRenderer, id: string, value: string): void {
23
+ const input = renderer.root.find((node) => node.type === "input" && node.props["id"] === id)
24
+ act(() => { fire(input, "onChange", { target: { value } }) })
25
+ }
26
+
27
+ /** Submit the form and wait for its request to settle. */
28
+ export async function submit(renderer: ReactTestRenderer): Promise<void> {
29
+ const form = renderer.root.findByType("form")
30
+ await act(async () => { await fire(form, "onSubmit", { preventDefault: () => undefined }) })
31
+ }
32
+
33
+ /** The text inside a node, its children's included. */
34
+ export function textOf(node: ReactTestInstance): string {
35
+ return node.children.map((child) => (typeof child === "string" ? child : textOf(child))).join("")
36
+ }
37
+
38
+ /** The class on each element of this type, in order. */
39
+ export function classesOf(root: ReactTestInstance, type: keyof React.JSX.IntrinsicElements): Array<string | undefined> {
40
+ return root.findAllByType(type).map((node) => stringProp(node, "className"))
41
+ }