diff --git a/AGENTS.md b/AGENTS.md index e70ad7b12c..63f4d9fb6e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -75,12 +75,12 @@ The CLI binary is `lunora`. The npm scope is `@lunora/*`. The "main" server pack There is an unscoped **umbrella** package `lunorash` (directory `packages/lunora/`; npm name is `lunorash` because `lunora` is taken on npm, but the directory and CLI bin stay `lunora`). It re-exports the base packages (`@lunora/server` + subpaths, `@lunora/values`, `@lunora/runtime`, `@lunora/do`, `@lunora/client`) via subpaths (`lunorash/server`, …) and ships the `lunora` CLI bin. Codegen emits `lunorash/*` imports in `_generated/*` when a project declares a `lunorash` dependency (else `@lunora/*`) — opt-in and backward-compatible. Add-ons/adapters/Vite plugin stay separate installs. -**Platform family (plan 114).** Multi-platform support ships as exactly **two** packages: +**Platform family (plan 114).** Multi-platform support is split into a contracts package, a host-neutral engine, one host package per target, and extracted host-neutral telemetry: - `@lunora/platform` — **contracts** (types + capability matrix, zero deps): `ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`, `SchedulerHost`, the canonical binding `*Like` projections, `PlatformCapabilities`. The behavioural TCK lives at the `@lunora/platform/conformance` subpath (`/conformance/suite` is the workerd-safe pure suite; the barrel adds the `node:sqlite` reference host) — the TCK versions in lockstep with the contracts it asserts, and a subpath keeps the root import types-only. - `@lunora/shard-engine` — the host-neutral reactive engine (extracted from `@lunora/do`). - - `@lunora/platform-cloudflare` — the Cloudflare **host**: the contracts implemented over Durable Object primitives, plus the composition roots (`createShardPlatform` / `createWorkerPlatform`). `@lunora/do` depends on it and stays the Durable Object class itself; app code never imports it directly. +- `@lunora/platform-node` — a Node **host** spike (plan 234): no `lunora dev` wiring, no deploy driver, capabilities mostly `unsupported`/`emulated`; its public surface is still expected to move. Add it alongside `platform`/`platform-cloudflare` in the API-snapshot guard once it graduates past spike stage. - `@lunora/observability` — host-neutral telemetry (logs, metrics, traces, issues), also extracted from `@lunora/do`. Each host is its own `@lunora/platform-` package — never a subpath of the contracts package, since each carries its own provider deps. `@lunora/platform` stays zero-dependency. @@ -89,58 +89,63 @@ Each host is its own `@lunora/platform-` package — never a subpath of Concise roles below — read the package's `src/` and `docs/` for detail. Flags: **Internal** = supporting layer, depend on the CLI/Vite/runtime that uses it; **not published** = build-time only; **Experimental** = outside the 1.0 stability promise. -| Package | Role | -| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `lunorash` | **Unscoped umbrella** (dir `packages/lunora/`, npm `lunorash`, bin `lunora`). Re-exports the base packages via subpaths; codegen emits `lunorash/*` when depended on. | -| `@lunora/server` | Main API: `defineSchema`, `defineTable`, `query`, `mutation`, `action`; ships `ctx.secrets` (Cloudflare Secrets Store). | -| `@lunora/values` | `v.*` validators, return-type inference. | -| `@lunora/errors` | **Zero-dep** error layer: `LunoraError`, `ERROR_CATALOG`, guards, `invariant`/`unreachable`, `toErrorBody`. Terminal renderer lives in `@lunora/cli`. | -| `@lunora/runtime` | Worker entry: RPC router, shard resolver, query coordinator. | -| `@lunora/do` | `ShardDO` (SQLite, OCC, hibernated WS subscriptions) and `SessionDO`. | -| `@lunora/d1` | D1 adapter for `.global()` tables; wraps the Sessions API for read-your-writes. | -| `@lunora/codegen` | Emits `_generated/{api,server,dataModel}.ts` from `schema.ts`. | -| `@lunora/client` | Browser SDK: WebSocket, optimistic updates, offline queue. | -| `@lunora/react` | `useQuery` / `useMutation` / `useSubscription` / `useAuth`. | -| `@lunora/react-native` | React Native / Expo: re-exports `@lunora/react`, adds `createLunoraClient` + `@lunora/react-native/auth` better-auth Expo bridge. | -| `@lunora/vue` | Vue adapter: live composables, optimistic mutations, reactive loaders. | -| `@lunora/solid` | SolidJS adapter: live queries, optimistic mutations, reactive loaders. | -| `@lunora/svelte` | Svelte adapter: live stores, optimistic mutations, reactive loaders. | -| `@lunora/angular` | Angular signal-based adapter: `provideLunora` / `injectLunoraClient` / `liveQuery` / `mutate` / `connectionStatus`. | -| `@lunora/astro` | Astro integration: single-worker composition + reactive-loader server helpers. | -| `@lunora/nuxt` | Nuxt module: mounts Lunora inside Nitro; `@lunora/nuxt/server` reactive-loader helpers. | -| `@lunora/db` | TanStack DB binding: `defineCollections` → live indexed collections + durable offline outbox. | -| `@lunora/replica` | Local-first replica runtime: `EventSource`, `LocalMirror` (pluggable SQLite), `EventsSync`; SQLite adapters as subpath exports. | -| `@lunora/vite` | Vite plugin over `@cloudflare/vite-plugin`: codegen, wrangler validator, error overlay. | -| `@lunora/cli` | CLI subcommands: `init`, `dev`, `deploy`, `codegen`, `run`, `reset`, `migrate`. | -| `@lunora/auth` | Auth on **better-auth**, D1-backed; email/password + OAuth, session policies; curated plugins via `@lunora/auth/plugins`. | -| `@lunora/cloudflare-access` | Cloudflare Access (Zero Trust) identity → `ctx.auth` / RLS via a `resolveIdentity` adapter. | -| `@lunora/mail` | Resend adapter, TSX templates, queue-backed sends. | -| `@lunora/observability` | Host-neutral telemetry storage + read models: request logs, traces, metrics, issue grouping, security audit. Backs the Studio's observability pages; extracted from `@lunora/do`. | -| `@lunora/notify` | Multi-channel notifications: `ctx.notify`/`ctx.push` over `@visulima/notification`; Web Push + FCM, subscription stores + queue fan-out; `/web` browser subpath. | -| `@lunora/storage` | R2 typed buckets, signed URLs. | -| `@lunora/scheduler` | `runAfter` / `runAt` + Cron Triggers via `SchedulerDO`. | -| `@lunora/container` | Cloudflare Containers: `defineContainer` → container DO classes + typed `ctx.containers`; `@lunora/container/do` + `/bridge` subpaths. | -| `@lunora/agent` | Durable AI agents (add-on): `defineAgent` compiles a replay-safe tool-loop onto Cloudflare Workflows — tools (MCP/function/agent/sandbox), memory, HITL approvals, token streaming, telemetry. | -| `@lunora/ai` | Workers AI on Vercel AI SDK v7 → `ctx.ai`; `@lunora/ai/rag` ships `defineRag` (chunk→embed→Vectorize + retrieve). | -| `@lunora/flags` | OpenFeature feature flags: `defineFlags` → `ctx.flags`; `useFlag`/`useFlags` client hooks; read-only Studio page. | -| `@lunora/advisor` | Schema & query lints (splinter-style) feeding the Studio Advisors pages (~81 static rules + runtime lints). | -| `@lunora/config` | **Internal.** Shared CLI+Vite config/scaffolding: `wrangler.jsonc` validator, `.dev.vars` grammar/scaffolder, prompt helper. | -| `@lunora/search-core` | **Internal, not published** (bundled into server/do/sql-store). The shared full-text search core: analyzer, tokenizer, scorer, caps, cursor algebra, backfill policy. | -| `@lunora/sql-store` | **Internal.** Dialect-parameterized SQL store core for `.global()` backends (D1, PlanetScale). | -| `@lunora/studio` | Local admin UI for schema, data, logs, and advisors. Embedded by the CLI/Vite. | -| `@lunora/mcp` | MCP server exposing a Lunora deployment to AI agents; can front durable `@lunora/agent` runs (config-gated, fail-closed). | -| `@lunora/ratelimit` | Rate limiting: token-bucket / fixed-window / sliding-window, deny list, sharding, pluggable stores, procedure middleware. | -| `@lunora/testing` | Testing toolkit: `lunoraTest` in-memory harness, `agentHarness` double, `evaluate` scorers, mail-catcher helpers. | -| `@lunora/seed` | Deterministic seeding from `defineSchema` (FK-ordered fake data); `@lunora/seed/testing` + `lunora seed` CLI. | -| `@lunora/bindings` | Cloudflare binding helpers, per-binding subpaths: `/kv`, `/images`, `/analytics`, `/pipelines`, `/vectors`, `/r2sql` → `ctx.*` facades. | -| `@lunora/browser` | Cloudflare Browser Rendering: `ctx.browser` (action-only) — navigate, screenshot/PDF, scrape. | -| `@lunora/hyperdrive` | BYO Postgres/MySQL via Cloudflare Hyperdrive: driver-agnostic `ctx.sql` (action-only); node-postgres / postgres.js / mysql2 adapters. | -| `@lunora/payment` | Provider-agnostic payments: Stripe-first + Polar adapters, webhook sync, subscription state machine, entitlements, money helpers. | -| `@lunora/x402` | **Experimental.** Agentic payments (x402): charge agents per request (`/charge`) and pay x402-gated resources (`/pay`). | -| `@lunora/workflow` | Durable workflows over Cloudflare Workflows: `defineWorkflow` + generated `WorkflowEntrypoint` classes, `ctx.workflows`. | -| `@lunora/queue` | Cloudflare Queues: `defineQueue` → typed `ctx.queues.` producers + a generated `queue()` consumer (or `mode: "pull"`). | -| `@lunora/dispatch` | **Internal, not published** (bundled into queue/workflow). Shared dispatch runner calling a Lunora function from a server-initiated context. | -| `@lunora/fingerprint` | **Zero-dep** deterministic error-grouping (`fingerprintError` → stable 16-char hash); feeds the `getIssues` RPC + Studio Issues panel. | +| Package | Role | +| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `lunorash` | **Unscoped umbrella** (dir `packages/lunora/`, npm `lunorash`, bin `lunora`). Re-exports the base packages via subpaths; codegen emits `lunorash/*` when depended on. | +| `@lunora/server` | Main API: `defineSchema`, `defineTable`, `query`, `mutation`, `action`; ships `ctx.secrets` (Cloudflare Secrets Store). | +| `@lunora/values` | `v.*` validators, return-type inference. | +| `@lunora/errors` | **Zero-dep** error layer: `LunoraError`, `ERROR_CATALOG`, guards, `invariant`/`unreachable`, `toErrorBody`. Terminal renderer lives in `@lunora/cli`. | +| `@lunora/runtime` | Worker entry: RPC router, shard resolver, query coordinator. | +| `@lunora/do` | `ShardDO` (SQLite, OCC, hibernated WS subscriptions) and `SessionDO`. | +| `@lunora/platform` | Platform-family contracts (types + capability matrix, zero deps): `ShardHost`, `SocketHost`, `ShardDirectory`, `ShardKvStore`, `SchedulerHost`, the canonical binding `*Like` projections, `PlatformCapabilities`; behavioural TCK at `@lunora/platform/conformance`. | +| `@lunora/shard-engine` | Host-neutral reactive engine for the platform family (extracted from `@lunora/do`). | +| `@lunora/platform-cloudflare` | The Cloudflare host: `@lunora/platform` contracts implemented over Durable Object primitives, plus `createShardPlatform` / `createWorkerPlatform`. | +| `@lunora/platform-node` | **Experimental.** A Node host spike (plan 234) for the platform contracts — no `lunora dev` wiring, no deploy driver, capabilities mostly `unsupported`/`emulated`. | +| `@lunora/observability` | Host-neutral telemetry storage + read models: request logs, traces, metrics, issue grouping, security audit. Backs the Studio's observability pages; extracted from `@lunora/do`. | +| `@lunora/d1` | D1 adapter for `.global()` tables; wraps the Sessions API for read-your-writes. | +| `@lunora/codegen` | Emits `_generated/{api,server,dataModel}.ts` from `schema.ts`. | +| `@lunora/client` | Browser SDK: WebSocket, optimistic updates, offline queue. | +| `@lunora/react` | `useQuery` / `useMutation` / `useSubscription` / `useAuth`. | +| `@lunora/react-native` | React Native / Expo: re-exports `@lunora/react`, adds `createLunoraClient` + `@lunora/react-native/auth` better-auth Expo bridge. | +| `@lunora/vue` | Vue adapter: live composables, optimistic mutations, reactive loaders. | +| `@lunora/solid` | SolidJS adapter: live queries, optimistic mutations, reactive loaders. | +| `@lunora/svelte` | Svelte adapter: live stores, optimistic mutations, reactive loaders. | +| `@lunora/angular` | Angular signal-based adapter: `provideLunora` / `injectLunoraClient` / `liveQuery` / `mutate` / `connectionStatus`. | +| `@lunora/astro` | Astro integration: single-worker composition + reactive-loader server helpers. | +| `@lunora/nuxt` | Nuxt module: mounts Lunora inside Nitro; `@lunora/nuxt/server` reactive-loader helpers. | +| `@lunora/db` | TanStack DB binding: `defineCollections` → live indexed collections + durable offline outbox. | +| `@lunora/replica` | Local-first replica runtime: `EventSource`, `LocalMirror` (pluggable SQLite), `EventsSync`; SQLite adapters as subpath exports. | +| `@lunora/vite` | Vite plugin over `@cloudflare/vite-plugin`: codegen, wrangler validator, error overlay. | +| `@lunora/cli` | CLI subcommands: `init`, `dev`, `deploy`, `codegen`, `run`, `reset`, `migrate`. | +| `@lunora/auth` | Auth on **better-auth**, D1-backed; email/password + OAuth, session policies; curated plugins via `@lunora/auth/plugins`. | +| `@lunora/auth-ui` | **Internal, not published.** Source-of-truth for the copy-in, user-owned auth screens distributed via the `auth-ui-*` registry items; synced into `registry/auth-ui-/` by `scripts/sync-auth-ui-registry.mjs` (checked by `pnpm run lint:registry:sync`). | +| `@lunora/cloudflare-access` | Cloudflare Access (Zero Trust) identity → `ctx.auth` / RLS via a `resolveIdentity` adapter. | +| `@lunora/mail` | Resend adapter, TSX templates, queue-backed sends. | +| `@lunora/notify` | Multi-channel notifications: `ctx.notify`/`ctx.push` over `@visulima/notification`; Web Push + FCM, subscription stores + queue fan-out; `/web` browser subpath. | +| `@lunora/storage` | R2 typed buckets, signed URLs. | +| `@lunora/scheduler` | `runAfter` / `runAt` + Cron Triggers via `SchedulerDO`. | +| `@lunora/container` | Cloudflare Containers: `defineContainer` → container DO classes + typed `ctx.containers`; `@lunora/container/do` + `/bridge` subpaths. | +| `@lunora/agent` | Durable AI agents (add-on): `defineAgent` compiles a replay-safe tool-loop onto Cloudflare Workflows — tools (MCP/function/agent/sandbox), memory, HITL approvals, token streaming, telemetry. | +| `@lunora/ai` | Workers AI on Vercel AI SDK v7 → `ctx.ai`; `@lunora/ai/rag` ships `defineRag` (chunk→embed→Vectorize + retrieve). | +| `@lunora/flags` | OpenFeature feature flags: `defineFlags` → `ctx.flags`; `useFlag`/`useFlags` client hooks; read-only Studio page. | +| `@lunora/advisor` | Schema & query lints (splinter-style) feeding the Studio Advisors pages (~95 static rules at last count — see `STATIC_LINTS` in `packages/advisor/src/index.ts` for the live set — plus runtime lints). | +| `@lunora/config` | **Internal.** Shared CLI+Vite config/scaffolding: `wrangler.jsonc` validator, `.dev.vars` grammar/scaffolder, prompt helper. | +| `@lunora/search-core` | **Internal, not published** (bundled into server/do/sql-store). The shared full-text search core: analyzer, tokenizer, scorer, caps, cursor algebra, backfill policy. | +| `@lunora/sql-store` | **Internal.** Dialect-parameterized SQL store core for `.global()` backends (D1, PlanetScale). | +| `@lunora/studio` | Local admin UI for schema, data, logs, and advisors. Embedded by the CLI/Vite. | +| `@lunora/mcp` | MCP server exposing a Lunora deployment to AI agents; can front durable `@lunora/agent` runs (config-gated, fail-closed). | +| `@lunora/ratelimit` | Rate limiting: token-bucket / fixed-window / sliding-window, deny list, sharding, pluggable stores, procedure middleware. | +| `@lunora/testing` | Testing toolkit: `lunoraTest` in-memory harness, `agentHarness` double, `evaluate` scorers, mail-catcher helpers. | +| `@lunora/seed` | Deterministic seeding from `defineSchema` (FK-ordered fake data); `@lunora/seed/testing` + `lunora seed` CLI. | +| `@lunora/bindings` | Cloudflare binding helpers, per-binding subpaths: `/kv`, `/images`, `/analytics`, `/pipelines`, `/vectors`, `/r2sql` → `ctx.*` facades. | +| `@lunora/browser` | Cloudflare Browser Rendering: `ctx.browser` (action-only) — navigate, screenshot/PDF, scrape. | +| `@lunora/hyperdrive` | BYO Postgres/MySQL via Cloudflare Hyperdrive: driver-agnostic `ctx.sql` (action-only); node-postgres / postgres.js / mysql2 adapters. | +| `@lunora/payment` | Provider-agnostic payments: Stripe-first + Polar adapters, webhook sync, subscription state machine, entitlements, money helpers. | +| `@lunora/x402` | **Experimental.** Agentic payments (x402): charge agents per request (`/charge`) and pay x402-gated resources (`/pay`). | +| `@lunora/workflow` | Durable workflows over Cloudflare Workflows: `defineWorkflow` + generated `WorkflowEntrypoint` classes, `ctx.workflows`. | +| `@lunora/queue` | Cloudflare Queues: `defineQueue` → typed `ctx.queues.` producers + a generated `queue()` consumer (or `mode: "pull"`). | +| `@lunora/dispatch` | **Internal, not published** (bundled into queue/workflow). Shared dispatch runner calling a Lunora function from a server-initiated context. | +| `@lunora/fingerprint` | **Zero-dep** deterministic error-grouping (`fingerprintError` → stable 16-char hash); feeds the `getIssues` RPC + Studio Issues panel. | ### Layout diff --git a/api-snapshots/auth-ui.api.md b/api-snapshots/auth-ui.api.md new file mode 100644 index 0000000000..ed2c7c7ce9 --- /dev/null +++ b/api-snapshots/auth-ui.api.md @@ -0,0 +1,10128 @@ +# `@lunora/auth-ui` — public API + +- Package: `packages/auth-ui` +- Tier: stable-adapter + +Generated by `pnpm run api:update` from the built `dist` types; verified by +`pnpm run api:check` (CI: Lint / api-surface). Do not edit by hand — a diff +here is a public-API change and must be reviewed as one (SemVer applies). + +## `@lunora/auth-ui/core` + +### `ACCEPTED_TYPES` (const) + +```ts +const ACCEPTED_TYPES = new Set(["image/avif", "image/gif", "image/jpeg", "image/png", "image/webp"]); +``` + +### `ACCEPT_ATTRIBUTE` (const) + +```ts +const ACCEPT_ATTRIBUTE = [...ACCEPTED_TYPES].join(","); +``` + +### `AcceptInvitationActions` (interface) + +```ts +interface AcceptInvitationActions { + accept: () => Promise; + load: () => Promise; + reject: () => Promise; +} +``` + +### `AcceptInvitationController` (type) + +```ts +type AcceptInvitationController = Controller; +``` + +### `AcceptInvitationOptions` (interface) + +```ts +interface AcceptInvitationOptions { + autoLoad?: boolean; + invitationId?: string; +} +``` + +### `AcceptInvitationState` (interface) + +```ts +interface AcceptInvitationState { + error?: string; + invitation?: AuthInvitationDetail; + loading: boolean; + status: FlowStatus; +} +``` + +### `AccountsActions` (interface) + +```ts +interface AccountsActions { + link: (provider: string) => Promise; + refetch: () => Promise; + unlink: (providerId: string, accountId?: string) => Promise; +} +``` + +### `AccountsController` (type) + +```ts +type AccountsController = Controller, AccountsActions>; +``` + +### `ActiveMemberActions` (interface) + +```ts +interface ActiveMemberActions { + refetch: () => Promise; +} +``` + +### `ActiveMemberController` (type) + +```ts +type ActiveMemberController = Controller; +``` + +### `ActiveMemberState` (interface) + +```ts +interface ActiveMemberState { + error?: string; + loading: boolean; + role?: string; + status: FlowStatus; +} +``` + +### `AdminUsersActions` (interface) + +```ts +interface AdminUsersActions { + ban: (userId: string, reason?: string) => Promise; + impersonate: (userId: string) => Promise; + refetch: () => Promise; + remove: (userId: string) => Promise; + setRole: (userId: string, role: string) => Promise; + setSearch: (value: string) => Promise; + stopImpersonating: () => Promise; + unban: (userId: string) => Promise; +} +``` + +### `AdminUsersController` (type) + +```ts +type AdminUsersController = Controller; +``` + +### `AdminUsersOptions` (interface) + +```ts +interface AdminUsersOptions { + autoLoad?: boolean; + debounceMs?: number; + limit?: number; +} +``` + +### `AdminUsersState` (type) + +```ts +type AdminUsersState = ResourceState; +``` + +### `AuthAccount` (interface) + +```ts +interface AuthAccount { + accountId?: string; + createdAt?: Date | string; + id?: string; + providerId?: string; + scopes?: string[]; +} +``` + +### `AuthActionError` (class) + +```ts +class AuthActionError extends Error { + public readonly code?: string; + public readonly status?: number; + public constructor(error: AuthFetchError) { + super(error.message ?? error.statusText ?? "Authentication request failed"); + this.name = "AuthActionError"; + this.code = error.code; + this.status = error.status; + } +} +``` + +### `AuthAdminUser` (interface) + +```ts +interface AuthAdminUser extends AuthUser { + banExpires?: Date | string; + banned?: boolean; + banReason?: string; + createdAt?: Date | string; + role?: string; +} +``` + +### `AuthClient` (interface) + +```ts +interface AuthClient { + admin: { + banUser: (input: { + banExpiresIn?: number; + banReason?: string; + userId: string; + }) => Promise>; + impersonateUser: (input: { + userId: string; + }) => Promise>; + listUsers: (input?: { + query?: { + limit?: number; + offset?: number; + searchField?: string; + searchOperator?: string; + searchValue?: string; + }; + }) => Promise>; + removeUser: (input: { + userId: string; + }) => Promise>; + setRole: (input: { + role: string; + userId: string; + }) => Promise>; + stopImpersonating: () => Promise>; + unbanUser: (input: { + userId: string; + }) => Promise>; + }; + changeEmail: (input: { + callbackURL?: string; + newEmail: string; + }) => Promise>; + changePassword: (input: { + currentPassword: string; + newPassword: string; + revokeOtherSessions?: boolean; + }) => Promise>; + deleteUser: (input: { + callbackURL?: string; + password?: string; + }) => Promise>; + device: { + approve: (input: { + userCode: string; + }) => Promise>; + deny: (input: { + userCode: string; + }) => Promise>; + }; + emailOtp: { + resetPassword: (input: { + email: string; + otp: string; + password: string; + }) => Promise>; + sendVerificationOtp: (input: { + email: string; + type: "email-verification" | "forget-password" | "sign-in"; + }) => Promise>; + }; + forgetPassword: (input: { + email: string; + redirectTo?: string; + }) => Promise>; + getSession: () => Promise>; + isUsernameAvailable: (input: { + username: string; + }) => Promise>; + linkSocial: (input: { + callbackURL?: string; + provider: string; + }) => Promise>; + listAccounts: () => Promise>; + listSessions: () => Promise>; + multiSession: { + listDeviceSessions: () => Promise>; + revoke: (input: { + sessionToken: string; + }) => Promise>; + setActive: (input: { + sessionToken: string; + }) => Promise>; + }; + oauth2: { + consent: (input: { + accept: boolean; + scope?: string; + }) => Promise>; + deleteConsent: (input: { + id: string; + }) => Promise>; + getConsent: (input: { + query: { + id: string; + }; + }) => Promise>; + getConsents: () => Promise>; + }; + oneTap: (input?: { + callbackURL?: string; + }) => Promise>; + organization: { + acceptInvitation: (input: { + invitationId: string; + }) => Promise>; + cancelInvitation: (input: { + invitationId: string; + }) => Promise>; + create: (input: { + name: string; + slug: string; + }) => Promise>; + createTeam: (input: { + name: string; + organizationId?: string; + }) => Promise>; + delete: (input: { + organizationId: string; + }) => Promise>; + getFullOrganization: (input?: { + organizationId?: string; + }) => Promise>; + getInvitation: (input: { + query: { + id: string; + }; + }) => Promise>; + inviteMember: (input: { + email: string; + organizationId?: string; + role: string; + teamId?: string; + }) => Promise>; + leave: (input: { + organizationId: string; + }) => Promise>; + list: () => Promise>; + listTeams: (input?: { + query?: { + organizationId?: string; + }; + }) => Promise>; + listUserInvitations: () => Promise>; + rejectInvitation: (input: { + invitationId: string; + }) => Promise>; + removeMember: (input: { + memberIdOrEmail: string; + organizationId?: string; + }) => Promise>; + removeTeam: (input: { + organizationId?: string; + teamId: string; + }) => Promise>; + setActive: (input: { + organizationId: string; + }) => Promise>; + update: (input: { + data: { + logo?: string; + name?: string; + slug?: string; + }; + organizationId?: string; + }) => Promise>; + updateMemberRole: (input: { + memberId: string; + organizationId?: string; + role: string; + }) => Promise>; + updateTeam: (input: { + data: { + name?: string; + }; + teamId: string; + }) => Promise>; + }; + passkey: { + addPasskey: (input?: { + authenticatorAttachment?: "cross-platform" | "platform"; + name?: string; + }) => Promise; + deletePasskey: (input: { + id: string; + }) => Promise>; + listUserPasskeys: () => Promise>; + updatePasskey: (input: { + id: string; + name: string; + }) => Promise>; + }; + phoneNumber: { + requestPasswordReset: (input: { + phoneNumber: string; + }) => Promise>; + resetPassword: (input: { + newPassword: string; + otp: string; + phoneNumber: string; + }) => Promise>; + sendOtp: (input: { + phoneNumber: string; + }) => Promise>; + verify: (input: { + code: string; + disableSession?: boolean; + phoneNumber: string; + updatePhoneNumber?: boolean; + }) => Promise>; + }; + resetPassword: (input: { + newPassword: string; + token?: string; + }) => Promise>; + revokeOtherSessions: () => Promise>; + revokeSession: (input: { + token: string; + }) => Promise>; + sendVerificationEmail: (input: { + callbackURL?: string; + email: string; + }) => Promise>; + signIn: { + anonymous: () => Promise>; + email: (input: { + callbackURL?: string; + email: string; + password: string; + rememberMe?: boolean; + }) => Promise>; + emailOtp: (input: { + email: string; + otp: string; + }) => Promise>; + magicLink: (input: { + callbackURL?: string; + email: string; + }) => Promise>; + phoneNumber: (input: { + password: string; + phoneNumber: string; + rememberMe?: boolean; + }) => Promise>; + social: (input: { + callbackURL?: string; + provider: string; + }) => Promise>; + username: (input: { + password: string; + rememberMe?: boolean; + username: string; + }) => Promise>; + }; + signOut: () => Promise>; + signUp: { + email: (input: { + callbackURL?: string; + email: string; + name: string; + password: string; + username?: string; + }) => Promise>; + }; + twoFactor: { + disable: (input: { + password: string; + }) => Promise>; + enable: (input: { + password: string; + }) => Promise>; + generateBackupCodes: (input: { + password: string; + }) => Promise>; + verifyBackupCode: (input: { + code: string; + trustDevice?: boolean; + }) => Promise>; + verifyOtp: (input: { + code: string; + trustDevice?: boolean; + }) => Promise>; + verifyTotp: (input: { + code: string; + trustDevice?: boolean; + }) => Promise>; + }; + unlinkAccount: (input: { + accountId?: string; + providerId: string; + }) => Promise>; + updateUser: (input: { + image?: string; + name?: string; + username?: string; + }) => Promise>; + verifyEmail: (input: { + query: { + token: string; + }; + }) => Promise>; +} +``` + +### `AuthDeviceRequest` (interface) + +```ts +interface AuthDeviceRequest { + clientId?: string; + scope?: string; + userCode?: string; +} +``` + +### `AuthDeviceSession` (interface) + +```ts +interface AuthDeviceSession { + session?: AuthSession; + user?: AuthUser; +} +``` + +### `AuthFetchError` (interface) + +```ts +interface AuthFetchError { + code?: string; + message?: string; + status?: number; + statusText?: string; +} +``` + +### `AuthFullOrganization` (interface) + +```ts +interface AuthFullOrganization extends AuthOrganization { + invitations?: AuthInvitation[]; + members?: AuthMember[]; +} +``` + +### `AuthInvitation` (interface) + +```ts +interface AuthInvitation { + email?: string; + id?: string; + role?: string; + status?: string; +} +``` + +### `AuthInvitationDetail` (interface) + +```ts +interface AuthInvitationDetail extends AuthInvitation { + expiresAt?: Date | string; + inviterEmail?: string; + organizationName?: string; + organizationSlug?: string; +} +``` + +### `AuthMember` (interface) + +```ts +interface AuthMember { + id?: string; + role?: string; + user?: { + email?: string; + name?: string; + }; + userId?: string; +} +``` + +### `AuthOrganization` (interface) + +```ts +interface AuthOrganization { + id?: string; + logo?: string; + name?: string; + slug?: string; +} +``` + +### `AuthPasskey` (interface) + +```ts +interface AuthPasskey { + createdAt?: Date | string; + deviceType?: string; + id?: string; + name?: string; +} +``` + +### `AuthResponse` (interface) + +```ts +interface AuthResponse { + data: T | null; + error: AuthFetchError | null; +} +``` + +### `AuthSession` (interface) + +```ts +interface AuthSession { + createdAt?: string; + id?: string; + ipAddress?: string; + token?: string; + userAgent?: string; +} +``` + +### `AuthTeam` (interface) + +```ts +interface AuthTeam { + id?: string; + name?: string; + organizationId?: string; +} +``` + +### `AuthUIConfig` (interface) + +```ts +interface AuthUIConfig { + authClient: AnyAuthClient; + avatar?: AvatarConfig; + basePath?: string; + discover?: boolean; + forgotPassword?: { + method?: "link" | "otp"; + }; + localization?: Partial; + nav: NavAdapter; + onError?: (error: unknown) => void; + onSessionChange?: () => void; + organization?: { + roles?: boolean; + showSlug?: boolean; + teams?: boolean; + }; + password?: PasswordPolicy; + plugins?: PluginFlags; + redirects?: RedirectConfig; + social?: ReadonlyArray; + theme?: (defaults: ThemeTokens) => ThemeTokens; + viewPaths?: ViewPaths; +} +``` + +### `AuthUser` (interface) + +```ts +interface AuthUser { + email?: string; + emailVerified?: boolean; + id?: string; + image?: string; + name?: string; +} +``` + +### `AuthorizedAppsActions` (interface) + +```ts +interface AuthorizedAppsActions { + refetch: () => Promise; + revoke: (consentId: string) => Promise; +} +``` + +### `AuthorizedAppsController` (type) + +```ts +type AuthorizedAppsController = Controller, AuthorizedAppsActions>; +``` + +### `AvailabilityStatus` (type) + +```ts +type AvailabilityStatus = "available" | "checking" | "idle" | "taken" | "unknown"; +``` + +### `AvatarConfig` (interface) + +```ts +interface AvatarConfig { + maxSize?: number; + upload?: (file: File) => Promise; +} +``` + +### `AvatarUploadActions` (interface) + +```ts +interface AvatarUploadActions { + remove: () => Promise; + upload: (file: File) => Promise; +} +``` + +### `AvatarUploadController` (type) + +```ts +type AvatarUploadController = Controller; +``` + +### `AvatarUploadState` (interface) + +```ts +interface AvatarUploadState { + error?: string; + imageUrl?: string; + status: FlowStatus; +} +``` + +### `BackupCodeSignInField` (type) + +```ts +type BackupCodeSignInField = "code"; +``` + +### `BackupCodesField` (type) + +```ts +type BackupCodesField = "password"; +``` + +### `BackupCodesHandle` (interface) + +```ts +interface BackupCodesHandle { + controller: FormController; + getCodes: () => ReadonlyArray; + subscribeCodes: (onChange: () => void) => () => void; +} +``` + +### `CAPTCHA_HEADER` (const) + +```ts +const CAPTCHA_HEADER = "x-captcha-response"; +``` + +### `CAPTCHA_PROVIDERS` (const) + +```ts +const PROVIDERS: Readonly> = { + captchafox: { global: "CaptchaFox", script: "https://cdn.captchafox.com/api.js?render=explicit" }, + "cloudflare-turnstile": { global: "turnstile", script: "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit" }, + "google-recaptcha": { global: "grecaptcha", script: "https://www.google.com/recaptcha/api.js?render=explicit" }, + hcaptcha: { global: "hcaptcha", script: "https://js.hcaptcha.com/1/api.js?render=explicit" }, +}; +``` + +### `CaptchaProvider` (type) + +```ts +type CaptchaProvider = "captchafox" | "cloudflare-turnstile" | "google-recaptcha" | "hcaptcha"; +``` + +### `ChangeEmailField` (type) + +```ts +type ChangeEmailField = "newEmail"; +``` + +### `ChangePasswordField` (type) + +```ts +type ChangePasswordField = "confirmPassword" | "currentPassword" | "newPassword"; +``` + +### `ConsentActions` (interface) + +```ts +interface ConsentActions { + accept: () => Promise; + deny: () => Promise; + load: () => Promise; +} +``` + +### `ConsentController` (type) + +```ts +type ConsentController = Controller; +``` + +### `ConsentOptions` (interface) + +```ts +interface ConsentOptions { + autoLoad?: boolean; + consentId?: string; +} +``` + +### `ConsentState` (interface) + +```ts +interface ConsentState { + error?: string; + loading: boolean; + request?: OAuthPendingConsent; + status: FlowStatus; +} +``` + +### `Controller` (interface) + +```ts +interface Controller { + actions: TActions; + destroy: () => void; + getState: () => TState; + subscribe: (onChange: () => void) => () => void; +} +``` + +### `ControllerContext` (interface) + +```ts +interface ControllerContext { + authClient: AuthClient; + avatar: AvatarConfig; + basePath: string; + credentials: boolean; + forgotPasswordMethod: "link" | "otp"; + localization: Localization; + nav: NavAdapter; + onError?: (error: unknown) => void; + onSessionChange?: () => void; + organization: { + allowUserToCreate: boolean; + invitationLimit?: number; + limit?: number; + membershipLimit?: number; + roles: boolean; + showSlug: boolean; + teams: boolean; + }; + password: PasswordPolicy; + plugins: Required; + redirects: Required; + signUp: boolean; + social: ReadonlyArray; + themeVariables: Readonly>; + viewPaths: Required; +} +``` + +### `DEFAULT_AVATAR_MAX_SIZE` (const) + +```ts +const DEFAULT_AVATAR_MAX_SIZE = 2 * 1024 * 1024; +``` + +### `DEFAULT_BASE_PATH` (const) + +```ts +const DEFAULT_BASE_PATH = "/api/auth"; +``` + +### `DEFAULT_LOCALIZATION` (const) + +```ts +const DEFAULT_LOCALIZATION: Localization = { + accountsEmpty: "No accounts linked yet.", + accountsLastOne: "You can't unlink your only sign-in method.", + accountsLink: "Link account", + accountsTitle: "Linked accounts", + activeBadge: "Active", + adminBan: "Ban", + adminImpersonate: "Impersonate", + adminSearch: "Search users by email", + adminStopImpersonating: "Stop impersonating", + adminTitle: "Users", + adminUnban: "Unban", + adminUsersEmpty: "No users match that search.", + anonymousSignIn: "Continue as guest", + appearance: "Appearance", + authorizedApps: "Authorized applications", + authorizedAppsEmpty: "You haven't authorized any applications.", + avatar: "Avatar", + avatarNoUploader: "Avatar uploads are not configured for this app.", + avatarRemove: "Remove photo", + avatarTooLarge: "That image is too large.", + avatarUpload: "Upload photo", + avatarUploadFailed: "Could not upload that image. Try again.", + avatarWrongType: "Choose a PNG, JPEG, WebP, GIF, or AVIF image.", + backToSignIn: "Back to sign in", + backupCodeLabel: "Backup code", + backupCodes: "Save these backup codes somewhere safe:", + backupCodeSignIn: "Use a backup code", + backupCodesRegenerate: "Regenerate backup codes", + backupCodesRegenerated: "New backup codes generated. The old ones no longer work.", + cancel: "Cancel", + changeEmail: "Change email", + changeEmailSent: "Check your new inbox to confirm the change.", + changePassword: "Change password", + changePasswordDone: "Your password has been changed.", + codeLabel: "Verification code", + confirmPasswordLabel: "Confirm password", + consentAllow: "Allow", + consentDeny: "Deny", + consentExpired: "This request is no longer valid. Start again from the application.", + consentMissing: "There's no authorization request to review.", + consentTitle: "Authorize application", + consentWants: "wants access to:", + copied: "Copied", + copy: "Copy", + createOrganization: "Create organization", + currentPasswordLabel: "Current password", + currentSession: "This device", + deleteAccount: "Delete account", + deleteAccountWarning: "This permanently deletes your account and cannot be undone.", + deviceApprove: "Approve", + deviceApproved: "Device approved. You can close this page.", + deviceCodeLabel: "Device code", + deviceCodeRequired: "Enter the code shown on your device.", + deviceDenied: "Device denied.", + deviceDeny: "Deny", + deviceFailed: "That code is not valid or has expired.", + deviceTitle: "Authorize device", + emailInvalid: "Enter a valid email address.", + emailLabel: "Email", + emailOtp: "Email me a code", + emailOtpSent: "We emailed you a one-time code.", + emailRequired: "Email is required.", + forgotPassword: "Reset password", + forgotPasswordLink: "Forgot your password?", + forgotPasswordSent: "If that email exists, a reset link is on its way.", + genericError: "Something went wrong. Please try again.", + haveAccount: "Already have an account? Sign in", + invitationAccept: "Accept invitation", + invitationMissing: "That invitation link is not valid or has expired.", + invitationReject: "Decline", + invitations: "Pending invitations", + invitationsEmpty: "No invitations waiting for you.", + invitationTitle: "You've been invited", + inviteEmailLabel: "Email to invite", + inviteMember: "Invite member", + lastUsed: "Last used", + leaveOrganization: "Leave organization", + magicLink: "Email me a link", + magicLinkSent: "Check your email for a sign-in link.", + members: "Members", + multiSessionEmpty: "No other accounts signed in on this device.", + multiSessionTitle: "Switch account", + nameLabel: "Name", + nameRequired: "Name is required.", + newEmailLabel: "New email", + newPasswordLabel: "New password", + noAccount: "Don't have an account? Sign up", + noOrganizations: "You're not in any organization yet.", + organizationCreateDisallowed: "Your account can't create organizations.", + organizationLimitReached: "You've reached the maximum number of organizations.", + organizationLogo: "Logo URL", + organizationName: "Organization name", + organizationNameRequired: "Organization name is required.", + organizations: "Organizations", + organizationSaved: "Organization settings saved.", + organizationSettings: "Organization settings", + organizationSlug: "Slug", + organizationSlugRequired: "Slug is required.", + otpRequired: "Enter the code we sent you.", + passkeyAdd: "Add a passkey", + passkeyName: "Passkey name", + passkeyRename: "Rename", + passkeys: "Passkeys", + passkeysEmpty: "No passkeys registered yet.", + passkeyUnnamed: "Unnamed passkey", + passwordLabel: "Password", + passwordMismatch: "Passwords do not match.", + passwordRequired: "Password is required.", + passwordRuleDigit: "At least one number", + passwordRuleLength: "At least {min} characters", + passwordRuleLowercase: "At least one lowercase letter", + passwordRuleSymbol: "At least one symbol", + passwordRuleUppercase: "At least one uppercase letter", + passwordTooLong: "Password must be at most {max} characters.", + passwordTooShort: "Password must be at least {min} characters.", + phoneLabel: "Phone number", + phoneOtpSent: "We texted you a code.", + phoneRequired: "Phone number is required.", + phoneVerified: "Phone number verified.", + phoneVerify: "Verify phone number", + profile: "Profile", + profileSaved: "Your profile has been updated.", + remove: "Remove", + resetPassword: "Set new password", + resetPasswordDone: "Your password has been updated. You can sign in now.", + resetPasswordOtpDescription: "Enter the code we emailed you, then choose a new password.", + revoke: "Revoke", + revokeAccess: "Revoke access", + revokeOthers: "Sign out other sessions", + roleLabel: "Role", + saveChanges: "Save changes", + sendNewCode: "Use a different email", + sessionNotFresh: "For your security, sign in again before making this change.", + sessions: "Active sessions", + sessionsEmpty: "No other active sessions.", + signIn: "Sign in", + signInFailed: "Could not sign you in. Check your details and try again.", + signInWith: "Continue with", + signOut: "Sign out", + signUp: "Create account", + signUpFailed: "Could not create your account. Try again.", + switchAccount: "Switch to this account", + switchOrganization: "Switch", + teamNameLabel: "Team name", + teams: "Teams", + teamsEmpty: "No teams yet.", + themeDark: "Dark", + themeLight: "Light", + themeSystem: "System", + twoFactor: "Verify", + twoFactorDisable: "Disable 2FA", + twoFactorEnable: "Enable 2FA", + twoFactorEnabled: "Two-factor authentication is on.", + twoFactorFailed: "That code is not valid. Try again.", + twoFactorNeedsPassword: "Set a password before turning on two-factor authentication.", + twoFactorScan: "Add this account to your authenticator app using the setup key below, then enter the 6-digit code it generates.", + twoFactorSecret: "Setup key:", + twoFactorSetup: "Two-factor authentication", + twoFactorUseAuthenticator: "Use your authenticator app instead", + unknownDevice: "Unknown device", + usernameAvailable: "That username is available.", + usernameChecking: "Checking…", + usernameLabel: "Username", + usernameRequired: "Username is required.", + usernameSaved: "Your username has been updated.", + usernameTaken: "That username is taken.", + verifyEmail: "Verify your email", + verifyEmailFailed: "We couldn't verify that link. Request a new one.", + verifyEmailNoToken: "This page needs a verification link to work.", + verifyEmailResend: "Send a new link", + verifyEmailSent: "Check your email for a verification link.", + verifyEmailVerifying: "Verifying your email…", +}; +``` + +### `DEFAULT_PASSWORD_POLICY` (const) + +```ts +const DEFAULT_PASSWORD_POLICY: Required> = { maxLength: 128, minLength: 8 }; +``` + +### `DEFAULT_THEME_TOKENS` (const) + +```ts +const DEFAULT_THEME_TOKENS: ThemeTokens = { + background: "hsl(0 0% 100%)", + border: "hsl(228 16% 88%)", + card: "hsl(0 0% 100%)", + cardForeground: "hsl(240 14% 10%)", + destructive: "hsl(0 72% 45%)", + fontMono: "ui-monospace, monospace", + fontSans: "ui-sans-serif, system-ui, sans-serif", + input: "hsl(228 16% 88%)", + muted: "hsl(228 16% 93%)", + mutedForeground: "hsl(235 9% 42%)", + primary: "hsl(240 14% 12%)", + primaryForeground: "hsl(228 32% 97%)", + radius: "0.5rem", + ring: "hsl(256 72% 68%)", + secondary: "hsl(228 16% 93%)", + secondaryForeground: "hsl(240 14% 14%)", + success: "hsl(160 60% 28%)", +}; +``` + +### `DeleteAccountField` (type) + +```ts +type DeleteAccountField = "password"; +``` + +### `DeviceAuthorizationActions` (interface) + +```ts +interface DeviceAuthorizationActions { + approve: () => Promise; + deny: () => Promise; + setCode: (value: string) => void; +} +``` + +### `DeviceAuthorizationController` (type) + +```ts +type DeviceAuthorizationController = Controller; +``` + +### `DeviceAuthorizationOptions` (interface) + +```ts +interface DeviceAuthorizationOptions { + userCode?: string; +} +``` + +### `DeviceAuthorizationState` (interface) + +```ts +interface DeviceAuthorizationState { + code: string; + decision?: "approved" | "denied"; + error?: string; + status: FlowStatus; +} +``` + +### `DeviceSessionsActions` (interface) + +```ts +interface DeviceSessionsActions { + refetch: () => Promise; + revoke: (sessionToken: string) => Promise; + setActive: (sessionToken: string) => Promise; +} +``` + +### `DeviceSessionsController` (type) + +```ts +type DeviceSessionsController = Controller, DeviceSessionsActions>; +``` + +### `DiscoveredConfig` (interface) + +```ts +interface DiscoveredConfig { + emailAndPassword: boolean; + organization?: DiscoveredOrganization; + plugins?: ReadonlyArray; + signUp: boolean; + socialProviders?: ReadonlyArray; +} +``` + +### `DiscoveredOrganization` (interface) + +```ts +interface DiscoveredOrganization { + allowUserToCreate: boolean; + enabled: boolean; + invitationLimit?: number; + limit?: number; + membershipLimit?: number; + roles: boolean; + teams: boolean; +} +``` + +### `DiscoveryHandle` (interface) + +```ts +interface DiscoveryHandle { + getState: () => DiscoveryState; + subscribe: (onChange: () => void) => () => void; +} +``` + +### `DiscoveryState` (interface) + +```ts +interface DiscoveryState { + config?: DiscoveredConfig; + status: DiscoveryStatus; +} +``` + +### `DiscoveryStatus` (type) + +```ts +type DiscoveryStatus = "loading" | "ready" | "unavailable"; +``` + +### `EmailOtpActions` (interface) + +```ts +interface EmailOtpActions { + back: () => void; + reset: () => void; + sendCode: () => Promise; + setCode: (value: string) => void; + setEmail: (value: string) => void; + verify: () => Promise; +} +``` + +### `EmailOtpController` (type) + +```ts +type EmailOtpController = Controller; +``` + +### `EmailOtpState` (interface) + +```ts +interface EmailOtpState { + code: FieldState; + email: FieldState; + formError?: string; + status: FlowStatus; + step: "request" | "verify"; + successMessage?: string; +} +``` + +### `FLOW_NAMES` (const) + +```ts +const FLOW_NAMES: ReadonlyArray = [ + "admin", + "anonymous", + "apiKey", + "deviceAuthorization", + "emailOtp", + "lastLoginMethod", + "magicLink", + "multiSession", + "oauthProvider", + "oneTap", + "organization", + "passkey", + "phoneNumber", + "twoFactor", + "username", +]; +``` + +### `FieldSpec` (interface) + +```ts +interface FieldSpec { + initial?: string; + validate?: (value: string, values: Record, localization: Localization) => string | undefined; +} +``` + +### `FieldState` (interface) + +```ts +interface FieldState { + error?: string; + touched: boolean; + value: string; +} +``` + +### `FlowName` (type) + +```ts +type FlowName = keyof PluginFlags; +``` + +### `FlowStatus` (type) + +```ts +type FlowStatus = "error" | "idle" | "submitting" | "success"; +``` + +### `ForgotPasswordField` (type) + +```ts +type ForgotPasswordField = "email"; +``` + +### `ForgotPasswordOptions` (interface) + +```ts +interface ForgotPasswordOptions { + resetPath?: string; +} +``` + +### `FormActions` (interface) + +```ts +interface FormActions { + blur: (field: TField) => void; + load: () => Promise; + reset: () => void; + setField: (field: TField, value: string) => void; + submit: () => Promise; +} +``` + +### `FormController` (type) + +```ts +type FormController = Controller, FormActions>; +``` + +### `FormControllerOptions` (interface) + +```ts +interface FormControllerOptions { + fallbackError: (localization: Localization) => string; + fields: Record>; + prefill?: (context: ControllerContext) => Promise>>; + sessionChanging?: boolean; + submit: (values: Record, context: ControllerContext) => Promise; +} +``` + +### `FormState` (interface) + +```ts +interface FormState { + fields: Record; + formError?: string; + loading: boolean; + status: FlowStatus; + successMessage?: string; +} +``` + +### `FormSubmitResult` (interface) + +```ts +interface FormSubmitResult { + redirectTo?: string; + successMessage?: string; +} +``` + +### `LAST_LOGIN_METHOD_COOKIE` (const) + +```ts +const LAST_LOGIN_METHOD_COOKIE = "better-auth.last_used_login_method"; +``` + +### `LAST_METHOD_EMAIL` (const) + +```ts +const LAST_METHOD_EMAIL = "email"; +``` + +### `LAST_METHOD_MAGIC_LINK` (const) + +```ts +const LAST_METHOD_MAGIC_LINK = "magic-link"; +``` + +### `LAST_METHOD_PASSKEY` (const) + +```ts +const LAST_METHOD_PASSKEY = "passkey"; +``` + +### `Localization` (interface) + +```ts +interface Localization { + accountsEmpty: string; + accountsLastOne: string; + accountsLink: string; + accountsTitle: string; + activeBadge: string; + adminBan: string; + adminImpersonate: string; + adminSearch: string; + adminStopImpersonating: string; + adminTitle: string; + adminUnban: string; + adminUsersEmpty: string; + anonymousSignIn: string; + appearance: string; + authorizedApps: string; + authorizedAppsEmpty: string; + avatar: string; + avatarNoUploader: string; + avatarRemove: string; + avatarTooLarge: string; + avatarUpload: string; + avatarUploadFailed: string; + avatarWrongType: string; + backToSignIn: string; + backupCodeLabel: string; + backupCodes: string; + backupCodeSignIn: string; + backupCodesRegenerate: string; + backupCodesRegenerated: string; + cancel: string; + changeEmail: string; + changeEmailSent: string; + changePassword: string; + changePasswordDone: string; + codeLabel: string; + confirmPasswordLabel: string; + consentAllow: string; + consentDeny: string; + consentExpired: string; + consentMissing: string; + consentTitle: string; + consentWants: string; + copied: string; + copy: string; + createOrganization: string; + currentPasswordLabel: string; + currentSession: string; + deleteAccount: string; + deleteAccountWarning: string; + deviceApprove: string; + deviceApproved: string; + deviceCodeLabel: string; + deviceCodeRequired: string; + deviceDenied: string; + deviceDeny: string; + deviceFailed: string; + deviceTitle: string; + emailInvalid: string; + emailLabel: string; + emailOtp: string; + emailOtpSent: string; + emailRequired: string; + forgotPassword: string; + forgotPasswordLink: string; + forgotPasswordSent: string; + genericError: string; + haveAccount: string; + invitationAccept: string; + invitationMissing: string; + invitationReject: string; + invitations: string; + invitationsEmpty: string; + invitationTitle: string; + inviteEmailLabel: string; + inviteMember: string; + lastUsed: string; + leaveOrganization: string; + magicLink: string; + magicLinkSent: string; + members: string; + multiSessionEmpty: string; + multiSessionTitle: string; + nameLabel: string; + nameRequired: string; + newEmailLabel: string; + newPasswordLabel: string; + noAccount: string; + noOrganizations: string; + organizationCreateDisallowed: string; + organizationLimitReached: string; + organizationLogo: string; + organizationName: string; + organizationNameRequired: string; + organizations: string; + organizationSaved: string; + organizationSettings: string; + organizationSlug: string; + organizationSlugRequired: string; + otpRequired: string; + passkeyAdd: string; + passkeyName: string; + passkeyRename: string; + passkeys: string; + passkeysEmpty: string; + passkeyUnnamed: string; + passwordLabel: string; + passwordMismatch: string; + passwordRequired: string; + passwordRuleDigit: string; + passwordRuleLength: string; + passwordRuleLowercase: string; + passwordRuleSymbol: string; + passwordRuleUppercase: string; + passwordTooLong: string; + passwordTooShort: string; + phoneLabel: string; + phoneOtpSent: string; + phoneRequired: string; + phoneVerified: string; + phoneVerify: string; + profile: string; + profileSaved: string; + remove: string; + resetPassword: string; + resetPasswordDone: string; + resetPasswordOtpDescription: string; + revoke: string; + revokeAccess: string; + revokeOthers: string; + roleLabel: string; + saveChanges: string; + sendNewCode: string; + sessionNotFresh: string; + sessions: string; + sessionsEmpty: string; + signIn: string; + signInFailed: string; + signInWith: string; + signOut: string; + signUp: string; + signUpFailed: string; + switchAccount: string; + switchOrganization: string; + teamNameLabel: string; + teams: string; + teamsEmpty: string; + themeDark: string; + themeLight: string; + themeSystem: string; + twoFactor: string; + twoFactorDisable: string; + twoFactorEnable: string; + twoFactorEnabled: string; + twoFactorFailed: string; + twoFactorNeedsPassword: string; + twoFactorScan: string; + twoFactorSecret: string; + twoFactorSetup: string; + twoFactorUseAuthenticator: string; + unknownDevice: string; + usernameAvailable: string; + usernameChecking: string; + usernameLabel: string; + usernameRequired: string; + usernameSaved: string; + usernameTaken: string; + verifyEmail: string; + verifyEmailFailed: string; + verifyEmailNoToken: string; + verifyEmailResend: string; + verifyEmailSent: string; + verifyEmailVerifying: string; +} +``` + +### `LogoUploadActions` (interface) + +```ts +interface LogoUploadActions { + remove: () => Promise; + upload: (file: File) => Promise; +} +``` + +### `LogoUploadController` (type) + +```ts +type LogoUploadController = Controller; +``` + +### `LogoUploadOptions` (interface) + +```ts +interface LogoUploadOptions { + initialLogo?: string; + organizationId?: string; +} +``` + +### `LogoUploadState` (interface) + +```ts +interface LogoUploadState { + error?: string; + logoUrl?: string; + status: FlowStatus; +} +``` + +### `MIN_PASSWORD_LENGTH` (const) + +```ts +const MIN_PASSWORD_LENGTH = 8; +``` + +### `MagicLinkField` (type) + +```ts +type MagicLinkField = "email"; +``` + +### `MembersActions` (interface) + +```ts +interface MembersActions { + cancelInvitation: (invitationId: string) => Promise; + invite: (email: string, role: string) => Promise; + refetch: () => Promise; + removeMember: (memberIdOrEmail: string) => Promise; + updateRole: (memberId: string, role: string) => Promise; +} +``` + +### `MembersController` (type) + +```ts +type MembersController = Controller; +``` + +### `MembersState` (interface) + +```ts +interface MembersState { + busy: boolean; + error?: string; + invitations: ReadonlyArray; + loading: boolean; + members: ReadonlyArray; +} +``` + +### `NON_SOCIAL_PROVIDERS` (const) + +```ts +const NON_SOCIAL_PROVIDERS = new Set(["credential", "email", "passkey"]); +``` + +### `NavAdapter` (interface) + +```ts +interface NavAdapter { + navigate: (to: string) => void; + replace: (to: string) => void; +} +``` + +### `OAuthConsent` (interface) + +```ts +interface OAuthConsent { + clientId?: string; + clientName?: string; + createdAt?: Date | string; + id?: string; + scopes?: string[]; +} +``` + +### `OAuthPendingConsent` (interface) + +```ts +interface OAuthPendingConsent { + clientId?: string; + clientName?: string; + clientURI?: string; + logoURI?: string; + scope?: string; +} +``` + +### `OrganizationSettingsField` (type) + +```ts +type OrganizationSettingsField = "logo" | "name" | "slug"; +``` + +### `OrganizationSettingsOptions` (interface) + +```ts +interface OrganizationSettingsOptions { + autoLoad?: boolean; + organizationId?: string; +} +``` + +### `OrganizationsActions` (interface) + +```ts +interface OrganizationsActions { + create: (name: string, slug: string) => Promise; + leave: (organizationId: string) => Promise; + refetch: () => Promise; + remove: (organizationId: string) => Promise; + setActive: (organizationId: string) => Promise; +} +``` + +### `OrganizationsController` (type) + +```ts +type OrganizationsController = Controller, OrganizationsActions>; +``` + +### `PLUGIN_ID_TO_FLOW` (const) + +```ts +const PLUGIN_ID_TO_FLOW: Readonly> = { + admin: "admin", + anonymous: "anonymous", + "device-authorization": "deviceAuthorization", + "email-otp": "emailOtp", + "last-login-method": "lastLoginMethod", + "magic-link": "magicLink", + "multi-session": "multiSession", + "oauth-provider": "oauthProvider", + "one-tap": "oneTap", + organization: "organization", + passkey: "passkey", + "phone-number": "phoneNumber", + "two-factor": "twoFactor", + username: "username", +}; +``` + +### `PREFILLABLE` (const) + +```ts +const PREFILLABLE = new Set(["email", "name", "username"]); +``` + +### `PasskeysActions` (interface) + +```ts +interface PasskeysActions { + add: (name?: string) => Promise; + refetch: () => Promise; + remove: (id: string) => Promise; + rename: (id: string, name: string) => Promise; +} +``` + +### `PasskeysController` (type) + +```ts +type PasskeysController = Controller, PasskeysActions>; +``` + +### `PasswordPolicy` (interface) + +```ts +interface PasswordPolicy { + maxLength?: number; + minLength?: number; + requireDigit?: boolean; + requireLowercase?: boolean; + requireSymbol?: boolean; + requireUppercase?: boolean; +} +``` + +### `PasswordRequirement` (interface) + +```ts +interface PasswordRequirement { + label: string; + met: boolean; +} +``` + +### `PhoneForgotPasswordField` (type) + +```ts +type PhoneForgotPasswordField = "phoneNumber"; +``` + +### `PhoneResetPasswordField` (type) + +```ts +type PhoneResetPasswordField = "confirmPassword" | "newPassword" | "otp" | "phoneNumber"; +``` + +### `PhoneSignInField` (type) + +```ts +type PhoneSignInField = "password" | "phoneNumber"; +``` + +### `PhoneVerifyActions` (interface) + +```ts +interface PhoneVerifyActions { + restart: () => void; + send: (phoneNumber: string) => Promise; + verify: (code: string) => Promise; +} +``` + +### `PhoneVerifyController` (type) + +```ts +type PhoneVerifyController = Controller; +``` + +### `PhoneVerifyOptions` (interface) + +```ts +interface PhoneVerifyOptions { + updatePhoneNumber?: boolean; +} +``` + +### `PhoneVerifyState` (interface) + +```ts +interface PhoneVerifyState { + error?: string; + phoneNumber: string; + status: FlowStatus; + step: "request" | "verify"; + successMessage?: string; +} +``` + +### `PluginFlags` (interface) + +```ts +interface PluginFlags { + admin?: boolean; + anonymous?: boolean; + apiKey?: boolean; + deviceAuthorization?: boolean; + emailOtp?: boolean; + lastLoginMethod?: boolean; + magicLink?: boolean; + multiSession?: boolean; + oauthProvider?: boolean; + oneTap?: boolean; + organization?: boolean; + passkey?: boolean; + phoneNumber?: boolean; + twoFactor?: boolean; + username?: boolean; +} +``` + +### `ProfileField` (type) + +```ts +type ProfileField = "image" | "name"; +``` + +### `ProfileOptions` (interface) + +```ts +interface ProfileOptions { + initialImage?: string; + initialName?: string; +} +``` + +### `ROLE_OPTIONS` (const) + +```ts +const ROLE_OPTIONS: ReadonlyArray = ["member", "admin", "owner"]; +``` + +### `RedirectConfig` (interface) + +```ts +interface RedirectConfig { + afterSignIn?: string; + afterSignOut?: string; + signIn?: string; + twoFactor?: string; +} +``` + +### `RenderCaptchaOptions` (interface) + +```ts +interface RenderCaptchaOptions { + onError?: (error: unknown) => void; + provider: CaptchaProvider; + siteKey: string; +} +``` + +### `ResendVerificationField` (type) + +```ts +type ResendVerificationField = "email"; +``` + +### `ResetPasswordField` (type) + +```ts +type ResetPasswordField = "confirmPassword" | "password"; +``` + +### `ResetPasswordOptions` (interface) + +```ts +interface ResetPasswordOptions { + token?: string; +} +``` + +### `ResetPasswordOtpField` (type) + +```ts +type ResetPasswordOtpField = "confirmPassword" | "email" | "otp" | "password"; +``` + +### `ResourceHandle` (interface) + +```ts +interface ResourceHandle> { + destroy: () => void; + getState: () => ResourceState; + mutate: (run: () => Promise) => Promise; + mutateOk: (run: () => Promise) => Promise; + patch: (extra: Partial) => void; + refetch: () => Promise; + subscribe: (onChange: () => void) => () => void; +} +``` + +### `ResourceOptions` (interface) + +```ts +interface ResourceOptions> { + autoLoad?: boolean; + initialExtra?: TExtra; +} +``` + +### `ResourceState` (interface) + +```ts +interface ResourceState> { + busy: boolean; + error?: string; + extra: TExtra; + items: ReadonlyArray; + loading: boolean; + status: FlowStatus; +} +``` + +### `SCOPE_LABELS` (const) + +```ts +const SCOPE_LABELS: Readonly> = { + email: "Your email address", + offline_access: "Access while you're away", + openid: "Your identity", + profile: "Your name and picture", +}; +``` + +### `SessionActions` (interface) + +```ts +interface SessionActions { + refetch: () => Promise; +} +``` + +### `SessionController` (type) + +```ts +type SessionController = Controller; +``` + +### `SessionData` (interface) + +```ts +interface SessionData { + session?: AuthSession; + token?: string; + twoFactorRedirect?: boolean; + user?: AuthUser; +} +``` + +### `SessionState` (interface) + +```ts +interface SessionState { + error?: string; + loading: boolean; + settled: boolean; + status: FlowStatus; + user?: AuthUser; +} +``` + +### `SessionsActions` (interface) + +```ts +interface SessionsActions { + refetch: () => Promise; + revoke: (token: string) => Promise; + revokeOthers: () => Promise; +} +``` + +### `SessionsController` (type) + +```ts +type SessionsController = Controller, SessionsActions>; +``` + +### `SetUsernameField` (type) + +```ts +type SetUsernameField = "username"; +``` + +### `SignInField` (type) + +```ts +type SignInField = "email" | "password"; +``` + +### `SignUpField` (type) + +```ts +type SignUpField = "email" | "name" | "password"; +``` + +### `Store` (interface) + +```ts +interface Store { + clear: () => void; + get: () => T; + set: (next: T) => void; + subscribe: (onChange: () => void) => () => void; + update: (patch: Partial) => void; +} +``` + +### `THEME_MODES` (const) + +```ts +const THEME_MODES: ReadonlyArray = ["system", "light", "dark"]; +``` + +### `THEME_STORAGE_KEY` (const) + +```ts +const THEME_STORAGE_KEY = "lunora-theme"; +``` + +### `TOAST_DURATION_MS` (const) + +```ts +const TOAST_DURATION_MS = 6000; +``` + +### `TeamsActions` (interface) + +```ts +interface TeamsActions { + create: (name: string) => Promise; + refetch: () => Promise; + remove: (teamId: string) => Promise; + rename: (teamId: string, name: string) => Promise; +} +``` + +### `TeamsController` (type) + +```ts +type TeamsController = Controller, TeamsActions>; +``` + +### `TeamsOptions` (interface) + +```ts +interface TeamsOptions { + autoLoad?: boolean; + organizationId?: string; +} +``` + +### `ThemeMode` (type) + +```ts +type ThemeMode = "dark" | "light" | "system"; +``` + +### `ThemeModeActions` (interface) + +```ts +interface ThemeModeActions { + setMode: (mode: ThemeMode) => void; +} +``` + +### `ThemeModeController` (type) + +```ts +type ThemeModeController = Controller; +``` + +### `ThemeModeOptions` (interface) + +```ts +interface ThemeModeOptions { + apply?: (mode: ThemeMode, resolved: "dark" | "light") => void; + persist?: boolean; +} +``` + +### `ThemeModeState` (interface) + +```ts +interface ThemeModeState { + mode: ThemeMode; + resolved: "dark" | "light"; +} +``` + +### `ThemeTokens` (interface) + +```ts +interface ThemeTokens { + background: string; + border: string; + card: string; + cardForeground: string; + destructive: string; + fontMono: string; + fontSans: string; + input: string; + muted: string; + mutedForeground: string; + primary: string; + primaryForeground: string; + radius: string; + ring: string; + secondary: string; + secondaryForeground: string; + success: string; +} +``` + +### `Toast` (interface) + +```ts +interface Toast { + id: number; + message: string; +} +``` + +### `ToastState` (interface) + +```ts +interface ToastState { + toasts: ReadonlyArray; +} +``` + +### `TwoFactorField` (type) + +```ts +type TwoFactorField = "code"; +``` + +### `TwoFactorSetupActions` (interface) + +```ts +interface TwoFactorSetupActions { + disable: () => Promise; + enable: () => Promise; + reset: () => void; + setCode: (value: string) => void; + setPassword: (value: string) => void; + verify: () => Promise; +} +``` + +### `TwoFactorSetupController` (type) + +```ts +type TwoFactorSetupController = Controller; +``` + +### `TwoFactorSetupState` (interface) + +```ts +interface TwoFactorSetupState { + backupCodes: ReadonlyArray; + code: FieldState; + error?: string; + password: FieldState; + status: FlowStatus; + step: "enabled" | "start" | "verify"; + totpUri?: string; +} +``` + +### `TwoFactorVerifyOptions` (interface) + +```ts +interface TwoFactorVerifyOptions { + method?: "otp" | "totp"; + trustDevice?: boolean; +} +``` + +### `UserInvitationsActions` (interface) + +```ts +interface UserInvitationsActions { + accept: (invitationId: string) => Promise; + refetch: () => Promise; + reject: (invitationId: string) => Promise; +} +``` + +### `UserInvitationsController` (type) + +```ts +type UserInvitationsController = Controller, UserInvitationsActions>; +``` + +### `UsernameAvailabilityActions` (interface) + +```ts +interface UsernameAvailabilityActions { + check: (username: string) => void; + reset: () => void; +} +``` + +### `UsernameAvailabilityController` (type) + +```ts +type UsernameAvailabilityController = Controller; +``` + +### `UsernameAvailabilityOptions` (interface) + +```ts +interface UsernameAvailabilityOptions { + debounceMs?: number; + minLength?: number; +} +``` + +### `UsernameAvailabilityState` (interface) + +```ts +interface UsernameAvailabilityState { + status: AvailabilityStatus; + username: string; +} +``` + +### `UsernameSignInField` (type) + +```ts +type UsernameSignInField = "password" | "username"; +``` + +### `VerifyEmailActions` (interface) + +```ts +interface VerifyEmailActions { + verify: () => Promise; +} +``` + +### `VerifyEmailController` (type) + +```ts +type VerifyEmailController = Controller; +``` + +### `VerifyEmailOptions` (interface) + +```ts +interface VerifyEmailOptions { + autoVerify?: boolean; + token?: string; +} +``` + +### `VerifyEmailState` (interface) + +```ts +interface VerifyEmailState { + error?: string; + status: FlowStatus; +} +``` + +### `ViewPaths` (interface) + +```ts +interface ViewPaths { + acceptInvitation?: string; + deviceAuthorization?: string; + emailOtp?: string; + forgotPassword?: string; + magicLink?: string; + resetPassword?: string; + signIn?: string; + signUp?: string; + twoFactor?: string; + verifyEmail?: string; +} +``` + +### `assertOk` (const) + +```ts +const assertOk = (response: AuthResponse): AuthResponse => { + if (response.error) { + throw new AuthActionError(response.error); + } + return response; +}; +``` + +### `captchaHeaders` (const) + +```ts +const captchaHeaders = (path?: string, options: CaptchaHeaderOptions = {}): Record => { + if (path !== undefined && !isGuarded(path, options.endpoints ?? CAPTCHA_ENDPOINTS, options.basePath ?? "/api/auth")) { + return {}; + } + const { token } = store.get(); + if (token === undefined || token === "") { + return {}; + } + store.set({}); + return { [CAPTCHA_HEADER]: token }; +}; +``` + +### `createAcceptInvitationController` (const) + +```ts +const createAcceptInvitationController = (context: ControllerContext, options: AcceptInvitationOptions = {}): AcceptInvitationController => { + const store = createStore({ loading: true, status: "idle" }); + const load = async (): Promise => { + const id = options.invitationId?.trim(); + if (id === undefined || id === "") { + store.update({ error: context.localization.invitationMissing, loading: false, status: "error" }); + return; + } + store.update({ error: undefined, loading: true }); + try { + const invitation = assertOk(await context.authClient.organization.getInvitation({ query: { id } })).data ?? undefined; + store.update({ invitation, loading: false, status: "idle" }); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.invitationMissing), loading: false, status: "error" }); + } + }; + const decide = async (decision: "accept" | "reject"): Promise => { + const id = options.invitationId?.trim(); + if (id === undefined || id === "" || store.get().status === "submitting") { + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + const session = await context.authClient.getSession(); + if (!session.data?.user) { + const invited = store.get().invitation?.email; + const target = new URLSearchParams({ redirectTo: currentPath() }); + if (invited !== undefined && invited !== "") { + target.set("email", invited); + } + context.nav.replace(`${context.redirects.signIn}?${target.toString()}`); + return; + } + await (decision === "accept" + ? context.authClient.organization.acceptInvitation({ invitationId: id }).then(assertOk) + : context.authClient.organization.rejectInvitation({ invitationId: id }).then(assertOk)); + store.update({ status: "success" }); + context.onSessionChange?.(); + context.nav.replace(context.redirects.afterSignIn); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.genericError), status: "error" }); + } + }; + if (options.autoLoad !== false) { + void load(); + } + return { + actions: { accept: () => decide("accept"), load, reject: () => decide("reject") }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createAccountsController` (const) + +```ts +const createAccountsController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): AccountsController => { + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.listAccounts()).data ?? [] }; + }, options); + return { + actions: { + link: async (provider: string) => { + try { + assertOk(await context.authClient.linkSocial({ callbackURL: context.redirects.afterSignIn, provider })); + } + catch (error) { + notifyError(context, error, context.localization.genericError); + } + }, + refetch: resource.refetch, + unlink: (providerId: string, accountId?: string) => resource.mutate(async () => { + if (resource.getState().items.length <= 1) { + throw new Error(context.localization.accountsLastOne); + } + assertOk(await context.authClient.unlinkAccount(accountId === undefined ? { providerId } : { accountId, providerId })); + }), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createActiveMemberController` (const) + +```ts +const createActiveMemberController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): ActiveMemberController => { + const store = createStore({ loading: true, status: "idle" }); + const refetch = async (): Promise => { + store.update({ error: undefined, loading: true }); + try { + const [session, organization] = await Promise.all([context.authClient.getSession(), context.authClient.organization.getFullOrganization()]); + const userId = session.data?.user?.id; + const role = organization.data?.members?.find((member) => member.userId === userId)?.role; + store.update({ loading: false, role, status: "success" }); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.genericError), loading: false, status: "error" }); + } + }; + if (options.autoLoad !== false) { + void refetch(); + } + return { + actions: { refetch }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createAdminUsersController` (const) + +```ts +const createAdminUsersController = (context: ControllerContext, options: AdminUsersOptions = {}): AdminUsersController => { + const resource = createResourceController(context, async (context_, extra) => { + const search = extra.search.trim(); + const response = assertOk(await context_.authClient.admin.listUsers({ + query: { + limit: options.limit ?? 50, + ...(search === "" ? {} : { searchField: "email", searchOperator: "contains", searchValue: search }), + }, + })); + const { total, users } = readUsers(response.data); + return { extra: { total }, items: users }; + }, { autoLoad: options.autoLoad, initialExtra: { search: "" } }); + const debounceMs = options.debounceMs ?? 300; + let searchTimer: ReturnType | undefined; + const clearSearchTimer = (): void => { + if (searchTimer !== undefined) { + clearTimeout(searchTimer); + searchTimer = undefined; + } + }; + const afterSessionSwap = async (run: () => Promise): Promise => { + if (await run()) { + context.onSessionChange?.(); + context.nav.navigate(context.redirects.afterSignIn); + } + }; + return { + actions: { + ban: (userId: string, reason?: string) => resource.mutate(async () => assertOk(await context.authClient.admin.banUser({ banReason: reason, userId }))), + impersonate: (userId: string) => afterSessionSwap(async () => resource.mutateOk(async () => assertOk(await context.authClient.admin.impersonateUser({ userId })))), + refetch: resource.refetch, + remove: (userId: string) => resource.mutate(async () => assertOk(await context.authClient.admin.removeUser({ userId }))), + setRole: (userId: string, role: string) => resource.mutate(async () => assertOk(await context.authClient.admin.setRole({ role, userId }))), + setSearch: (value: string) => { + resource.patch({ search: value }); + clearSearchTimer(); + if (typeof setTimeout !== "function") { + return resource.refetch(); + } + return new Promise((resolve) => { + searchTimer = setTimeout(() => { + searchTimer = undefined; + resolve(resource.refetch()); + }, debounceMs); + }); + }, + stopImpersonating: () => afterSessionSwap(async () => resource.mutateOk(async () => assertOk(await context.authClient.admin.stopImpersonating()))), + unban: (userId: string) => resource.mutate(async () => assertOk(await context.authClient.admin.unbanUser({ userId }))), + }, + destroy: () => { + clearSearchTimer(); + resource.destroy(); + }, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createAuthorizedAppsController` (const) + +```ts +const createAuthorizedAppsController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): AuthorizedAppsController => { + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.oauth2.getConsents()).data ?? [] }; + }, options); + return { + actions: { + refetch: resource.refetch, + revoke: (consentId: string) => resource.mutate(async () => assertOk(await context.authClient.oauth2.deleteConsent({ id: consentId }))), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createAvatarUploadController` (const) + +```ts +const createAvatarUploadController = (context: ControllerContext, options: { + initialImage?: string; +} = {}): AvatarUploadController => { + const store = createStore({ imageUrl: options.initialImage, status: "idle" }); + const save = async (image: string | undefined, successStatus: FlowStatus): Promise => { + assertOk(await context.authClient.updateUser({ image })); + store.update({ imageUrl: image, status: successStatus }); + context.onSessionChange?.(); + }; + return { + actions: { + remove: async () => { + if (store.get().status === "submitting") { + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + await save(undefined, "success"); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.genericError), status: "error" }); + } + }, + upload: async (file: File) => { + const { upload } = context.avatar; + if (upload === undefined) { + store.update({ error: context.localization.avatarNoUploader, status: "error" }); + return; + } + const maxSize = context.avatar.maxSize ?? Number.POSITIVE_INFINITY; + if (file.size > maxSize) { + store.update({ error: `${context.localization.avatarTooLarge} (${megabytes(maxSize)})`, status: "error" }); + return; + } + if (file.type === "" ? !(await sniffImageType(file)) : !ACCEPTED_TYPES.has(file.type)) { + store.update({ error: context.localization.avatarWrongType, status: "error" }); + return; + } + if (store.get().status === "submitting") { + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + await save(await upload(file), "success"); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.avatarUploadFailed), status: "error" }); + } + }, + }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createBackupCodeSignInController` (const) + +```ts +const createBackupCodeSignInController = (context: ControllerContext, options: { + trustDevice?: boolean; +} = {}): FormController => createFormController(context, { + fallbackError: (localization) => localization.twoFactorFailed, + fields: { code: { validate: (value, _values, localization) => required(value, localization.otpRequired) } }, + sessionChanging: true, + submit: async (values, context_) => { + assertOk(await context_.authClient.twoFactor.verifyBackupCode({ code: values.code.trim(), trustDevice: options.trustDevice })); + return { redirectTo: resolveAfterSignIn(context_.redirects.afterSignIn) }; + }, +}); +``` + +### `createBackupCodesController` (const) + +```ts +const createBackupCodesController = (context: ControllerContext): BackupCodesHandle => { + const codes = createStore<{ + values: ReadonlyArray; + }>({ values: [] }); + const controller = createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { password: { validate: (value, _values, localization) => required(value, localization.passwordRequired) } }, + submit: async (values, context_) => { + const response = assertOk(await context_.authClient.twoFactor.generateBackupCodes({ password: values.password })); + codes.set({ values: response.data?.backupCodes ?? [] }); + return { successMessage: context_.localization.backupCodesRegenerated }; + }, + }); + return { + controller: { + ...controller, + destroy: () => { + controller.destroy(); + codes.clear(); + }, + }, + getCodes: () => codes.get().values, + subscribeCodes: codes.subscribe, + }; +}; +``` + +### `createChangeEmailController` (const) + +```ts +const createChangeEmailController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + newEmail: { validate: (value, _values, localization) => validateEmail(value, localization) }, + }, + submit: async (values, context_) => { + assertOk(await context_.authClient.changeEmail({ + callbackURL: context_.redirects.afterSignIn, + newEmail: values.newEmail.trim(), + })); + return { successMessage: context_.localization.changeEmailSent }; + }, +}); +``` + +### `createChangePasswordController` (const) + +```ts +const createChangePasswordController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + confirmPassword: { + validate: (value, values, localization) => (value === values.newPassword ? undefined : localization.passwordMismatch), + }, + currentPassword: { validate: (value, _values, localization) => required(value, localization.passwordRequired) }, + newPassword: { validate: (value, _values, localization) => validatePassword(value, localization, context.password) }, + }, + submit: async (values, context_) => { + assertOk(await context_.authClient.changePassword({ + currentPassword: values.currentPassword, + newPassword: values.newPassword, + revokeOtherSessions: true, + })); + return { successMessage: context_.localization.changePasswordDone }; + }, +}); +``` + +### `createConsentController` (const) + +```ts +const createConsentController = (context: ControllerContext, options: ConsentOptions = {}): ConsentController => { + const store = createStore({ loading: true, status: "idle" }); + const load = async (): Promise => { + const id = options.consentId?.trim(); + if (id === undefined || id === "") { + store.update({ error: context.localization.consentMissing, loading: false, status: "error" }); + return; + } + store.update({ error: undefined, loading: true }); + try { + const request = assertOk(await context.authClient.oauth2.getConsent({ query: { id } })).data ?? undefined; + store.update({ loading: false, request, status: "idle" }); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.consentMissing), loading: false, status: "error" }); + } + }; + const decide = async (accept: boolean): Promise => { + if (store.get().status === "submitting" || store.get().request === undefined) { + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + const response = assertOk(await context.authClient.oauth2.consent({ accept })); + const redirect = response.data?.redirectURI; + if (redirect === undefined || redirect === "") { + store.update({ error: context.localization.consentExpired, status: "error" }); + return; + } + store.update({ status: "success" }); + context.nav.replace(redirect); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.genericError), status: "error" }); + } + }; + if (options.autoLoad !== false) { + void load(); + } + return { + actions: { accept: () => decide(true), deny: () => decide(false), load }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createDeleteAccountController` (const) + +```ts +const createDeleteAccountController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + password: { validate: (value, _values, localization) => required(value, localization.passwordRequired) }, + }, + sessionChanging: true, + submit: async (values, context_) => { + assertOk(await context_.authClient.deleteUser({ password: values.password })); + return { redirectTo: context_.redirects.afterSignOut }; + }, +}); +``` + +### `createDeviceAuthorizationController` (const) + +```ts +const createDeviceAuthorizationController = (context: ControllerContext, options: DeviceAuthorizationOptions = {}): DeviceAuthorizationController => { + const store = createStore({ code: options.userCode ?? "", status: "idle" }); + const decide = async (decision: "approved" | "denied"): Promise => { + const code = store.get().code.trim(); + if (code === "") { + store.update({ error: context.localization.deviceCodeRequired, status: "error" }); + return; + } + if (store.get().status === "submitting") { + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + await (decision === "approved" + ? context.authClient.device.approve({ userCode: code }).then(assertOk) + : context.authClient.device.deny({ userCode: code }).then(assertOk)); + store.update({ decision, status: "success" }); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.deviceFailed), status: "error" }); + } + }; + return { + actions: { + approve: () => decide("approved"), + deny: () => decide("denied"), + setCode: (value: string) => { + store.update({ code: value, error: undefined, status: "idle" }); + }, + }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createDeviceSessionsController` (const) + +```ts +const createDeviceSessionsController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): DeviceSessionsController => { + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.multiSession.listDeviceSessions()).data ?? [] }; + }, options); + return { + actions: { + refetch: resource.refetch, + revoke: (sessionToken: string) => resource.mutate(async () => { + assertOk(await context.authClient.multiSession.revoke({ sessionToken })); + context.onSessionChange?.(); + }), + setActive: (sessionToken: string) => resource.mutate(async () => { + assertOk(await context.authClient.multiSession.setActive({ sessionToken })); + context.onSessionChange?.(); + }), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createEmailOtpController` (const) + +```ts +const createEmailOtpController = (context: ControllerContext): EmailOtpController => { + const store = createStore({ + code: emptyField(), + email: emptyField(), + status: "idle", + step: "request", + }); + const setEmail = (value: string): void => { + store.update({ email: { ...store.get().email, value }, formError: undefined, status: "idle" }); + }; + const setCode = (value: string): void => { + store.update({ code: { ...store.get().code, value }, formError: undefined, status: "idle" }); + }; + const sendCode = async (): Promise => { + const state = store.get(); + const error = validateEmail(state.email.value, context.localization); + if (error) { + store.update({ email: { ...state.email, error, touched: true }, status: "error" }); + return; + } + store.update({ email: { ...state.email, error: undefined }, formError: undefined, status: "submitting" }); + try { + assertOk(await context.authClient.emailOtp.sendVerificationOtp({ email: state.email.value.trim(), type: "sign-in" })); + store.update({ status: "idle", step: "verify", successMessage: context.localization.emailOtpSent }); + } + catch (error_) { + context.onError?.(error_); + store.update({ formError: mapAuthError(error_, context.localization, context.localization.genericError), status: "error" }); + } + }; + const verify = async (): Promise => { + const state = store.get(); + const error = required(state.code.value, context.localization.otpRequired); + if (error) { + store.update({ code: { ...state.code, error, touched: true }, status: "error" }); + return; + } + store.update({ code: { ...state.code, error: undefined }, formError: undefined, status: "submitting" }); + try { + assertOk(await context.authClient.signIn.emailOtp({ email: state.email.value.trim(), otp: state.code.value.trim() })); + store.update({ status: "success" }); + context.onSessionChange?.(); + context.nav.replace(context.redirects.afterSignIn); + } + catch (error_) { + context.onError?.(error_); + store.update({ formError: mapAuthError(error_, context.localization, context.localization.twoFactorFailed), status: "error" }); + } + }; + const actions: EmailOtpActions = { + back: () => { + store.update({ code: emptyField(), formError: undefined, status: "idle", step: "request", successMessage: undefined }); + }, + reset: () => { + store.set({ code: emptyField(), email: emptyField(), status: "idle", step: "request" }); + }, + sendCode, + setCode, + setEmail, + verify, + }; + return { + actions, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createForgotPasswordController` (const) + +```ts +const createForgotPasswordController = (context: ControllerContext, options: ForgotPasswordOptions = {}): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + email: { validate: (value, _values, localization) => validateEmail(value, localization) }, + }, + submit: async (values, context_) => { + const email = values.email.trim(); + if (context_.forgotPasswordMethod === "otp") { + assertOk(await context_.authClient.emailOtp.sendVerificationOtp({ email, type: "forget-password" })); + return { successMessage: context_.localization.emailOtpSent }; + } + assertOk(await context_.authClient.forgetPassword({ + email, + redirectTo: options.resetPath ?? "/reset-password", + })); + return { successMessage: context_.localization.forgotPasswordSent }; + }, +}); +``` + +### `createFormController` (const) + +```ts +const createFormController = (context: ControllerContext, options: FormControllerOptions): FormController => { + const fieldNames = Object.keys(options.fields) as TField[]; + const buildInitialFields = (): Record => { + const fields = {} as Record; + for (const name of fieldNames) { + fields[name] = { touched: false, value: options.fields[name].initial ?? "" }; + } + return fields; + }; + const initialState = (): FormState => { + return { fields: buildInitialFields(), loading: options.prefill !== undefined, status: "idle" }; + }; + const store = createStore>(initialState()); + let generation = 0; + const edited = new Set(); + const state = (): FormState => store.get(); + const values = (): Record => { + const out = {} as Record; + for (const name of fieldNames) { + out[name] = state().fields[name].value; + } + return out; + }; + const validateField = (name: TField): string | undefined => options.fields[name].validate?.(state().fields[name].value, values(), context.localization); + const setField = (name: TField, value: string): void => { + edited.add(name); + const current = state(); + store.set({ + ...current, + fields: { ...current.fields, [name]: { ...current.fields[name], error: undefined, value } }, + formError: undefined, + status: current.status === "submitting" ? "submitting" : "idle", + successMessage: undefined, + }); + }; + const blur = (name: TField): void => { + const error = validateField(name); + const current = state(); + store.set({ + ...current, + fields: { ...current.fields, [name]: { ...current.fields[name], error, touched: true } }, + }); + }; + const submit = async (): Promise => { + if (state().status === "submitting") { + return; + } + const nextFields = { ...state().fields }; + let hasError = false; + for (const name of fieldNames) { + const error = validateField(name); + nextFields[name] = { ...nextFields[name], error, touched: true }; + if (error) { + hasError = true; + } + } + if (hasError) { + store.set({ ...state(), fields: nextFields, formError: undefined, status: "error" }); + return; + } + store.set({ ...state(), fields: nextFields, formError: undefined, status: "submitting" }); + try { + const result = (await options.submit(values(), context)) ?? {}; + store.set({ + ...state(), + fields: { ...state().fields }, + status: "success", + successMessage: result.successMessage, + }); + if (options.sessionChanging) { + context.onSessionChange?.(); + } + if (result.redirectTo !== undefined) { + context.nav.replace(result.redirectTo); + } + } + catch (error) { + context.onError?.(error); + store.set({ + ...state(), + formError: mapAuthError(error, context.localization, options.fallbackError(context.localization)), + status: "error", + }); + } + }; + const load = async (): Promise => { + if (!options.prefill) { + return; + } + generation += 1; + const ticket = generation; + store.set({ ...state(), loading: true }); + try { + const seeded = await options.prefill(context); + if (ticket !== generation) { + return; + } + const current = state(); + if (current.status === "submitting" || current.status === "success") { + store.set({ ...current, loading: false }); + return; + } + const fields = { ...current.fields }; + for (const name of fieldNames) { + const value = seeded[name]; + if (value !== undefined && !edited.has(name)) { + fields[name] = { ...fields[name], error: undefined, touched: false, value }; + } + } + store.set({ ...current, fields, loading: false }); + } + catch (error) { + context.onError?.(error); + if (ticket === generation) { + store.set({ ...state(), loading: false }); + } + } + }; + const reset = (): void => { + edited.clear(); + store.set(initialState()); + if (options.prefill) { + void load(); + } + }; + if (options.prefill) { + void load(); + } + const actions: FormActions = { blur, load, reset, setField, submit }; + return { + actions, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createMagicLinkController` (const) + +```ts +const createMagicLinkController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + email: { validate: (value, _values, localization) => validateEmail(value, localization) }, + }, + submit: async (values, context_) => { + assertOk(await context_.authClient.signIn.magicLink({ + callbackURL: resolveAfterSignIn(context_.redirects.afterSignIn), + email: values.email.trim(), + })); + return { successMessage: context_.localization.magicLinkSent }; + }, +}); +``` + +### `createMembersController` (const) + +```ts +const createMembersController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): MembersController => { + const store = createStore({ busy: false, invitations: [], loading: true, members: [] }); + const refetch = async (): Promise => { + store.update({ error: undefined, loading: true }); + try { + const organization = assertOk(await context.authClient.organization.getFullOrganization()).data; + store.update({ invitations: organization?.invitations ?? [], loading: false, members: organization?.members ?? [] }); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.genericError), loading: false }); + } + }; + const mutate = async (run: () => Promise): Promise => { + if (store.get().busy) { + return; + } + store.update({ busy: true, error: undefined }); + try { + await run(); + store.update({ busy: false }); + await refetch(); + } + catch (error) { + context.onError?.(error); + store.update({ busy: false, error: mapAuthError(error, context.localization, context.localization.genericError) }); + } + }; + if (options.autoLoad !== false) { + void refetch(); + } + return { + actions: { + cancelInvitation: (invitationId: string) => mutate(async () => assertOk(await context.authClient.organization.cancelInvitation({ invitationId }))), + invite: (email: string, role: string) => mutate(async () => assertOk(await context.authClient.organization.inviteMember({ email, role }))), + refetch, + removeMember: (memberIdOrEmail: string) => mutate(async () => assertOk(await context.authClient.organization.removeMember({ memberIdOrEmail }))), + updateRole: (memberId: string, role: string) => mutate(async () => assertOk(await context.authClient.organization.updateMemberRole({ memberId, role }))), + }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createOrganizationLogoController` (const) + +```ts +const createOrganizationLogoController = (context: ControllerContext, options: LogoUploadOptions = {}): LogoUploadController => { + const store = createStore({ logoUrl: options.initialLogo, status: "idle" }); + const save = async (logo: string | undefined): Promise => { + assertOk(await context.authClient.organization.update({ data: { logo }, organizationId: options.organizationId })); + store.update({ logoUrl: logo, status: "success" }); + }; + const guard = async (run: () => Promise, fallback: string): Promise => { + if (store.get().status === "submitting") { + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + await run(); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, fallback), status: "error" }); + } + }; + return { + actions: { + remove: () => guard(async () => save(undefined), context.localization.genericError), + upload: async (file: File) => { + const { upload } = context.avatar; + if (upload === undefined) { + store.update({ error: context.localization.avatarNoUploader, status: "error" }); + return; + } + const maxSize = context.avatar.maxSize ?? Number.POSITIVE_INFINITY; + if (file.size > maxSize) { + store.update({ error: `${context.localization.avatarTooLarge} (${megabytes(maxSize)})`, status: "error" }); + return; + } + if (file.type !== "" && !ACCEPTED_TYPES.has(file.type)) { + store.update({ error: context.localization.avatarWrongType, status: "error" }); + return; + } + await guard(async () => save(await upload(file)), context.localization.avatarUploadFailed); + }, + }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createOrganizationSettingsController` (const) + +```ts +const createOrganizationSettingsController = (context: ControllerContext, options: OrganizationSettingsOptions = {}): FormController => { + const { organizationId } = options; + return createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + logo: {}, + name: { validate: (value, _values, localization) => required(value, localization.organizationNameRequired) }, + slug: { validate: (value, _values, localization) => required(value, localization.organizationSlugRequired) }, + }, + prefill: options.autoLoad === false + ? undefined + : async (context_) => { + const organization = assertOk(await context_.authClient.organization.getFullOrganization(organizationId === undefined ? undefined : { organizationId })).data; + return { logo: organization?.logo ?? "", name: organization?.name ?? "", slug: organization?.slug ?? "" }; + }, + submit: async (values, context_) => { + const logo = values.logo.trim(); + assertOk(await context_.authClient.organization.update({ + data: { logo: logo === "" ? undefined : logo, name: values.name.trim(), slug: values.slug.trim() }, + organizationId, + })); + return { successMessage: context_.localization.organizationSaved }; + }, + }); +}; +``` + +### `createOrganizationsController` (const) + +```ts +const createOrganizationsController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): OrganizationsController => { + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.organization.list()).data ?? [] }; + }, options); + return { + actions: { + create: (name: string, slug: string) => resource.mutate(async () => assertOk(await context.authClient.organization.create({ name, slug }))), + leave: (organizationId: string) => resource.mutate(async () => { + assertOk(await context.authClient.organization.leave({ organizationId })); + context.onSessionChange?.(); + }), + refetch: resource.refetch, + remove: (organizationId: string) => resource.mutate(async () => assertOk(await context.authClient.organization.delete({ organizationId }))), + setActive: (organizationId: string) => resource.mutate(async () => assertOk(await context.authClient.organization.setActive({ organizationId }))), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createPasskeysController` (const) + +```ts +const createPasskeysController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): PasskeysController => { + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.passkey.listUserPasskeys()).data ?? [] }; + }, options); + return { + actions: { + add: (name?: string) => resource.mutate(async () => { + const trimmed = name?.trim(); + const response = await context.authClient.passkey.addPasskey(trimmed === undefined || trimmed === "" ? undefined : { name: trimmed }); + if (!response || (response.error && CANCELLED_CODES.has(response.error.code ?? ""))) { + return; + } + assertOk(response); + }), + refetch: resource.refetch, + remove: (id: string) => resource.mutate(async () => assertOk(await context.authClient.passkey.deletePasskey({ id }))), + rename: (id: string, name: string) => resource.mutate(async () => assertOk(await context.authClient.passkey.updatePasskey({ id, name: name.trim() }))), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createPhoneForgotPasswordController` (const) + +```ts +const createPhoneForgotPasswordController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { phoneNumber: { validate: (value, _values, localization) => required(value, localization.phoneRequired) } }, + submit: async (values, context_) => { + assertOk(await context_.authClient.phoneNumber.requestPasswordReset({ phoneNumber: values.phoneNumber.trim() })); + return { successMessage: context_.localization.phoneOtpSent }; + }, +}); +``` + +### `createPhoneResetPasswordController` (const) + +```ts +const createPhoneResetPasswordController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + confirmPassword: { + validate: (value, values, localization) => (value === values.newPassword ? undefined : localization.passwordMismatch), + }, + newPassword: { validate: (value, _values, localization) => passwordValidator(value, localization, context.password) }, + otp: { validate: (value, _values, localization) => required(value, localization.otpRequired) }, + phoneNumber: { validate: (value, _values, localization) => required(value, localization.phoneRequired) }, + }, + submit: async (values, context_) => { + assertOk(await context_.authClient.phoneNumber.resetPassword({ + newPassword: values.newPassword, + otp: values.otp.trim(), + phoneNumber: values.phoneNumber.trim(), + })); + return { redirectTo: context_.redirects.signIn, successMessage: context_.localization.resetPasswordDone }; + }, +}); +``` + +### `createPhoneSignInController` (const) + +```ts +const createPhoneSignInController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.signInFailed, + fields: { + password: { validate: (value, _values, localization) => required(value, localization.passwordRequired) }, + phoneNumber: { validate: (value, _values, localization) => required(value, localization.phoneRequired) }, + }, + sessionChanging: true, + submit: async (values, context_) => { + const response = assertOk(await context_.authClient.signIn.phoneNumber({ password: values.password, phoneNumber: values.phoneNumber.trim() })); + if (response.data?.twoFactorRedirect) { + return { redirectTo: withRedirectTo(context_.redirects.twoFactor) }; + } + return { redirectTo: resolveAfterSignIn(context_.redirects.afterSignIn) }; + }, +}); +``` + +### `createPhoneVerifyController` (const) + +```ts +const createPhoneVerifyController = (context: ControllerContext, options: PhoneVerifyOptions = {}): PhoneVerifyController => { + const store = createStore({ phoneNumber: "", status: "idle", step: "request" }); + const run = async (work: () => Promise>, fallback: string): Promise => { + if (store.get().status === "submitting") { + return; + } + store.update({ error: undefined, status: "submitting", successMessage: undefined }); + try { + store.update({ status: "idle", ...(await work()) }); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, fallback), status: "error" }); + } + }; + return { + actions: { + restart: () => { + store.set({ phoneNumber: "", status: "idle", step: "request" }); + }, + send: async (phoneNumber: string) => { + const trimmed = phoneNumber.trim(); + if (trimmed === "") { + store.update({ error: context.localization.phoneRequired, status: "error" }); + return; + } + await run(async () => { + assertOk(await context.authClient.phoneNumber.sendOtp({ phoneNumber: trimmed })); + return { phoneNumber: trimmed, step: "verify", successMessage: context.localization.phoneOtpSent }; + }, context.localization.genericError); + }, + verify: async (code: string) => { + const trimmed = code.trim(); + if (trimmed === "") { + store.update({ error: context.localization.otpRequired, status: "error" }); + return; + } + await run(async () => { + assertOk(await context.authClient.phoneNumber.verify({ + code: trimmed, + phoneNumber: store.get().phoneNumber, + updatePhoneNumber: options.updatePhoneNumber, + })); + context.onSessionChange?.(); + if (options.updatePhoneNumber !== true) { + context.nav.replace(context.redirects.afterSignIn); + } + return { status: "success", successMessage: context.localization.phoneVerified }; + }, context.localization.twoFactorFailed); + }, + }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createProfileController` (const) + +```ts +const createProfileController = (context: ControllerContext, options: ProfileOptions = {}): FormController => { + const seeded = options.initialImage !== undefined || options.initialName !== undefined; + return createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + image: { initial: options.initialImage ?? "" }, + name: { initial: options.initialName ?? "", validate: (value, _values, localization) => required(value, localization.nameRequired) }, + }, + prefill: seeded + ? undefined + : async (context_) => { + const session = await context_.authClient.getSession(); + const user = session.data?.user; + return { image: user?.image ?? "", name: user?.name ?? "" }; + }, + submit: async (values, context_) => { + const image = values.image.trim(); + assertOk(await context_.authClient.updateUser({ image: image === "" ? undefined : image, name: values.name.trim() })); + return { successMessage: context_.localization.profileSaved }; + }, + }); +}; +``` + +### `createResendVerificationController` (const) + +```ts +const createResendVerificationController = (context: ControllerContext, options: { + initialEmail?: string; +} = {}): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { email: { initial: options.initialEmail ?? "", validate: (value, _values, localization) => emailValidator(value, localization) } }, + prefill: options.initialEmail === undefined + ? async (context_) => { + const session = await context_.authClient.getSession(); + return { email: session.data?.user?.email ?? "" }; + } + : undefined, + submit: async (values, context_) => { + assertOk(await context_.authClient.sendVerificationEmail({ callbackURL: context_.redirects.afterSignIn, email: values.email.trim() })); + return { successMessage: context_.localization.verifyEmailSent }; + }, +}); +``` + +### `createResetPasswordController` (const) + +```ts +const createResetPasswordController = (context: ControllerContext, options: ResetPasswordOptions = {}): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + confirmPassword: { + validate: (value, values, localization) => (value === values.password ? undefined : localization.passwordMismatch), + }, + password: { validate: (value, _values, localization) => validatePassword(value, localization, context.password) }, + }, + submit: async (values, context_) => { + assertOk(await context_.authClient.resetPassword({ + newPassword: values.password, + token: options.token, + })); + return { redirectTo: context_.redirects.signIn, successMessage: context_.localization.resetPasswordDone }; + }, +}); +``` + +### `createResetPasswordOtpController` (const) + +```ts +const createResetPasswordOtpController = (context: ControllerContext, options: { + initialEmail?: string; +} = {}): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + confirmPassword: { + validate: (value, values, localization) => (value === values.password ? undefined : localization.passwordMismatch), + }, + email: { initial: options.initialEmail ?? "", validate: (value, _values, localization) => validateEmail(value, localization) }, + otp: { validate: (value, _values, localization) => required(value, localization.otpRequired) }, + password: { validate: (value, _values, localization) => validatePassword(value, localization, context.password) }, + }, + submit: async (values, context_) => { + assertOk(await context_.authClient.emailOtp.resetPassword({ + email: values.email.trim(), + otp: values.otp.trim(), + password: values.password, + })); + return { redirectTo: context_.redirects.signIn, successMessage: context_.localization.resetPasswordDone }; + }, +}); +``` + +### `createResourceController` (const) + +```ts +const createResourceController = >(context: ControllerContext, load: (context: ControllerContext, extra: TExtra) => Promise<{ + extra?: Partial; + items: ReadonlyArray; +}>, options: ResourceOptions = {}): ResourceHandle => { + const store = createStore>({ + busy: false, + extra: options.initialExtra ?? ({} as TExtra), + items: [], + loading: true, + status: "idle", + }); + let generation = 0; + const refetch = async (): Promise => { + generation += 1; + const ticket = generation; + store.update({ error: undefined, loading: true, status: "submitting" }); + try { + const result = await load(context, store.get().extra); + if (ticket !== generation) { + return; + } + const { extra: patched, items } = result; + store.update({ items, loading: false, status: "success" }); + if (patched !== undefined) { + store.update({ extra: { ...store.get().extra, ...patched } }); + } + } + catch (error) { + if (ticket !== generation) { + return; + } + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.genericError), loading: false, status: "error" }); + } + }; + const mutateOk = async (run: () => Promise): Promise => { + if (store.get().busy) { + return false; + } + store.update({ busy: true, error: undefined }); + try { + await run(); + store.update({ busy: false }); + await refetch(); + return true; + } + catch (error) { + context.onError?.(error); + store.update({ busy: false, error: mapAuthError(error, context.localization, context.localization.genericError), status: "error" }); + return false; + } + }; + if (options.autoLoad !== false) { + void refetch(); + } + return { + destroy: store.clear, + getState: store.get, + mutate: async (run: () => Promise) => { + await mutateOk(run); + }, + mutateOk, + patch: (next: Partial) => { + store.update({ extra: { ...store.get().extra, ...next } }); + }, + refetch, + subscribe: store.subscribe, + }; +}; +``` + +### `createSessionController` (const) + +```ts +const createSessionController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): SessionController => { + const store = createStore({ loading: true, settled: false, status: "idle" }); + const refetch = async (): Promise => { + store.update({ error: undefined, loading: true }); + try { + const response = await context.authClient.getSession(); + store.update({ loading: false, settled: true, status: "success", user: response.data?.user }); + } + catch (error) { + context.onError?.(error); + store.update({ + error: mapAuthError(error, context.localization, context.localization.genericError), + loading: false, + settled: true, + status: "error", + user: undefined, + }); + } + }; + if (options.autoLoad !== false) { + void refetch(); + } + return { + actions: { refetch }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createSessionsController` (const) + +```ts +const createSessionsController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): SessionsController => { + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.listSessions()).data ?? [] }; + }, options); + return { + actions: { + refetch: resource.refetch, + revoke: (token: string) => resource.mutate(async () => assertOk(await context.authClient.revokeSession({ token }))), + revokeOthers: () => resource.mutate(async () => assertOk(await context.authClient.revokeOtherSessions())), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createSetUsernameController` (const) + +```ts +const createSetUsernameController = (context: ControllerContext, options: { + initialUsername?: string; +} = {}): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + username: { initial: options.initialUsername ?? "", validate: (value, _values, localization) => required(value, localization.usernameRequired) }, + }, + submit: async (values, context_) => { + assertOk(await context_.authClient.updateUser({ username: values.username.trim() })); + return { successMessage: context_.localization.usernameSaved }; + }, +}); +``` + +### `createSignInController` (const) + +```ts +const createSignInController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.signInFailed, + fields: { + email: { validate: (value, _values, localization) => validateEmail(value, localization) }, + password: { validate: (value, _values, localization) => required(value, localization.passwordRequired) }, + }, + sessionChanging: true, + submit: async (values, context_) => { + const response = assertOk(await context_.authClient.signIn.email({ + callbackURL: context_.redirects.afterSignIn, + email: values.email.trim(), + password: values.password, + })); + if (response.data?.twoFactorRedirect === true) { + return { redirectTo: withRedirectTo(context_.redirects.twoFactor) }; + } + return { redirectTo: resolveAfterSignIn(context_.redirects.afterSignIn) }; + }, +}); +``` + +### `createSignUpController` (const) + +```ts +const createSignUpController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.signUpFailed, + fields: { + email: { validate: (value, _values, localization) => validateEmail(value, localization) }, + name: { validate: (value, _values, localization) => required(value, localization.nameRequired) }, + password: { validate: (value, _values, localization) => validatePassword(value, localization, context.password) }, + }, + prefill: () => { + const seeded: Partial> = {}; + const email = readFieldPrefill("email"); + const name = readFieldPrefill("name"); + if (email !== undefined) { + seeded.email = email; + } + if (name !== undefined) { + seeded.name = name; + } + return Promise.resolve(seeded); + }, + sessionChanging: true, + submit: async (values, context_) => { + assertOk(await context_.authClient.signUp.email({ + callbackURL: context_.redirects.afterSignIn, + email: values.email.trim(), + name: values.name.trim(), + password: values.password, + })); + return { redirectTo: resolveAfterSignIn(context_.redirects.afterSignIn) }; + }, +}); +``` + +### `createStore` (const) + +```ts +const createStore = (initial: T): Store => { + let state = initial; + const listeners = new Set<() => void>(); + const notify = (): void => { + for (const listener of listeners) { + listener(); + } + }; + return { + clear: () => { + listeners.clear(); + }, + get: () => state, + set: (next: T) => { + state = next; + notify(); + }, + subscribe: (onChange: () => void) => { + listeners.add(onChange); + return () => { + listeners.delete(onChange); + }; + }, + update: (patch: Partial) => { + state = { ...state, ...patch }; + notify(); + }, + }; +}; +``` + +### `createTeamsController` (const) + +```ts +const createTeamsController = (context: ControllerContext, options: TeamsOptions = {}): TeamsController => { + const query = options.organizationId === undefined ? undefined : { organizationId: options.organizationId }; + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.organization.listTeams(query === undefined ? undefined : { query })).data ?? [] }; + }, { autoLoad: options.autoLoad }); + return { + actions: { + create: (name: string) => resource.mutate(async () => assertOk(await context.authClient.organization.createTeam({ name: name.trim(), organizationId: options.organizationId }))), + refetch: resource.refetch, + remove: (teamId: string) => resource.mutate(async () => assertOk(await context.authClient.organization.removeTeam({ organizationId: options.organizationId, teamId }))), + rename: (teamId: string, name: string) => resource.mutate(async () => assertOk(await context.authClient.organization.updateTeam({ data: { name: name.trim() }, teamId }))), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createThemeModeController` (const) + +```ts +const createThemeModeController = (options: ThemeModeOptions = {}): ThemeModeController => { + const stored = options.persist === false ? undefined : readStored(); + const initial = stored ?? "system"; + const store = createStore({ mode: initial, resolved: initial === "system" ? systemPrefers() : initial }); + const apply = (mode: ThemeMode): void => { + const resolved = mode === "system" ? systemPrefers() : mode; + if (options.apply) { + options.apply(mode, resolved); + } + else { + const dataset = (globalThis as { + document?: { + documentElement?: { + dataset?: Record; + }; + }; + }).document?.documentElement?.dataset; + if (dataset) { + dataset["theme"] = resolved; + } + } + store.update({ mode, resolved }); + }; + if (stored !== undefined) { + apply(stored); + } + return { + actions: { + setMode: (mode: ThemeMode) => { + if (options.persist !== false) { + try { + storage()?.setItem(THEME_STORAGE_KEY, mode); + } + catch { + } + } + apply(mode); + }, + }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createTwoFactorSetupController` (const) + +```ts +const createTwoFactorSetupController = (context: ControllerContext): TwoFactorSetupController => { + const store = createStore(initialState()); + const fail = (error: unknown, fallback: string): void => { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, fallback), status: "error" }); + }; + const enable = async (): Promise => { + const state = store.get(); + const error = required(state.password.value, context.localization.passwordRequired); + if (error) { + store.update({ password: { ...state.password, error, touched: true }, status: "error" }); + return; + } + store.update({ error: undefined, password: { ...state.password, error: undefined }, status: "submitting" }); + try { + const { data } = assertOk(await context.authClient.twoFactor.enable({ password: state.password.value })); + store.update({ backupCodes: data?.backupCodes ?? [], status: "idle", step: "verify", totpUri: data?.totpURI }); + } + catch (error_) { + fail(error_, context.localization.genericError); + } + }; + const verify = async (): Promise => { + const state = store.get(); + const error = required(state.code.value, context.localization.otpRequired); + if (error) { + store.update({ code: { ...state.code, error, touched: true }, status: "error" }); + return; + } + store.update({ code: { ...state.code, error: undefined }, error: undefined, status: "submitting" }); + try { + assertOk(await context.authClient.twoFactor.verifyTotp({ code: state.code.value.trim() })); + store.update({ status: "success", step: "enabled" }); + } + catch (error_) { + fail(error_, context.localization.twoFactorFailed); + } + }; + const disable = async (): Promise => { + const state = store.get(); + const error = required(state.password.value, context.localization.passwordRequired); + if (error) { + store.update({ password: { ...state.password, error, touched: true }, status: "error" }); + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + assertOk(await context.authClient.twoFactor.disable({ password: state.password.value })); + store.set(initialState()); + } + catch (error_) { + fail(error_, context.localization.genericError); + } + }; + return { + actions: { + disable, + enable, + reset: () => { + store.set(initialState()); + }, + setCode: (value: string) => { + store.update({ code: { ...store.get().code, value }, error: undefined, status: "idle" }); + }, + setPassword: (value: string) => { + store.update({ error: undefined, password: { ...store.get().password, value }, status: "idle" }); + }, + verify, + }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createTwoFactorVerifyController` (const) + +```ts +const createTwoFactorVerifyController = (context: ControllerContext, options: TwoFactorVerifyOptions = {}): FormController => createFormController(context, { + fallbackError: (localization) => localization.twoFactorFailed, + fields: { + code: { validate: (value, _values, localization) => required(value, localization.otpRequired) }, + }, + sessionChanging: true, + submit: async (values, context_) => { + const input = { code: values.code.trim(), trustDevice: options.trustDevice }; + assertOk(options.method === "otp" ? await context_.authClient.twoFactor.verifyOtp(input) : await context_.authClient.twoFactor.verifyTotp(input)); + return { redirectTo: resolveAfterSignIn(context_.redirects.afterSignIn) }; + }, +}); +``` + +### `createUserInvitationsController` (const) + +```ts +const createUserInvitationsController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): UserInvitationsController => { + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.organization.listUserInvitations()).data ?? [] }; + }, options); + return { + actions: { + accept: (invitationId: string) => resource.mutate(async () => { + assertOk(await context.authClient.organization.acceptInvitation({ invitationId })); + context.onSessionChange?.(); + }), + refetch: resource.refetch, + reject: (invitationId: string) => resource.mutate(async () => assertOk(await context.authClient.organization.rejectInvitation({ invitationId }))), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createUsernameAvailabilityController` (const) + +```ts +const createUsernameAvailabilityController = (context: ControllerContext, options: UsernameAvailabilityOptions = {}): UsernameAvailabilityController => { + const store = createStore({ status: "idle", username: "" }); + const debounceMs = options.debounceMs ?? 400; + const minLength = options.minLength ?? 3; + let timer: ReturnType | undefined; + let inFlight = ""; + const clearTimer = (): void => { + if (timer !== undefined) { + clearTimeout(timer); + timer = undefined; + } + }; + const ask = async (username: string): Promise => { + inFlight = username; + store.set({ status: "checking", username }); + try { + const response = await context.authClient.isUsernameAvailable({ username }); + if (inFlight !== username) { + return; + } + if (response.error) { + store.set({ status: "unknown", username }); + return; + } + store.set({ status: response.data?.available === false ? "taken" : "available", username }); + } + catch (error) { + context.onError?.(error); + if (inFlight === username) { + store.set({ status: "unknown", username }); + } + } + }; + return { + actions: { + check: (username: string) => { + const trimmed = username.trim(); + clearTimer(); + if (trimmed.length < minLength) { + inFlight = ""; + store.set({ status: "idle", username: trimmed }); + return; + } + if (typeof setTimeout !== "function") { + void ask(trimmed); + return; + } + timer = setTimeout(() => { + void ask(trimmed); + }, debounceMs); + }, + reset: () => { + clearTimer(); + inFlight = ""; + store.set({ status: "idle", username: "" }); + }, + }, + destroy: () => { + clearTimer(); + store.clear(); + }, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createUsernameSignInController` (const) + +```ts +const createUsernameSignInController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.signInFailed, + fields: { + password: { validate: (value, _values, localization) => required(value, localization.passwordRequired) }, + username: { validate: (value, _values, localization) => required(value, localization.usernameRequired) }, + }, + sessionChanging: true, + submit: async (values, context_) => { + const response = assertOk(await context_.authClient.signIn.username({ password: values.password, username: values.username.trim() })); + if (response.data?.twoFactorRedirect) { + return { redirectTo: withRedirectTo(context_.redirects.twoFactor) }; + } + return { redirectTo: resolveAfterSignIn(context_.redirects.afterSignIn) }; + }, +}); +``` + +### `createVerifyEmailController` (const) + +```ts +const createVerifyEmailController = (context: ControllerContext, options: VerifyEmailOptions = {}): VerifyEmailController => { + const store = createStore({ status: "idle" }); + const verify = async (): Promise => { + const token = options.token?.trim(); + if (token === undefined || token === "") { + store.update({ error: context.localization.verifyEmailNoToken, status: "error" }); + return; + } + if (store.get().status === "submitting") { + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + const response = await context.authClient.verifyEmail({ query: { token } }); + if (response.error && !ALREADY_VERIFIED_CODES.has(response.error.code ?? "")) { + assertOk(response); + } + store.update({ status: "success" }); + context.onSessionChange?.(); + context.nav.replace(context.redirects.afterSignIn); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.verifyEmailFailed), status: "error" }); + } + }; + if (options.autoVerify !== false) { + void verify(); + } + return { + actions: { verify }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `defaultNav` (const) + +```ts +const defaultNav: NavAdapter = { + navigate: (to: string): void => { + globalThis.location.assign(to); + }, + replace: (to: string): void => { + globalThis.location.replace(to); + }, +}; +``` + +### `derivePluginFlags` (const) + +```ts +const derivePluginFlags = (authClient: unknown): Required => { + if (authClient === null || (typeof authClient !== "object" && typeof authClient !== "function")) { + return withEveryFlow(true); + } + return registry.get(authClient) ?? withEveryFlow(true); +}; +``` + +### `discoverAuthConfig` (const) + +```ts +const discoverAuthConfig = (basePath: string): DiscoveryHandle => { + const url = `${basePath.endsWith("/") ? basePath.slice(0, -1) : basePath}/ui-config`; + const existing = handles.get(url); + if (existing) { + return existing; + } + const store = createStore({ status: "loading" }); + const handle: DiscoveryHandle = { getState: store.get, subscribe: store.subscribe }; + handles.set(url, handle); + const fetcher = (globalThis as { + fetch?: typeof fetch; + }).fetch; + if (typeof fetcher !== "function") { + handles.delete(url); + store.update({ status: "unavailable" }); + return handle; + } + const origin = (globalThis as { + location?: { + origin?: string; + }; + }).location?.origin; + const hasOrigin = origin !== undefined && origin !== ""; + let requestUrl: string | undefined = url; + if (url.startsWith("/")) { + requestUrl = hasOrigin ? `${origin}${url}` : undefined; + } + if (requestUrl === undefined) { + handles.delete(url); + store.update({ status: "unavailable" }); + return handle; + } + const unavailable = (): void => { + handles.delete(url); + store.update({ status: "unavailable" }); + }; + void (async () => { + try { + const response = await fetcher(requestUrl, { credentials: "include", headers: { accept: "application/json" } }); + if (!response.ok) { + unavailable(); + return; + } + const body: unknown = await response.json(); + if (isConfig(body)) { + store.update({ config: normalize(body), status: "ready" }); + return; + } + unavailable(); + } + catch { + unavailable(); + } + })(); + return handle; +}; +``` + +### `dismissToast` (const) + +```ts +const dismissToast = (id: number): void => { + const timer = timers.get(id); + if (timer !== undefined) { + clearTimeout(timer); + timers.delete(id); + } + store.update({ toasts: store.get().toasts.filter((toast) => toast.id !== id) }); +}; +``` + +### `email` (const) + +```ts +const email = (value: string, localization: Localization): string | undefined => { + const missing = required(value, localization.emailRequired); + if (missing) { + return missing; + } + return EMAIL_RE.test(value.trim()) ? undefined : localization.emailInvalid; +}; +``` + +### `getToasts` (const) + +```ts +const getToasts = (): ReadonlyArray => store.get().toasts; +``` + +### `isFlowEnabled` (const) + +```ts +const isFlowEnabled = (context: { + plugins: Required; +}, flow: FlowName, component: string): boolean => { + if (context.plugins[flow]) { + return true; + } + if (!warned.has(component)) { + warned.add(component); + console.warn(`[lunora-auth-ui] <${component}> did not render: the "${flow}" flow is off. Turn it on in lunora/auth-ui/client.ts, or pass plugins={{ ${flow}: true }} to .`); + } + return false; +}; +``` + +### `isSafeRedirect` (const) + +```ts +const isSafeRedirect = (target: string): boolean => { + const trimmed = target.trim(); + if (trimmed === "" || !trimmed.startsWith("/")) { + return false; + } + if (trimmed.startsWith("//") || trimmed.startsWith("/\\")) { + return false; + } + return !CONTROL_CHARACTERS.test(trimmed); +}; +``` + +### `linkableProviders` (const) + +```ts +const linkableProviders = (accounts: ReadonlyArray, social: ReadonlyArray): ReadonlyArray => { + const linked = new Set(linkedProviderIds(accounts)); + return social.filter((provider) => !linked.has(provider)); +}; +``` + +### `lockedPrefill` (const) + +```ts +const lockedPrefill = (field: string, lock: boolean | undefined): boolean => lock === true && readFieldPrefill(field) !== undefined; +``` + +### `mapAuthError` (const) + +```ts +const mapAuthError = (error: unknown, localization: Localization, fallback: string): string => { + if (error instanceof AuthActionError) { + if (error.code !== undefined && NOT_FRESH_CODES.has(error.code)) { + return localization.sessionNotFresh; + } + return error.message.trim() === "" ? fallback : error.message; + } + if (error instanceof LunoraError) { + return error.message.trim() === "" ? fallback : error.message; + } + return fallback === "" ? localization.genericError : fallback; +}; +``` + +### `notifyError` (const) + +```ts +const notifyError = (context: ControllerContext, error: unknown, fallback: string): void => { + context.onError?.(error); + pushToast(mapAuthError(error, context.localization, fallback)); +}; +``` + +### `passkeyLabel` (const) + +```ts +const passkeyLabel = (passkey: AuthPasskey, localization: Localization): string => { + const name = passkey.name?.trim(); + return name === undefined || name === "" ? localization.passkeyUnnamed : name; +}; +``` + +### `password` (const) + +```ts +const password = (value: string, localization: Localization, policy?: PasswordPolicy): string | undefined => validatePassword(value, localization, policy); +``` + +### `passwordRequirements` (const) + +```ts +const passwordRequirements = (value: string, localization: Localization, policy: PasswordPolicy = {}): ReadonlyArray => { + const minLength = policy.minLength ?? DEFAULT_PASSWORD_POLICY.minLength; + const requirements: PasswordRequirement[] = [ + { label: localization.passwordRuleLength.replace("{min}", String(minLength)), met: value.length >= minLength }, + ]; + if (policy.requireLowercase === true) { + requirements.push({ label: localization.passwordRuleLowercase, met: LOWERCASE.test(value) }); + } + if (policy.requireUppercase === true) { + requirements.push({ label: localization.passwordRuleUppercase, met: UPPERCASE.test(value) }); + } + if (policy.requireDigit === true) { + requirements.push({ label: localization.passwordRuleDigit, met: DIGIT.test(value) }); + } + if (policy.requireSymbol === true) { + requirements.push({ label: localization.passwordRuleSymbol, met: SYMBOL.test(value) }); + } + return requirements; +}; +``` + +### `passwordScore` (const) + +```ts +const passwordScore = (requirements: ReadonlyArray): number => { + if (requirements.length === 0) { + return 0; + } + return requirements.filter((requirement) => requirement.met).length / requirements.length; +}; +``` + +### `promptOneTap` (const) + +```ts +const promptOneTap = async (context: ControllerContext): Promise => { + try { + await context.authClient.oneTap({ callbackURL: resolveAfterSignIn(context.redirects.afterSignIn) }); + context.onSessionChange?.(); + } + catch (error) { + context.onError?.(error); + } +}; +``` + +### `providerLabel` (const) + +```ts +const providerLabel = (provider: string): string => { + const known = PROVIDER_LABELS[provider]; + if (known !== undefined) { + return known; + } + return provider + .split("-") + .map((part) => (part === "" ? part : `${part.charAt(0).toUpperCase()}${part.slice(1)}`)) + .join(" "); +}; +``` + +### `pushToast` (const) + +```ts +const pushToast = (message: string): number => { + const current = store.get().toasts; + const last = current.at(-1); + if (last?.message === message) { + return last.id; + } + nextId += 1; + const toast: Toast = { id: nextId, message }; + store.update({ toasts: [...current, toast] }); + if (typeof setTimeout === "function") { + timers.set(toast.id, setTimeout(() => { + dismissToast(toast.id); + }, TOAST_DURATION_MS)); + } + return toast.id; +}; +``` + +### `readFieldPrefill` (const) + +```ts +const readFieldPrefill = (field: string): string | undefined => { + if (!PREFILLABLE.has(field)) { + return undefined; + } + const value = queryParameter(field); + if (value === undefined) { + return undefined; + } + const trimmed = value.trim(); + return trimmed === "" || CONTROL_CHARACTERS.test(trimmed) ? undefined : trimmed; +}; +``` + +### `readLastLoginMethod` (const) + +```ts +const readLastLoginMethod = (cookieName: string = LAST_LOGIN_METHOD_COOKIE): string | undefined => { + const cookie = (globalThis as { + document?: { + cookie?: string; + }; + }).document?.cookie; + if (cookie === undefined || cookie === "") { + return undefined; + } + for (const part of cookie.split(";")) { + const separator = part.indexOf("="); + if (separator === -1) { + continue; + } + if (part.slice(0, separator).trim() !== cookieName) { + continue; + } + const value = decodeURIComponent(part.slice(separator + 1).trim()); + return value === "" ? undefined : value; + } + return undefined; +}; +``` + +### `readRedirectTo` (const) + +```ts +const readRedirectTo = (parameter = "redirectTo"): string | undefined => { + const value = queryParameter(parameter); + if (value === undefined) { + return undefined; + } + const trimmed = value.trim(); + return isSafeRedirect(trimmed) ? trimmed : undefined; +}; +``` + +### `registerAuthClientPlugins` (const) + +```ts +const registerAuthClientPlugins = (authClient: unknown, plugins: PluginFlags = {}): void => { + if (typeof authClient !== "object" && typeof authClient !== "function") { + return; + } + if (authClient === null) { + return; + } + const flags = withEveryFlow(false); + for (const flow of FLOW_NAMES) { + flags[flow] = plugins[flow] ?? false; + } + registry.set(authClient, flags); +}; +``` + +### `renderCaptcha` (const) + +```ts +const renderCaptcha = (element: Element, options: RenderCaptchaOptions): (() => void) => { + const provider = PROVIDERS[options.provider]; + let widgetId: unknown; + let disposed = false; + let ownToken: string | undefined; + void loadScript(provider.script) + .then(() => { + if (disposed) { + return false; + } + const api = (globalThis as unknown as Record)[provider.global]; + if (api === undefined) { + throw new Error(`${provider.global} did not appear after its script loaded`); + } + widgetId = api.render(element, { + callback: (token: string) => { + ownToken = token; + setCaptchaToken(token); + }, + "expired-callback": () => { + ownToken = undefined; + setCaptchaToken(undefined); + }, + sitekey: options.siteKey, + }); + return true; + }) + .catch((error: unknown) => { + options.onError?.(error); + }); + return () => { + disposed = true; + if (ownToken !== undefined && store.get().token === ownToken) { + setCaptchaToken(undefined); + } + const api = (globalThis as unknown as Record)[provider.global]; + api?.reset?.(widgetId); + }; +}; +``` + +### `required` (const) + +```ts +const required = (value: string, message: string): string | undefined => (value.trim() === "" ? message : undefined); +``` + +### `resetAuthConfigDiscovery` (const) + +```ts +const resetAuthConfigDiscovery = (): void => { + handles.clear(); +}; +``` + +### `resetFlowWarnings` (const) + +```ts +const resetFlowWarnings = (): void => { + warned.clear(); +}; +``` + +### `resetToasts` (const) + +```ts +const resetToasts = (): void => { + for (const timer of timers.values()) { + clearTimeout(timer); + } + timers.clear(); + store.set({ toasts: [] }); +}; +``` + +### `resolveAfterSignIn` (const) + +```ts +const resolveAfterSignIn = (fallback: string): string => readRedirectTo() ?? fallback; +``` + +### `resolveContext` (const) + +```ts +const resolveContext = (config: AuthUIConfig, discovered?: DiscoveredConfig): ControllerContext => { + return { + authClient: config.authClient as AuthClient, + avatar: { maxSize: config.avatar?.maxSize ?? DEFAULT_AVATAR_MAX_SIZE, upload: config.avatar?.upload }, + basePath: config.basePath ?? DEFAULT_BASE_PATH, + credentials: discovered?.emailAndPassword ?? true, + forgotPasswordMethod: config.forgotPassword?.method ?? "link", + localization: resolveLocalization(config.localization), + nav: config.nav, + onError: config.onError, + onSessionChange: config.onSessionChange, + organization: { + allowUserToCreate: discovered?.organization?.allowUserToCreate ?? true, + invitationLimit: discovered?.organization?.invitationLimit, + limit: discovered?.organization?.limit, + membershipLimit: discovered?.organization?.membershipLimit, + roles: config.organization?.roles ?? discovered?.organization?.roles ?? false, + showSlug: config.organization?.showSlug ?? true, + teams: config.organization?.teams ?? discovered?.organization?.teams ?? false, + }, + password: config.password ?? {}, + plugins: resolvePlugins(config.authClient, config.plugins, discovered), + redirects: resolveRedirects(config.redirects), + signUp: discovered?.signUp ?? true, + social: config.social ?? discovered?.socialProviders ?? [], + themeVariables: resolveThemeVariables(config.theme), + viewPaths: resolveViewPaths(config.viewPaths), + }; +}; +``` + +### `resolveLocalization` (const) + +```ts +const resolveLocalization = (overrides?: Partial): Localization => { + return { + ...DEFAULT_LOCALIZATION, + ...overrides, + }; +}; +``` + +### `resolveThemeVariables` (const) + +```ts +const resolveThemeVariables = (theme?: (defaults: ThemeTokens) => ThemeTokens): Readonly> => { + if (!theme) { + return {}; + } + const resolved = theme({ ...DEFAULT_THEME_TOKENS }); + const variables: Record = {}; + for (const token of Object.keys(DEFAULT_THEME_TOKENS) as (keyof ThemeTokens)[]) { + const value = resolved[token]; + if (typeof value === "string" && value !== DEFAULT_THEME_TOKENS[token]) { + variables[toCustomProperty(token)] = value; + } + } + return variables; +}; +``` + +### `scopeLabels` (const) + +```ts +const scopeLabels = (scope?: string): ReadonlyArray => { + const parts = (scope ?? "").split(SCOPE_SEPARATOR).filter((part) => part !== ""); + return parts.map((part) => SCOPE_LABELS[part] ?? part); +}; +``` + +### `sessionLabel` (const) + +```ts +const sessionLabel = (session: AuthSession, localization: Localization): string => { + const agent = session.userAgent?.trim(); + if (agent !== undefined && agent !== "") { + return agent; + } + return session.ipAddress ?? localization.unknownDevice; +}; +``` + +### `setCaptchaToken` (const) + +```ts +const setCaptchaToken = (token: string | undefined): void => { + store.set({ token }); +}; +``` + +### `signInAnonymously` (const) + +```ts +const signInAnonymously = async (context: ControllerContext): Promise => { + try { + assertOk(await context.authClient.signIn.anonymous()); + context.onSessionChange?.(); + context.nav.replace(context.redirects.afterSignIn); + } + catch (error) { + notifyError(context, error, context.localization.signInFailed); + } +}; +``` + +### `signInWithSocial` (const) + +```ts +const signInWithSocial = async (context: ControllerContext, provider: string): Promise => { + try { + assertOk(await context.authClient.signIn.social({ callbackURL: resolveAfterSignIn(context.redirects.afterSignIn), provider })); + } + catch (error) { + notifyError(context, error, context.localization.signInFailed); + } +}; +``` + +### `signOut` (const) + +```ts +const signOut = async (context: ControllerContext): Promise => { + try { + assertOk(await context.authClient.signOut()); + context.onSessionChange?.(); + context.nav.replace(context.redirects.afterSignOut); + } + catch (error) { + context.onError?.(error); + } +}; +``` + +### `slugify` (const) + +```ts +const slugify = (value: string): string => value + .toLowerCase() + .trim() + .replaceAll(/[^a-z0-9]+/gu, "-") + .replaceAll(/^-|-$/gu, ""); +``` + +### `subscribeToasts` (const) + +```ts +const subscribeToasts = (onChange: () => void): (() => void) => store.subscribe(onChange); +``` + +### `totpSecret` (const) + +```ts +const totpSecret = (totpUri?: string): string | undefined => { + if (totpUri === undefined || totpUri === "") { + return undefined; + } + const query = totpUri.slice(totpUri.indexOf("?") + 1); + const secret = new URLSearchParams(query).get("secret"); + return secret === null || secret === "" ? undefined : secret; +}; +``` + +### `userInitials` (const) + +```ts +const userInitials = (user?: AuthUser): string => { + const name = user?.name?.trim(); + if (name !== undefined && name !== "") { + const parts = name.split(WHITESPACE).filter((part) => part !== ""); + const first = parts.at(0) ?? ""; + const last = parts.at(-1) ?? ""; + const initials = parts.length > 1 ? `${first.charAt(0)}${last.charAt(0)}` : first.slice(0, 2); + return initials.toUpperCase(); + } + const email = user?.email?.trim(); + return email === undefined || email === "" ? "?" : email.charAt(0).toUpperCase(); +}; +``` + +### `userLabel` (const) + +```ts +const userLabel = (user?: AuthUser): string => { + const name = user?.name?.trim(); + if (name !== undefined && name !== "") { + return name; + } + return user?.email ?? ""; +}; +``` + +### `validatePassword` (const) + +```ts +const validatePassword = (value: string, localization: Localization, policy: PasswordPolicy = {}): string | undefined => { + if (value.trim() === "") { + return localization.passwordRequired; + } + const minLength = policy.minLength ?? DEFAULT_PASSWORD_POLICY.minLength; + const maxLength = policy.maxLength ?? DEFAULT_PASSWORD_POLICY.maxLength; + if (value.length < minLength) { + return localization.passwordTooShort.replace("{min}", String(minLength)); + } + if (value.length > maxLength) { + return localization.passwordTooLong.replace("{max}", String(maxLength)); + } + if (policy.requireLowercase === true && !LOWERCASE.test(value)) { + return localization.passwordRuleLowercase; + } + if (policy.requireUppercase === true && !UPPERCASE.test(value)) { + return localization.passwordRuleUppercase; + } + if (policy.requireDigit === true && !DIGIT.test(value)) { + return localization.passwordRuleDigit; + } + if (policy.requireSymbol === true && !SYMBOL.test(value)) { + return localization.passwordRuleSymbol; + } + return undefined; +}; +``` + +### `withRedirectTo` (const) + +```ts +const withRedirectTo = (path: string): string => { + const target = readRedirectTo(); + if (target === undefined) { + return path; + } + const [base, existing = ""] = path.split("?"); + const parameters = new URLSearchParams(existing); + parameters.set("redirectTo", target); + return `${base ?? path}?${parameters.toString()}`; +}; +``` + +## `@lunora/auth-ui/react` + +### `ACCEPTED_TYPES` (const) + +```ts +const ACCEPTED_TYPES = new Set(["image/avif", "image/gif", "image/jpeg", "image/png", "image/webp"]); +``` + +### `ACCEPT_ATTRIBUTE` (const) + +```ts +const ACCEPT_ATTRIBUTE = [...ACCEPTED_TYPES].join(","); +``` + +### `AcceptInvitationActions` (interface) + +```ts +interface AcceptInvitationActions { + accept: () => Promise; + load: () => Promise; + reject: () => Promise; +} +``` + +### `AcceptInvitationCard` (unknown) + +```ts +AcceptInvitationCard +``` + +### `AcceptInvitationCardProps` (unknown) + +```ts +AcceptInvitationCardProps +``` + +### `AcceptInvitationController` (type) + +```ts +type AcceptInvitationController = Controller; +``` + +### `AcceptInvitationOptions` (interface) + +```ts +interface AcceptInvitationOptions { + autoLoad?: boolean; + invitationId?: string; +} +``` + +### `AcceptInvitationState` (interface) + +```ts +interface AcceptInvitationState { + error?: string; + invitation?: AuthInvitationDetail; + loading: boolean; + status: FlowStatus; +} +``` + +### `AccountsActions` (interface) + +```ts +interface AccountsActions { + link: (provider: string) => Promise; + refetch: () => Promise; + unlink: (providerId: string, accountId?: string) => Promise; +} +``` + +### `AccountsController` (type) + +```ts +type AccountsController = Controller, AccountsActions>; +``` + +### `ActiveMemberActions` (interface) + +```ts +interface ActiveMemberActions { + refetch: () => Promise; +} +``` + +### `ActiveMemberController` (type) + +```ts +type ActiveMemberController = Controller; +``` + +### `ActiveMemberState` (interface) + +```ts +interface ActiveMemberState { + error?: string; + loading: boolean; + role?: string; + status: FlowStatus; +} +``` + +### `AdminUsersActions` (interface) + +```ts +interface AdminUsersActions { + ban: (userId: string, reason?: string) => Promise; + impersonate: (userId: string) => Promise; + refetch: () => Promise; + remove: (userId: string) => Promise; + setRole: (userId: string, role: string) => Promise; + setSearch: (value: string) => Promise; + stopImpersonating: () => Promise; + unban: (userId: string) => Promise; +} +``` + +### `AdminUsersCard` (unknown) + +```ts +AdminUsersCard +``` + +### `AdminUsersController` (type) + +```ts +type AdminUsersController = Controller; +``` + +### `AdminUsersOptions` (interface) + +```ts +interface AdminUsersOptions { + autoLoad?: boolean; + debounceMs?: number; + limit?: number; +} +``` + +### `AdminUsersState` (type) + +```ts +type AdminUsersState = ResourceState; +``` + +### `AnonymousButton` (unknown) + +```ts +AnonymousButton +``` + +### `AppearanceCard` (unknown) + +```ts +AppearanceCard +``` + +### `AuthAccount` (interface) + +```ts +interface AuthAccount { + accountId?: string; + createdAt?: Date | string; + id?: string; + providerId?: string; + scopes?: string[]; +} +``` + +### `AuthActionError` (class) + +```ts +class AuthActionError extends Error { + public readonly code?: string; + public readonly status?: number; + public constructor(error: AuthFetchError) { + super(error.message ?? error.statusText ?? "Authentication request failed"); + this.name = "AuthActionError"; + this.code = error.code; + this.status = error.status; + } +} +``` + +### `AuthAdminUser` (interface) + +```ts +interface AuthAdminUser extends AuthUser { + banExpires?: Date | string; + banned?: boolean; + banReason?: string; + createdAt?: Date | string; + role?: string; +} +``` + +### `AuthCard` (unknown) + +```ts +AuthCard +``` + +### `AuthCardProps` (unknown) + +```ts +AuthCardProps +``` + +### `AuthClient` (interface) + +```ts +interface AuthClient { + admin: { + banUser: (input: { + banExpiresIn?: number; + banReason?: string; + userId: string; + }) => Promise>; + impersonateUser: (input: { + userId: string; + }) => Promise>; + listUsers: (input?: { + query?: { + limit?: number; + offset?: number; + searchField?: string; + searchOperator?: string; + searchValue?: string; + }; + }) => Promise>; + removeUser: (input: { + userId: string; + }) => Promise>; + setRole: (input: { + role: string; + userId: string; + }) => Promise>; + stopImpersonating: () => Promise>; + unbanUser: (input: { + userId: string; + }) => Promise>; + }; + changeEmail: (input: { + callbackURL?: string; + newEmail: string; + }) => Promise>; + changePassword: (input: { + currentPassword: string; + newPassword: string; + revokeOtherSessions?: boolean; + }) => Promise>; + deleteUser: (input: { + callbackURL?: string; + password?: string; + }) => Promise>; + device: { + approve: (input: { + userCode: string; + }) => Promise>; + deny: (input: { + userCode: string; + }) => Promise>; + }; + emailOtp: { + resetPassword: (input: { + email: string; + otp: string; + password: string; + }) => Promise>; + sendVerificationOtp: (input: { + email: string; + type: "email-verification" | "forget-password" | "sign-in"; + }) => Promise>; + }; + forgetPassword: (input: { + email: string; + redirectTo?: string; + }) => Promise>; + getSession: () => Promise>; + isUsernameAvailable: (input: { + username: string; + }) => Promise>; + linkSocial: (input: { + callbackURL?: string; + provider: string; + }) => Promise>; + listAccounts: () => Promise>; + listSessions: () => Promise>; + multiSession: { + listDeviceSessions: () => Promise>; + revoke: (input: { + sessionToken: string; + }) => Promise>; + setActive: (input: { + sessionToken: string; + }) => Promise>; + }; + oauth2: { + consent: (input: { + accept: boolean; + scope?: string; + }) => Promise>; + deleteConsent: (input: { + id: string; + }) => Promise>; + getConsent: (input: { + query: { + id: string; + }; + }) => Promise>; + getConsents: () => Promise>; + }; + oneTap: (input?: { + callbackURL?: string; + }) => Promise>; + organization: { + acceptInvitation: (input: { + invitationId: string; + }) => Promise>; + cancelInvitation: (input: { + invitationId: string; + }) => Promise>; + create: (input: { + name: string; + slug: string; + }) => Promise>; + createTeam: (input: { + name: string; + organizationId?: string; + }) => Promise>; + delete: (input: { + organizationId: string; + }) => Promise>; + getFullOrganization: (input?: { + organizationId?: string; + }) => Promise>; + getInvitation: (input: { + query: { + id: string; + }; + }) => Promise>; + inviteMember: (input: { + email: string; + organizationId?: string; + role: string; + teamId?: string; + }) => Promise>; + leave: (input: { + organizationId: string; + }) => Promise>; + list: () => Promise>; + listTeams: (input?: { + query?: { + organizationId?: string; + }; + }) => Promise>; + listUserInvitations: () => Promise>; + rejectInvitation: (input: { + invitationId: string; + }) => Promise>; + removeMember: (input: { + memberIdOrEmail: string; + organizationId?: string; + }) => Promise>; + removeTeam: (input: { + organizationId?: string; + teamId: string; + }) => Promise>; + setActive: (input: { + organizationId: string; + }) => Promise>; + update: (input: { + data: { + logo?: string; + name?: string; + slug?: string; + }; + organizationId?: string; + }) => Promise>; + updateMemberRole: (input: { + memberId: string; + organizationId?: string; + role: string; + }) => Promise>; + updateTeam: (input: { + data: { + name?: string; + }; + teamId: string; + }) => Promise>; + }; + passkey: { + addPasskey: (input?: { + authenticatorAttachment?: "cross-platform" | "platform"; + name?: string; + }) => Promise; + deletePasskey: (input: { + id: string; + }) => Promise>; + listUserPasskeys: () => Promise>; + updatePasskey: (input: { + id: string; + name: string; + }) => Promise>; + }; + phoneNumber: { + requestPasswordReset: (input: { + phoneNumber: string; + }) => Promise>; + resetPassword: (input: { + newPassword: string; + otp: string; + phoneNumber: string; + }) => Promise>; + sendOtp: (input: { + phoneNumber: string; + }) => Promise>; + verify: (input: { + code: string; + disableSession?: boolean; + phoneNumber: string; + updatePhoneNumber?: boolean; + }) => Promise>; + }; + resetPassword: (input: { + newPassword: string; + token?: string; + }) => Promise>; + revokeOtherSessions: () => Promise>; + revokeSession: (input: { + token: string; + }) => Promise>; + sendVerificationEmail: (input: { + callbackURL?: string; + email: string; + }) => Promise>; + signIn: { + anonymous: () => Promise>; + email: (input: { + callbackURL?: string; + email: string; + password: string; + rememberMe?: boolean; + }) => Promise>; + emailOtp: (input: { + email: string; + otp: string; + }) => Promise>; + magicLink: (input: { + callbackURL?: string; + email: string; + }) => Promise>; + phoneNumber: (input: { + password: string; + phoneNumber: string; + rememberMe?: boolean; + }) => Promise>; + social: (input: { + callbackURL?: string; + provider: string; + }) => Promise>; + username: (input: { + password: string; + rememberMe?: boolean; + username: string; + }) => Promise>; + }; + signOut: () => Promise>; + signUp: { + email: (input: { + callbackURL?: string; + email: string; + name: string; + password: string; + username?: string; + }) => Promise>; + }; + twoFactor: { + disable: (input: { + password: string; + }) => Promise>; + enable: (input: { + password: string; + }) => Promise>; + generateBackupCodes: (input: { + password: string; + }) => Promise>; + verifyBackupCode: (input: { + code: string; + trustDevice?: boolean; + }) => Promise>; + verifyOtp: (input: { + code: string; + trustDevice?: boolean; + }) => Promise>; + verifyTotp: (input: { + code: string; + trustDevice?: boolean; + }) => Promise>; + }; + unlinkAccount: (input: { + accountId?: string; + providerId: string; + }) => Promise>; + updateUser: (input: { + image?: string; + name?: string; + username?: string; + }) => Promise>; + verifyEmail: (input: { + query: { + token: string; + }; + }) => Promise>; +} +``` + +### `AuthDeviceRequest` (interface) + +```ts +interface AuthDeviceRequest { + clientId?: string; + scope?: string; + userCode?: string; +} +``` + +### `AuthDeviceSession` (interface) + +```ts +interface AuthDeviceSession { + session?: AuthSession; + user?: AuthUser; +} +``` + +### `AuthDivider` (unknown) + +```ts +AuthDivider +``` + +### `AuthFetchError` (interface) + +```ts +interface AuthFetchError { + code?: string; + message?: string; + status?: number; + statusText?: string; +} +``` + +### `AuthFullOrganization` (interface) + +```ts +interface AuthFullOrganization extends AuthOrganization { + invitations?: AuthInvitation[]; + members?: AuthMember[]; +} +``` + +### `AuthInvitation` (interface) + +```ts +interface AuthInvitation { + email?: string; + id?: string; + role?: string; + status?: string; +} +``` + +### `AuthInvitationDetail` (interface) + +```ts +interface AuthInvitationDetail extends AuthInvitation { + expiresAt?: Date | string; + inviterEmail?: string; + organizationName?: string; + organizationSlug?: string; +} +``` + +### `AuthLink` (unknown) + +```ts +AuthLink +``` + +### `AuthMember` (interface) + +```ts +interface AuthMember { + id?: string; + role?: string; + user?: { + email?: string; + name?: string; + }; + userId?: string; +} +``` + +### `AuthOrganization` (interface) + +```ts +interface AuthOrganization { + id?: string; + logo?: string; + name?: string; + slug?: string; +} +``` + +### `AuthPasskey` (interface) + +```ts +interface AuthPasskey { + createdAt?: Date | string; + deviceType?: string; + id?: string; + name?: string; +} +``` + +### `AuthResponse` (interface) + +```ts +interface AuthResponse { + data: T | null; + error: AuthFetchError | null; +} +``` + +### `AuthSession` (interface) + +```ts +interface AuthSession { + createdAt?: string; + id?: string; + ipAddress?: string; + token?: string; + userAgent?: string; +} +``` + +### `AuthTeam` (interface) + +```ts +interface AuthTeam { + id?: string; + name?: string; + organizationId?: string; +} +``` + +### `AuthUIConfig` (interface) + +```ts +interface AuthUIConfig { + authClient: AnyAuthClient; + avatar?: AvatarConfig; + basePath?: string; + discover?: boolean; + forgotPassword?: { + method?: "link" | "otp"; + }; + localization?: Partial; + nav: NavAdapter; + onError?: (error: unknown) => void; + onSessionChange?: () => void; + organization?: { + roles?: boolean; + showSlug?: boolean; + teams?: boolean; + }; + password?: PasswordPolicy; + plugins?: PluginFlags; + redirects?: RedirectConfig; + social?: ReadonlyArray; + theme?: (defaults: ThemeTokens) => ThemeTokens; + viewPaths?: ViewPaths; +} +``` + +### `AuthUIProvider` (unknown) + +```ts +AuthUIProvider +``` + +### `AuthUIProviderProps` (unknown) + +```ts +AuthUIProviderProps +``` + +### `AuthUser` (interface) + +```ts +interface AuthUser { + email?: string; + emailVerified?: boolean; + id?: string; + image?: string; + name?: string; +} +``` + +### `AuthView` (unknown) + +```ts +AuthView +``` + +### `AuthViewProps` (unknown) + +```ts +AuthViewProps +``` + +### `AuthorizedAppsActions` (interface) + +```ts +interface AuthorizedAppsActions { + refetch: () => Promise; + revoke: (consentId: string) => Promise; +} +``` + +### `AuthorizedAppsCard` (unknown) + +```ts +AuthorizedAppsCard +``` + +### `AuthorizedAppsController` (type) + +```ts +type AuthorizedAppsController = Controller, AuthorizedAppsActions>; +``` + +### `AvailabilityStatus` (type) + +```ts +type AvailabilityStatus = "available" | "checking" | "idle" | "taken" | "unknown"; +``` + +### `AvatarCard` (unknown) + +```ts +AvatarCard +``` + +### `AvatarConfig` (interface) + +```ts +interface AvatarConfig { + maxSize?: number; + upload?: (file: File) => Promise; +} +``` + +### `AvatarUploadActions` (interface) + +```ts +interface AvatarUploadActions { + remove: () => Promise; + upload: (file: File) => Promise; +} +``` + +### `AvatarUploadController` (type) + +```ts +type AvatarUploadController = Controller; +``` + +### `AvatarUploadState` (interface) + +```ts +interface AvatarUploadState { + error?: string; + imageUrl?: string; + status: FlowStatus; +} +``` + +### `BackupCodeSignInField` (type) + +```ts +type BackupCodeSignInField = "code"; +``` + +### `BackupCodesCard` (unknown) + +```ts +BackupCodesCard +``` + +### `BackupCodesField` (type) + +```ts +type BackupCodesField = "password"; +``` + +### `BackupCodesHandle` (interface) + +```ts +interface BackupCodesHandle { + controller: FormController; + getCodes: () => ReadonlyArray; + subscribeCodes: (onChange: () => void) => () => void; +} +``` + +### `CAPTCHA_HEADER` (const) + +```ts +const CAPTCHA_HEADER = "x-captcha-response"; +``` + +### `CAPTCHA_PROVIDERS` (const) + +```ts +const PROVIDERS: Readonly> = { + captchafox: { global: "CaptchaFox", script: "https://cdn.captchafox.com/api.js?render=explicit" }, + "cloudflare-turnstile": { global: "turnstile", script: "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit" }, + "google-recaptcha": { global: "grecaptcha", script: "https://www.google.com/recaptcha/api.js?render=explicit" }, + hcaptcha: { global: "hcaptcha", script: "https://js.hcaptcha.com/1/api.js?render=explicit" }, +}; +``` + +### `Captcha` (unknown) + +```ts +Captcha +``` + +### `CaptchaProps` (unknown) + +```ts +CaptchaProps +``` + +### `CaptchaProvider` (type) + +```ts +type CaptchaProvider = "captchafox" | "cloudflare-turnstile" | "google-recaptcha" | "hcaptcha"; +``` + +### `ChangeEmailCard` (unknown) + +```ts +ChangeEmailCard +``` + +### `ChangeEmailField` (type) + +```ts +type ChangeEmailField = "newEmail"; +``` + +### `ChangePasswordCard` (unknown) + +```ts +ChangePasswordCard +``` + +### `ChangePasswordField` (type) + +```ts +type ChangePasswordField = "confirmPassword" | "currentPassword" | "newPassword"; +``` + +### `ConsentActions` (interface) + +```ts +interface ConsentActions { + accept: () => Promise; + deny: () => Promise; + load: () => Promise; +} +``` + +### `ConsentCard` (unknown) + +```ts +ConsentCard +``` + +### `ConsentCardProps` (unknown) + +```ts +ConsentCardProps +``` + +### `ConsentController` (type) + +```ts +type ConsentController = Controller; +``` + +### `ConsentOptions` (interface) + +```ts +interface ConsentOptions { + autoLoad?: boolean; + consentId?: string; +} +``` + +### `ConsentState` (interface) + +```ts +interface ConsentState { + error?: string; + loading: boolean; + request?: OAuthPendingConsent; + status: FlowStatus; +} +``` + +### `Controller` (interface) + +```ts +interface Controller { + actions: TActions; + destroy: () => void; + getState: () => TState; + subscribe: (onChange: () => void) => () => void; +} +``` + +### `ControllerContext` (interface) + +```ts +interface ControllerContext { + authClient: AuthClient; + avatar: AvatarConfig; + basePath: string; + credentials: boolean; + forgotPasswordMethod: "link" | "otp"; + localization: Localization; + nav: NavAdapter; + onError?: (error: unknown) => void; + onSessionChange?: () => void; + organization: { + allowUserToCreate: boolean; + invitationLimit?: number; + limit?: number; + membershipLimit?: number; + roles: boolean; + showSlug: boolean; + teams: boolean; + }; + password: PasswordPolicy; + plugins: Required; + redirects: Required; + signUp: boolean; + social: ReadonlyArray; + themeVariables: Readonly>; + viewPaths: Required; +} +``` + +### `DEFAULT_AVATAR_MAX_SIZE` (const) + +```ts +const DEFAULT_AVATAR_MAX_SIZE = 2 * 1024 * 1024; +``` + +### `DEFAULT_BASE_PATH` (const) + +```ts +const DEFAULT_BASE_PATH = "/api/auth"; +``` + +### `DEFAULT_LOCALIZATION` (const) + +```ts +const DEFAULT_LOCALIZATION: Localization = { + accountsEmpty: "No accounts linked yet.", + accountsLastOne: "You can't unlink your only sign-in method.", + accountsLink: "Link account", + accountsTitle: "Linked accounts", + activeBadge: "Active", + adminBan: "Ban", + adminImpersonate: "Impersonate", + adminSearch: "Search users by email", + adminStopImpersonating: "Stop impersonating", + adminTitle: "Users", + adminUnban: "Unban", + adminUsersEmpty: "No users match that search.", + anonymousSignIn: "Continue as guest", + appearance: "Appearance", + authorizedApps: "Authorized applications", + authorizedAppsEmpty: "You haven't authorized any applications.", + avatar: "Avatar", + avatarNoUploader: "Avatar uploads are not configured for this app.", + avatarRemove: "Remove photo", + avatarTooLarge: "That image is too large.", + avatarUpload: "Upload photo", + avatarUploadFailed: "Could not upload that image. Try again.", + avatarWrongType: "Choose a PNG, JPEG, WebP, GIF, or AVIF image.", + backToSignIn: "Back to sign in", + backupCodeLabel: "Backup code", + backupCodes: "Save these backup codes somewhere safe:", + backupCodeSignIn: "Use a backup code", + backupCodesRegenerate: "Regenerate backup codes", + backupCodesRegenerated: "New backup codes generated. The old ones no longer work.", + cancel: "Cancel", + changeEmail: "Change email", + changeEmailSent: "Check your new inbox to confirm the change.", + changePassword: "Change password", + changePasswordDone: "Your password has been changed.", + codeLabel: "Verification code", + confirmPasswordLabel: "Confirm password", + consentAllow: "Allow", + consentDeny: "Deny", + consentExpired: "This request is no longer valid. Start again from the application.", + consentMissing: "There's no authorization request to review.", + consentTitle: "Authorize application", + consentWants: "wants access to:", + copied: "Copied", + copy: "Copy", + createOrganization: "Create organization", + currentPasswordLabel: "Current password", + currentSession: "This device", + deleteAccount: "Delete account", + deleteAccountWarning: "This permanently deletes your account and cannot be undone.", + deviceApprove: "Approve", + deviceApproved: "Device approved. You can close this page.", + deviceCodeLabel: "Device code", + deviceCodeRequired: "Enter the code shown on your device.", + deviceDenied: "Device denied.", + deviceDeny: "Deny", + deviceFailed: "That code is not valid or has expired.", + deviceTitle: "Authorize device", + emailInvalid: "Enter a valid email address.", + emailLabel: "Email", + emailOtp: "Email me a code", + emailOtpSent: "We emailed you a one-time code.", + emailRequired: "Email is required.", + forgotPassword: "Reset password", + forgotPasswordLink: "Forgot your password?", + forgotPasswordSent: "If that email exists, a reset link is on its way.", + genericError: "Something went wrong. Please try again.", + haveAccount: "Already have an account? Sign in", + invitationAccept: "Accept invitation", + invitationMissing: "That invitation link is not valid or has expired.", + invitationReject: "Decline", + invitations: "Pending invitations", + invitationsEmpty: "No invitations waiting for you.", + invitationTitle: "You've been invited", + inviteEmailLabel: "Email to invite", + inviteMember: "Invite member", + lastUsed: "Last used", + leaveOrganization: "Leave organization", + magicLink: "Email me a link", + magicLinkSent: "Check your email for a sign-in link.", + members: "Members", + multiSessionEmpty: "No other accounts signed in on this device.", + multiSessionTitle: "Switch account", + nameLabel: "Name", + nameRequired: "Name is required.", + newEmailLabel: "New email", + newPasswordLabel: "New password", + noAccount: "Don't have an account? Sign up", + noOrganizations: "You're not in any organization yet.", + organizationCreateDisallowed: "Your account can't create organizations.", + organizationLimitReached: "You've reached the maximum number of organizations.", + organizationLogo: "Logo URL", + organizationName: "Organization name", + organizationNameRequired: "Organization name is required.", + organizations: "Organizations", + organizationSaved: "Organization settings saved.", + organizationSettings: "Organization settings", + organizationSlug: "Slug", + organizationSlugRequired: "Slug is required.", + otpRequired: "Enter the code we sent you.", + passkeyAdd: "Add a passkey", + passkeyName: "Passkey name", + passkeyRename: "Rename", + passkeys: "Passkeys", + passkeysEmpty: "No passkeys registered yet.", + passkeyUnnamed: "Unnamed passkey", + passwordLabel: "Password", + passwordMismatch: "Passwords do not match.", + passwordRequired: "Password is required.", + passwordRuleDigit: "At least one number", + passwordRuleLength: "At least {min} characters", + passwordRuleLowercase: "At least one lowercase letter", + passwordRuleSymbol: "At least one symbol", + passwordRuleUppercase: "At least one uppercase letter", + passwordTooLong: "Password must be at most {max} characters.", + passwordTooShort: "Password must be at least {min} characters.", + phoneLabel: "Phone number", + phoneOtpSent: "We texted you a code.", + phoneRequired: "Phone number is required.", + phoneVerified: "Phone number verified.", + phoneVerify: "Verify phone number", + profile: "Profile", + profileSaved: "Your profile has been updated.", + remove: "Remove", + resetPassword: "Set new password", + resetPasswordDone: "Your password has been updated. You can sign in now.", + resetPasswordOtpDescription: "Enter the code we emailed you, then choose a new password.", + revoke: "Revoke", + revokeAccess: "Revoke access", + revokeOthers: "Sign out other sessions", + roleLabel: "Role", + saveChanges: "Save changes", + sendNewCode: "Use a different email", + sessionNotFresh: "For your security, sign in again before making this change.", + sessions: "Active sessions", + sessionsEmpty: "No other active sessions.", + signIn: "Sign in", + signInFailed: "Could not sign you in. Check your details and try again.", + signInWith: "Continue with", + signOut: "Sign out", + signUp: "Create account", + signUpFailed: "Could not create your account. Try again.", + switchAccount: "Switch to this account", + switchOrganization: "Switch", + teamNameLabel: "Team name", + teams: "Teams", + teamsEmpty: "No teams yet.", + themeDark: "Dark", + themeLight: "Light", + themeSystem: "System", + twoFactor: "Verify", + twoFactorDisable: "Disable 2FA", + twoFactorEnable: "Enable 2FA", + twoFactorEnabled: "Two-factor authentication is on.", + twoFactorFailed: "That code is not valid. Try again.", + twoFactorNeedsPassword: "Set a password before turning on two-factor authentication.", + twoFactorScan: "Add this account to your authenticator app using the setup key below, then enter the 6-digit code it generates.", + twoFactorSecret: "Setup key:", + twoFactorSetup: "Two-factor authentication", + twoFactorUseAuthenticator: "Use your authenticator app instead", + unknownDevice: "Unknown device", + usernameAvailable: "That username is available.", + usernameChecking: "Checking…", + usernameLabel: "Username", + usernameRequired: "Username is required.", + usernameSaved: "Your username has been updated.", + usernameTaken: "That username is taken.", + verifyEmail: "Verify your email", + verifyEmailFailed: "We couldn't verify that link. Request a new one.", + verifyEmailNoToken: "This page needs a verification link to work.", + verifyEmailResend: "Send a new link", + verifyEmailSent: "Check your email for a verification link.", + verifyEmailVerifying: "Verifying your email…", +}; +``` + +### `DEFAULT_PASSWORD_POLICY` (const) + +```ts +const DEFAULT_PASSWORD_POLICY: Required> = { maxLength: 128, minLength: 8 }; +``` + +### `DEFAULT_THEME_TOKENS` (const) + +```ts +const DEFAULT_THEME_TOKENS: ThemeTokens = { + background: "hsl(0 0% 100%)", + border: "hsl(228 16% 88%)", + card: "hsl(0 0% 100%)", + cardForeground: "hsl(240 14% 10%)", + destructive: "hsl(0 72% 45%)", + fontMono: "ui-monospace, monospace", + fontSans: "ui-sans-serif, system-ui, sans-serif", + input: "hsl(228 16% 88%)", + muted: "hsl(228 16% 93%)", + mutedForeground: "hsl(235 9% 42%)", + primary: "hsl(240 14% 12%)", + primaryForeground: "hsl(228 32% 97%)", + radius: "0.5rem", + ring: "hsl(256 72% 68%)", + secondary: "hsl(228 16% 93%)", + secondaryForeground: "hsl(240 14% 14%)", + success: "hsl(160 60% 28%)", +}; +``` + +### `DeleteAccountCard` (unknown) + +```ts +DeleteAccountCard +``` + +### `DeleteAccountField` (type) + +```ts +type DeleteAccountField = "password"; +``` + +### `DeviceAuthorizationActions` (interface) + +```ts +interface DeviceAuthorizationActions { + approve: () => Promise; + deny: () => Promise; + setCode: (value: string) => void; +} +``` + +### `DeviceAuthorizationCard` (unknown) + +```ts +DeviceAuthorizationCard +``` + +### `DeviceAuthorizationCardProps` (unknown) + +```ts +DeviceAuthorizationCardProps +``` + +### `DeviceAuthorizationController` (type) + +```ts +type DeviceAuthorizationController = Controller; +``` + +### `DeviceAuthorizationOptions` (interface) + +```ts +interface DeviceAuthorizationOptions { + userCode?: string; +} +``` + +### `DeviceAuthorizationState` (interface) + +```ts +interface DeviceAuthorizationState { + code: string; + decision?: "approved" | "denied"; + error?: string; + status: FlowStatus; +} +``` + +### `DeviceSessionsActions` (interface) + +```ts +interface DeviceSessionsActions { + refetch: () => Promise; + revoke: (sessionToken: string) => Promise; + setActive: (sessionToken: string) => Promise; +} +``` + +### `DeviceSessionsController` (type) + +```ts +type DeviceSessionsController = Controller, DeviceSessionsActions>; +``` + +### `DiscoveredConfig` (interface) + +```ts +interface DiscoveredConfig { + emailAndPassword: boolean; + organization?: DiscoveredOrganization; + plugins?: ReadonlyArray; + signUp: boolean; + socialProviders?: ReadonlyArray; +} +``` + +### `DiscoveredOrganization` (interface) + +```ts +interface DiscoveredOrganization { + allowUserToCreate: boolean; + enabled: boolean; + invitationLimit?: number; + limit?: number; + membershipLimit?: number; + roles: boolean; + teams: boolean; +} +``` + +### `DiscoveryHandle` (interface) + +```ts +interface DiscoveryHandle { + getState: () => DiscoveryState; + subscribe: (onChange: () => void) => () => void; +} +``` + +### `DiscoveryState` (interface) + +```ts +interface DiscoveryState { + config?: DiscoveredConfig; + status: DiscoveryStatus; +} +``` + +### `DiscoveryStatus` (type) + +```ts +type DiscoveryStatus = "loading" | "ready" | "unavailable"; +``` + +### `EmailOtpActions` (interface) + +```ts +interface EmailOtpActions { + back: () => void; + reset: () => void; + sendCode: () => Promise; + setCode: (value: string) => void; + setEmail: (value: string) => void; + verify: () => Promise; +} +``` + +### `EmailOtpCard` (unknown) + +```ts +EmailOtpCard +``` + +### `EmailOtpController` (type) + +```ts +type EmailOtpController = Controller; +``` + +### `EmailOtpState` (interface) + +```ts +interface EmailOtpState { + code: FieldState; + email: FieldState; + formError?: string; + status: FlowStatus; + step: "request" | "verify"; + successMessage?: string; +} +``` + +### `ErrorToaster` (unknown) + +```ts +ErrorToaster +``` + +### `FLOW_NAMES` (const) + +```ts +const FLOW_NAMES: ReadonlyArray = [ + "admin", + "anonymous", + "apiKey", + "deviceAuthorization", + "emailOtp", + "lastLoginMethod", + "magicLink", + "multiSession", + "oauthProvider", + "oneTap", + "organization", + "passkey", + "phoneNumber", + "twoFactor", + "username", +]; +``` + +### `Field` (unknown) + +```ts +Field +``` + +### `FieldProps` (unknown) + +```ts +FieldProps +``` + +### `FieldSpec` (interface) + +```ts +interface FieldSpec { + initial?: string; + validate?: (value: string, values: Record, localization: Localization) => string | undefined; +} +``` + +### `FieldState` (interface) + +```ts +interface FieldState { + error?: string; + touched: boolean; + value: string; +} +``` + +### `FlowName` (type) + +```ts +type FlowName = keyof PluginFlags; +``` + +### `FlowStatus` (type) + +```ts +type FlowStatus = "error" | "idle" | "submitting" | "success"; +``` + +### `ForgotPasswordCard` (unknown) + +```ts +ForgotPasswordCard +``` + +### `ForgotPasswordCardProps` (unknown) + +```ts +ForgotPasswordCardProps +``` + +### `ForgotPasswordField` (type) + +```ts +type ForgotPasswordField = "email"; +``` + +### `ForgotPasswordOptions` (interface) + +```ts +interface ForgotPasswordOptions { + resetPath?: string; +} +``` + +### `FormActions` (interface) + +```ts +interface FormActions { + blur: (field: TField) => void; + load: () => Promise; + reset: () => void; + setField: (field: TField, value: string) => void; + submit: () => Promise; +} +``` + +### `FormBanner` (unknown) + +```ts +FormBanner +``` + +### `FormController` (type) + +```ts +type FormController = Controller, FormActions>; +``` + +### `FormControllerOptions` (interface) + +```ts +interface FormControllerOptions { + fallbackError: (localization: Localization) => string; + fields: Record>; + prefill?: (context: ControllerContext) => Promise>>; + sessionChanging?: boolean; + submit: (values: Record, context: ControllerContext) => Promise; +} +``` + +### `FormState` (interface) + +```ts +interface FormState { + fields: Record; + formError?: string; + loading: boolean; + status: FlowStatus; + successMessage?: string; +} +``` + +### `FormSubmitResult` (interface) + +```ts +interface FormSubmitResult { + redirectTo?: string; + successMessage?: string; +} +``` + +### `LAST_LOGIN_METHOD_COOKIE` (const) + +```ts +const LAST_LOGIN_METHOD_COOKIE = "better-auth.last_used_login_method"; +``` + +### `LAST_METHOD_EMAIL` (const) + +```ts +const LAST_METHOD_EMAIL = "email"; +``` + +### `LAST_METHOD_MAGIC_LINK` (const) + +```ts +const LAST_METHOD_MAGIC_LINK = "magic-link"; +``` + +### `LAST_METHOD_PASSKEY` (const) + +```ts +const LAST_METHOD_PASSKEY = "passkey"; +``` + +### `LinkedAccountsCard` (unknown) + +```ts +LinkedAccountsCard +``` + +### `Localization` (interface) + +```ts +interface Localization { + accountsEmpty: string; + accountsLastOne: string; + accountsLink: string; + accountsTitle: string; + activeBadge: string; + adminBan: string; + adminImpersonate: string; + adminSearch: string; + adminStopImpersonating: string; + adminTitle: string; + adminUnban: string; + adminUsersEmpty: string; + anonymousSignIn: string; + appearance: string; + authorizedApps: string; + authorizedAppsEmpty: string; + avatar: string; + avatarNoUploader: string; + avatarRemove: string; + avatarTooLarge: string; + avatarUpload: string; + avatarUploadFailed: string; + avatarWrongType: string; + backToSignIn: string; + backupCodeLabel: string; + backupCodes: string; + backupCodeSignIn: string; + backupCodesRegenerate: string; + backupCodesRegenerated: string; + cancel: string; + changeEmail: string; + changeEmailSent: string; + changePassword: string; + changePasswordDone: string; + codeLabel: string; + confirmPasswordLabel: string; + consentAllow: string; + consentDeny: string; + consentExpired: string; + consentMissing: string; + consentTitle: string; + consentWants: string; + copied: string; + copy: string; + createOrganization: string; + currentPasswordLabel: string; + currentSession: string; + deleteAccount: string; + deleteAccountWarning: string; + deviceApprove: string; + deviceApproved: string; + deviceCodeLabel: string; + deviceCodeRequired: string; + deviceDenied: string; + deviceDeny: string; + deviceFailed: string; + deviceTitle: string; + emailInvalid: string; + emailLabel: string; + emailOtp: string; + emailOtpSent: string; + emailRequired: string; + forgotPassword: string; + forgotPasswordLink: string; + forgotPasswordSent: string; + genericError: string; + haveAccount: string; + invitationAccept: string; + invitationMissing: string; + invitationReject: string; + invitations: string; + invitationsEmpty: string; + invitationTitle: string; + inviteEmailLabel: string; + inviteMember: string; + lastUsed: string; + leaveOrganization: string; + magicLink: string; + magicLinkSent: string; + members: string; + multiSessionEmpty: string; + multiSessionTitle: string; + nameLabel: string; + nameRequired: string; + newEmailLabel: string; + newPasswordLabel: string; + noAccount: string; + noOrganizations: string; + organizationCreateDisallowed: string; + organizationLimitReached: string; + organizationLogo: string; + organizationName: string; + organizationNameRequired: string; + organizations: string; + organizationSaved: string; + organizationSettings: string; + organizationSlug: string; + organizationSlugRequired: string; + otpRequired: string; + passkeyAdd: string; + passkeyName: string; + passkeyRename: string; + passkeys: string; + passkeysEmpty: string; + passkeyUnnamed: string; + passwordLabel: string; + passwordMismatch: string; + passwordRequired: string; + passwordRuleDigit: string; + passwordRuleLength: string; + passwordRuleLowercase: string; + passwordRuleSymbol: string; + passwordRuleUppercase: string; + passwordTooLong: string; + passwordTooShort: string; + phoneLabel: string; + phoneOtpSent: string; + phoneRequired: string; + phoneVerified: string; + phoneVerify: string; + profile: string; + profileSaved: string; + remove: string; + resetPassword: string; + resetPasswordDone: string; + resetPasswordOtpDescription: string; + revoke: string; + revokeAccess: string; + revokeOthers: string; + roleLabel: string; + saveChanges: string; + sendNewCode: string; + sessionNotFresh: string; + sessions: string; + sessionsEmpty: string; + signIn: string; + signInFailed: string; + signInWith: string; + signOut: string; + signUp: string; + signUpFailed: string; + switchAccount: string; + switchOrganization: string; + teamNameLabel: string; + teams: string; + teamsEmpty: string; + themeDark: string; + themeLight: string; + themeSystem: string; + twoFactor: string; + twoFactorDisable: string; + twoFactorEnable: string; + twoFactorEnabled: string; + twoFactorFailed: string; + twoFactorNeedsPassword: string; + twoFactorScan: string; + twoFactorSecret: string; + twoFactorSetup: string; + twoFactorUseAuthenticator: string; + unknownDevice: string; + usernameAvailable: string; + usernameChecking: string; + usernameLabel: string; + usernameRequired: string; + usernameSaved: string; + usernameTaken: string; + verifyEmail: string; + verifyEmailFailed: string; + verifyEmailNoToken: string; + verifyEmailResend: string; + verifyEmailSent: string; + verifyEmailVerifying: string; +} +``` + +### `LogoUploadActions` (interface) + +```ts +interface LogoUploadActions { + remove: () => Promise; + upload: (file: File) => Promise; +} +``` + +### `LogoUploadController` (type) + +```ts +type LogoUploadController = Controller; +``` + +### `LogoUploadOptions` (interface) + +```ts +interface LogoUploadOptions { + initialLogo?: string; + organizationId?: string; +} +``` + +### `LogoUploadState` (interface) + +```ts +interface LogoUploadState { + error?: string; + logoUrl?: string; + status: FlowStatus; +} +``` + +### `MIN_PASSWORD_LENGTH` (const) + +```ts +const MIN_PASSWORD_LENGTH = 8; +``` + +### `MagicLinkCard` (unknown) + +```ts +MagicLinkCard +``` + +### `MagicLinkCardProps` (unknown) + +```ts +MagicLinkCardProps +``` + +### `MagicLinkField` (type) + +```ts +type MagicLinkField = "email"; +``` + +### `MembersActions` (interface) + +```ts +interface MembersActions { + cancelInvitation: (invitationId: string) => Promise; + invite: (email: string, role: string) => Promise; + refetch: () => Promise; + removeMember: (memberIdOrEmail: string) => Promise; + updateRole: (memberId: string, role: string) => Promise; +} +``` + +### `MembersCard` (unknown) + +```ts +MembersCard +``` + +### `MembersController` (type) + +```ts +type MembersController = Controller; +``` + +### `MembersState` (interface) + +```ts +interface MembersState { + busy: boolean; + error?: string; + invitations: ReadonlyArray; + loading: boolean; + members: ReadonlyArray; +} +``` + +### `MultiSessionCard` (unknown) + +```ts +MultiSessionCard +``` + +### `NON_SOCIAL_PROVIDERS` (const) + +```ts +const NON_SOCIAL_PROVIDERS = new Set(["credential", "email", "passkey"]); +``` + +### `NavAdapter` (interface) + +```ts +interface NavAdapter { + navigate: (to: string) => void; + replace: (to: string) => void; +} +``` + +### `OAuthConsent` (interface) + +```ts +interface OAuthConsent { + clientId?: string; + clientName?: string; + createdAt?: Date | string; + id?: string; + scopes?: string[]; +} +``` + +### `OAuthPendingConsent` (interface) + +```ts +interface OAuthPendingConsent { + clientId?: string; + clientName?: string; + clientURI?: string; + logoURI?: string; + scope?: string; +} +``` + +### `OneTap` (unknown) + +```ts +OneTap +``` + +### `OrganizationLogoCard` (unknown) + +```ts +OrganizationLogoCard +``` + +### `OrganizationLogoCardProps` (unknown) + +```ts +OrganizationLogoCardProps +``` + +### `OrganizationSettingsCard` (unknown) + +```ts +OrganizationSettingsCard +``` + +### `OrganizationSettingsCardProps` (unknown) + +```ts +OrganizationSettingsCardProps +``` + +### `OrganizationSettingsField` (type) + +```ts +type OrganizationSettingsField = "logo" | "name" | "slug"; +``` + +### `OrganizationSettingsOptions` (interface) + +```ts +interface OrganizationSettingsOptions { + autoLoad?: boolean; + organizationId?: string; +} +``` + +### `OrganizationsActions` (interface) + +```ts +interface OrganizationsActions { + create: (name: string, slug: string) => Promise; + leave: (organizationId: string) => Promise; + refetch: () => Promise; + remove: (organizationId: string) => Promise; + setActive: (organizationId: string) => Promise; +} +``` + +### `OrganizationsCard` (unknown) + +```ts +OrganizationsCard +``` + +### `OrganizationsController` (type) + +```ts +type OrganizationsController = Controller, OrganizationsActions>; +``` + +### `PLUGIN_ID_TO_FLOW` (const) + +```ts +const PLUGIN_ID_TO_FLOW: Readonly> = { + admin: "admin", + anonymous: "anonymous", + "device-authorization": "deviceAuthorization", + "email-otp": "emailOtp", + "last-login-method": "lastLoginMethod", + "magic-link": "magicLink", + "multi-session": "multiSession", + "oauth-provider": "oauthProvider", + "one-tap": "oneTap", + organization: "organization", + passkey: "passkey", + "phone-number": "phoneNumber", + "two-factor": "twoFactor", + username: "username", +}; +``` + +### `PREFILLABLE` (const) + +```ts +const PREFILLABLE = new Set(["email", "name", "username"]); +``` + +### `PasskeysActions` (interface) + +```ts +interface PasskeysActions { + add: (name?: string) => Promise; + refetch: () => Promise; + remove: (id: string) => Promise; + rename: (id: string, name: string) => Promise; +} +``` + +### `PasskeysCard` (unknown) + +```ts +PasskeysCard +``` + +### `PasskeysController` (type) + +```ts +type PasskeysController = Controller, PasskeysActions>; +``` + +### `PasswordPolicy` (interface) + +```ts +interface PasswordPolicy { + maxLength?: number; + minLength?: number; + requireDigit?: boolean; + requireLowercase?: boolean; + requireSymbol?: boolean; + requireUppercase?: boolean; +} +``` + +### `PasswordRequirement` (interface) + +```ts +interface PasswordRequirement { + label: string; + met: boolean; +} +``` + +### `PasswordStrength` (unknown) + +```ts +PasswordStrength +``` + +### `PhoneForgotPasswordField` (type) + +```ts +type PhoneForgotPasswordField = "phoneNumber"; +``` + +### `PhoneResetPasswordField` (type) + +```ts +type PhoneResetPasswordField = "confirmPassword" | "newPassword" | "otp" | "phoneNumber"; +``` + +### `PhoneSignInCard` (unknown) + +```ts +PhoneSignInCard +``` + +### `PhoneSignInField` (type) + +```ts +type PhoneSignInField = "password" | "phoneNumber"; +``` + +### `PhoneVerifyActions` (interface) + +```ts +interface PhoneVerifyActions { + restart: () => void; + send: (phoneNumber: string) => Promise; + verify: (code: string) => Promise; +} +``` + +### `PhoneVerifyController` (type) + +```ts +type PhoneVerifyController = Controller; +``` + +### `PhoneVerifyOptions` (interface) + +```ts +interface PhoneVerifyOptions { + updatePhoneNumber?: boolean; +} +``` + +### `PhoneVerifyState` (interface) + +```ts +interface PhoneVerifyState { + error?: string; + phoneNumber: string; + status: FlowStatus; + step: "request" | "verify"; + successMessage?: string; +} +``` + +### `PluginFlags` (interface) + +```ts +interface PluginFlags { + admin?: boolean; + anonymous?: boolean; + apiKey?: boolean; + deviceAuthorization?: boolean; + emailOtp?: boolean; + lastLoginMethod?: boolean; + magicLink?: boolean; + multiSession?: boolean; + oauthProvider?: boolean; + oneTap?: boolean; + organization?: boolean; + passkey?: boolean; + phoneNumber?: boolean; + twoFactor?: boolean; + username?: boolean; +} +``` + +### `ProfileCard` (unknown) + +```ts +ProfileCard +``` + +### `ProfileCardProps` (unknown) + +```ts +ProfileCardProps +``` + +### `ProfileField` (type) + +```ts +type ProfileField = "image" | "name"; +``` + +### `ProfileOptions` (interface) + +```ts +interface ProfileOptions { + initialImage?: string; + initialName?: string; +} +``` + +### `ROLE_OPTIONS` (const) + +```ts +const ROLE_OPTIONS: ReadonlyArray = ["member", "admin", "owner"]; +``` + +### `RedirectConfig` (interface) + +```ts +interface RedirectConfig { + afterSignIn?: string; + afterSignOut?: string; + signIn?: string; + twoFactor?: string; +} +``` + +### `RenderCaptchaOptions` (interface) + +```ts +interface RenderCaptchaOptions { + onError?: (error: unknown) => void; + provider: CaptchaProvider; + siteKey: string; +} +``` + +### `ResendVerificationCard` (unknown) + +```ts +ResendVerificationCard +``` + +### `ResendVerificationField` (type) + +```ts +type ResendVerificationField = "email"; +``` + +### `ResetPasswordCard` (unknown) + +```ts +ResetPasswordCard +``` + +### `ResetPasswordCardProps` (unknown) + +```ts +ResetPasswordCardProps +``` + +### `ResetPasswordField` (type) + +```ts +type ResetPasswordField = "confirmPassword" | "password"; +``` + +### `ResetPasswordOptions` (interface) + +```ts +interface ResetPasswordOptions { + token?: string; +} +``` + +### `ResetPasswordOtpCard` (unknown) + +```ts +ResetPasswordOtpCard +``` + +### `ResetPasswordOtpField` (type) + +```ts +type ResetPasswordOtpField = "confirmPassword" | "email" | "otp" | "password"; +``` + +### `ResourceHandle` (interface) + +```ts +interface ResourceHandle> { + destroy: () => void; + getState: () => ResourceState; + mutate: (run: () => Promise) => Promise; + mutateOk: (run: () => Promise) => Promise; + patch: (extra: Partial) => void; + refetch: () => Promise; + subscribe: (onChange: () => void) => () => void; +} +``` + +### `ResourceOptions` (interface) + +```ts +interface ResourceOptions> { + autoLoad?: boolean; + initialExtra?: TExtra; +} +``` + +### `ResourceState` (interface) + +```ts +interface ResourceState> { + busy: boolean; + error?: string; + extra: TExtra; + items: ReadonlyArray; + loading: boolean; + status: FlowStatus; +} +``` + +### `SCOPE_LABELS` (const) + +```ts +const SCOPE_LABELS: Readonly> = { + email: "Your email address", + offline_access: "Access while you're away", + openid: "Your identity", + profile: "Your name and picture", +}; +``` + +### `SessionActions` (interface) + +```ts +interface SessionActions { + refetch: () => Promise; +} +``` + +### `SessionController` (type) + +```ts +type SessionController = Controller; +``` + +### `SessionData` (interface) + +```ts +interface SessionData { + session?: AuthSession; + token?: string; + twoFactorRedirect?: boolean; + user?: AuthUser; +} +``` + +### `SessionState` (interface) + +```ts +interface SessionState { + error?: string; + loading: boolean; + settled: boolean; + status: FlowStatus; + user?: AuthUser; +} +``` + +### `SessionsActions` (interface) + +```ts +interface SessionsActions { + refetch: () => Promise; + revoke: (token: string) => Promise; + revokeOthers: () => Promise; +} +``` + +### `SessionsCard` (unknown) + +```ts +SessionsCard +``` + +### `SessionsController` (type) + +```ts +type SessionsController = Controller, SessionsActions>; +``` + +### `SetUsernameCard` (unknown) + +```ts +SetUsernameCard +``` + +### `SetUsernameField` (type) + +```ts +type SetUsernameField = "username"; +``` + +### `SignInCard` (unknown) + +```ts +SignInCard +``` + +### `SignInCardProps` (unknown) + +```ts +SignInCardProps +``` + +### `SignInField` (type) + +```ts +type SignInField = "email" | "password"; +``` + +### `SignOutButton` (unknown) + +```ts +SignOutButton +``` + +### `SignOutButtonProps` (unknown) + +```ts +SignOutButtonProps +``` + +### `SignUpCard` (unknown) + +```ts +SignUpCard +``` + +### `SignUpCardProps` (unknown) + +```ts +SignUpCardProps +``` + +### `SignUpField` (type) + +```ts +type SignUpField = "email" | "name" | "password"; +``` + +### `Skeleton` (unknown) + +```ts +Skeleton +``` + +### `SocialButtons` (unknown) + +```ts +SocialButtons +``` + +### `Store` (interface) + +```ts +interface Store { + clear: () => void; + get: () => T; + set: (next: T) => void; + subscribe: (onChange: () => void) => () => void; + update: (patch: Partial) => void; +} +``` + +### `SubmitButton` (unknown) + +```ts +SubmitButton +``` + +### `THEME_MODES` (const) + +```ts +const THEME_MODES: ReadonlyArray = ["system", "light", "dark"]; +``` + +### `THEME_STORAGE_KEY` (const) + +```ts +const THEME_STORAGE_KEY = "lunora-theme"; +``` + +### `TOAST_DURATION_MS` (const) + +```ts +const TOAST_DURATION_MS = 6000; +``` + +### `TeamsActions` (interface) + +```ts +interface TeamsActions { + create: (name: string) => Promise; + refetch: () => Promise; + remove: (teamId: string) => Promise; + rename: (teamId: string, name: string) => Promise; +} +``` + +### `TeamsCard` (unknown) + +```ts +TeamsCard +``` + +### `TeamsController` (type) + +```ts +type TeamsController = Controller, TeamsActions>; +``` + +### `TeamsOptions` (interface) + +```ts +interface TeamsOptions { + autoLoad?: boolean; + organizationId?: string; +} +``` + +### `ThemeMode` (type) + +```ts +type ThemeMode = "dark" | "light" | "system"; +``` + +### `ThemeModeActions` (interface) + +```ts +interface ThemeModeActions { + setMode: (mode: ThemeMode) => void; +} +``` + +### `ThemeModeController` (type) + +```ts +type ThemeModeController = Controller; +``` + +### `ThemeModeOptions` (interface) + +```ts +interface ThemeModeOptions { + apply?: (mode: ThemeMode, resolved: "dark" | "light") => void; + persist?: boolean; +} +``` + +### `ThemeModeState` (interface) + +```ts +interface ThemeModeState { + mode: ThemeMode; + resolved: "dark" | "light"; +} +``` + +### `ThemeTokens` (interface) + +```ts +interface ThemeTokens { + background: string; + border: string; + card: string; + cardForeground: string; + destructive: string; + fontMono: string; + fontSans: string; + input: string; + muted: string; + mutedForeground: string; + primary: string; + primaryForeground: string; + radius: string; + ring: string; + secondary: string; + secondaryForeground: string; + success: string; +} +``` + +### `Toast` (interface) + +```ts +interface Toast { + id: number; + message: string; +} +``` + +### `ToastState` (interface) + +```ts +interface ToastState { + toasts: ReadonlyArray; +} +``` + +### `TwoFactorCard` (unknown) + +```ts +TwoFactorCard +``` + +### `TwoFactorCardProps` (unknown) + +```ts +TwoFactorCardProps +``` + +### `TwoFactorField` (type) + +```ts +type TwoFactorField = "code"; +``` + +### `TwoFactorSetupActions` (interface) + +```ts +interface TwoFactorSetupActions { + disable: () => Promise; + enable: () => Promise; + reset: () => void; + setCode: (value: string) => void; + setPassword: (value: string) => void; + verify: () => Promise; +} +``` + +### `TwoFactorSetupCard` (unknown) + +```ts +TwoFactorSetupCard +``` + +### `TwoFactorSetupController` (type) + +```ts +type TwoFactorSetupController = Controller; +``` + +### `TwoFactorSetupState` (interface) + +```ts +interface TwoFactorSetupState { + backupCodes: ReadonlyArray; + code: FieldState; + error?: string; + password: FieldState; + status: FlowStatus; + step: "enabled" | "start" | "verify"; + totpUri?: string; +} +``` + +### `TwoFactorVerifyOptions` (interface) + +```ts +interface TwoFactorVerifyOptions { + method?: "otp" | "totp"; + trustDevice?: boolean; +} +``` + +### `UserAvatar` (unknown) + +```ts +UserAvatar +``` + +### `UserAvatarProps` (unknown) + +```ts +UserAvatarProps +``` + +### `UserButton` (unknown) + +```ts +UserButton +``` + +### `UserButtonProps` (unknown) + +```ts +UserButtonProps +``` + +### `UserInvitationsActions` (interface) + +```ts +interface UserInvitationsActions { + accept: (invitationId: string) => Promise; + refetch: () => Promise; + reject: (invitationId: string) => Promise; +} +``` + +### `UserInvitationsCard` (unknown) + +```ts +UserInvitationsCard +``` + +### `UserInvitationsController` (type) + +```ts +type UserInvitationsController = Controller, UserInvitationsActions>; +``` + +### `UserView` (unknown) + +```ts +UserView +``` + +### `UserViewProps` (unknown) + +```ts +UserViewProps +``` + +### `UsernameAvailability` (unknown) + +```ts +UsernameAvailability +``` + +### `UsernameAvailabilityActions` (interface) + +```ts +interface UsernameAvailabilityActions { + check: (username: string) => void; + reset: () => void; +} +``` + +### `UsernameAvailabilityController` (type) + +```ts +type UsernameAvailabilityController = Controller; +``` + +### `UsernameAvailabilityOptions` (interface) + +```ts +interface UsernameAvailabilityOptions { + debounceMs?: number; + minLength?: number; +} +``` + +### `UsernameAvailabilityState` (interface) + +```ts +interface UsernameAvailabilityState { + status: AvailabilityStatus; + username: string; +} +``` + +### `UsernameSignInCard` (unknown) + +```ts +UsernameSignInCard +``` + +### `UsernameSignInField` (type) + +```ts +type UsernameSignInField = "password" | "username"; +``` + +### `VerifyEmailActions` (interface) + +```ts +interface VerifyEmailActions { + verify: () => Promise; +} +``` + +### `VerifyEmailCard` (unknown) + +```ts +VerifyEmailCard +``` + +### `VerifyEmailCardProps` (unknown) + +```ts +VerifyEmailCardProps +``` + +### `VerifyEmailController` (type) + +```ts +type VerifyEmailController = Controller; +``` + +### `VerifyEmailOptions` (interface) + +```ts +interface VerifyEmailOptions { + autoVerify?: boolean; + token?: string; +} +``` + +### `VerifyEmailState` (interface) + +```ts +interface VerifyEmailState { + error?: string; + status: FlowStatus; +} +``` + +### `ViewPaths` (interface) + +```ts +interface ViewPaths { + acceptInvitation?: string; + deviceAuthorization?: string; + emailOtp?: string; + forgotPassword?: string; + magicLink?: string; + resetPassword?: string; + signIn?: string; + signUp?: string; + twoFactor?: string; + verifyEmail?: string; +} +``` + +### `assertOk` (const) + +```ts +const assertOk = (response: AuthResponse): AuthResponse => { + if (response.error) { + throw new AuthActionError(response.error); + } + return response; +}; +``` + +### `captchaHeaders` (const) + +```ts +const captchaHeaders = (path?: string, options: CaptchaHeaderOptions = {}): Record => { + if (path !== undefined && !isGuarded(path, options.endpoints ?? CAPTCHA_ENDPOINTS, options.basePath ?? "/api/auth")) { + return {}; + } + const { token } = store.get(); + if (token === undefined || token === "") { + return {}; + } + store.set({}); + return { [CAPTCHA_HEADER]: token }; +}; +``` + +### `createAcceptInvitationController` (const) + +```ts +const createAcceptInvitationController = (context: ControllerContext, options: AcceptInvitationOptions = {}): AcceptInvitationController => { + const store = createStore({ loading: true, status: "idle" }); + const load = async (): Promise => { + const id = options.invitationId?.trim(); + if (id === undefined || id === "") { + store.update({ error: context.localization.invitationMissing, loading: false, status: "error" }); + return; + } + store.update({ error: undefined, loading: true }); + try { + const invitation = assertOk(await context.authClient.organization.getInvitation({ query: { id } })).data ?? undefined; + store.update({ invitation, loading: false, status: "idle" }); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.invitationMissing), loading: false, status: "error" }); + } + }; + const decide = async (decision: "accept" | "reject"): Promise => { + const id = options.invitationId?.trim(); + if (id === undefined || id === "" || store.get().status === "submitting") { + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + const session = await context.authClient.getSession(); + if (!session.data?.user) { + const invited = store.get().invitation?.email; + const target = new URLSearchParams({ redirectTo: currentPath() }); + if (invited !== undefined && invited !== "") { + target.set("email", invited); + } + context.nav.replace(`${context.redirects.signIn}?${target.toString()}`); + return; + } + await (decision === "accept" + ? context.authClient.organization.acceptInvitation({ invitationId: id }).then(assertOk) + : context.authClient.organization.rejectInvitation({ invitationId: id }).then(assertOk)); + store.update({ status: "success" }); + context.onSessionChange?.(); + context.nav.replace(context.redirects.afterSignIn); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.genericError), status: "error" }); + } + }; + if (options.autoLoad !== false) { + void load(); + } + return { + actions: { accept: () => decide("accept"), load, reject: () => decide("reject") }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createAccountsController` (const) + +```ts +const createAccountsController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): AccountsController => { + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.listAccounts()).data ?? [] }; + }, options); + return { + actions: { + link: async (provider: string) => { + try { + assertOk(await context.authClient.linkSocial({ callbackURL: context.redirects.afterSignIn, provider })); + } + catch (error) { + notifyError(context, error, context.localization.genericError); + } + }, + refetch: resource.refetch, + unlink: (providerId: string, accountId?: string) => resource.mutate(async () => { + if (resource.getState().items.length <= 1) { + throw new Error(context.localization.accountsLastOne); + } + assertOk(await context.authClient.unlinkAccount(accountId === undefined ? { providerId } : { accountId, providerId })); + }), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createActiveMemberController` (const) + +```ts +const createActiveMemberController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): ActiveMemberController => { + const store = createStore({ loading: true, status: "idle" }); + const refetch = async (): Promise => { + store.update({ error: undefined, loading: true }); + try { + const [session, organization] = await Promise.all([context.authClient.getSession(), context.authClient.organization.getFullOrganization()]); + const userId = session.data?.user?.id; + const role = organization.data?.members?.find((member) => member.userId === userId)?.role; + store.update({ loading: false, role, status: "success" }); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.genericError), loading: false, status: "error" }); + } + }; + if (options.autoLoad !== false) { + void refetch(); + } + return { + actions: { refetch }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createAdminUsersController` (const) + +```ts +const createAdminUsersController = (context: ControllerContext, options: AdminUsersOptions = {}): AdminUsersController => { + const resource = createResourceController(context, async (context_, extra) => { + const search = extra.search.trim(); + const response = assertOk(await context_.authClient.admin.listUsers({ + query: { + limit: options.limit ?? 50, + ...(search === "" ? {} : { searchField: "email", searchOperator: "contains", searchValue: search }), + }, + })); + const { total, users } = readUsers(response.data); + return { extra: { total }, items: users }; + }, { autoLoad: options.autoLoad, initialExtra: { search: "" } }); + const debounceMs = options.debounceMs ?? 300; + let searchTimer: ReturnType | undefined; + const clearSearchTimer = (): void => { + if (searchTimer !== undefined) { + clearTimeout(searchTimer); + searchTimer = undefined; + } + }; + const afterSessionSwap = async (run: () => Promise): Promise => { + if (await run()) { + context.onSessionChange?.(); + context.nav.navigate(context.redirects.afterSignIn); + } + }; + return { + actions: { + ban: (userId: string, reason?: string) => resource.mutate(async () => assertOk(await context.authClient.admin.banUser({ banReason: reason, userId }))), + impersonate: (userId: string) => afterSessionSwap(async () => resource.mutateOk(async () => assertOk(await context.authClient.admin.impersonateUser({ userId })))), + refetch: resource.refetch, + remove: (userId: string) => resource.mutate(async () => assertOk(await context.authClient.admin.removeUser({ userId }))), + setRole: (userId: string, role: string) => resource.mutate(async () => assertOk(await context.authClient.admin.setRole({ role, userId }))), + setSearch: (value: string) => { + resource.patch({ search: value }); + clearSearchTimer(); + if (typeof setTimeout !== "function") { + return resource.refetch(); + } + return new Promise((resolve) => { + searchTimer = setTimeout(() => { + searchTimer = undefined; + resolve(resource.refetch()); + }, debounceMs); + }); + }, + stopImpersonating: () => afterSessionSwap(async () => resource.mutateOk(async () => assertOk(await context.authClient.admin.stopImpersonating()))), + unban: (userId: string) => resource.mutate(async () => assertOk(await context.authClient.admin.unbanUser({ userId }))), + }, + destroy: () => { + clearSearchTimer(); + resource.destroy(); + }, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createAuthorizedAppsController` (const) + +```ts +const createAuthorizedAppsController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): AuthorizedAppsController => { + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.oauth2.getConsents()).data ?? [] }; + }, options); + return { + actions: { + refetch: resource.refetch, + revoke: (consentId: string) => resource.mutate(async () => assertOk(await context.authClient.oauth2.deleteConsent({ id: consentId }))), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createAvatarUploadController` (const) + +```ts +const createAvatarUploadController = (context: ControllerContext, options: { + initialImage?: string; +} = {}): AvatarUploadController => { + const store = createStore({ imageUrl: options.initialImage, status: "idle" }); + const save = async (image: string | undefined, successStatus: FlowStatus): Promise => { + assertOk(await context.authClient.updateUser({ image })); + store.update({ imageUrl: image, status: successStatus }); + context.onSessionChange?.(); + }; + return { + actions: { + remove: async () => { + if (store.get().status === "submitting") { + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + await save(undefined, "success"); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.genericError), status: "error" }); + } + }, + upload: async (file: File) => { + const { upload } = context.avatar; + if (upload === undefined) { + store.update({ error: context.localization.avatarNoUploader, status: "error" }); + return; + } + const maxSize = context.avatar.maxSize ?? Number.POSITIVE_INFINITY; + if (file.size > maxSize) { + store.update({ error: `${context.localization.avatarTooLarge} (${megabytes(maxSize)})`, status: "error" }); + return; + } + if (file.type === "" ? !(await sniffImageType(file)) : !ACCEPTED_TYPES.has(file.type)) { + store.update({ error: context.localization.avatarWrongType, status: "error" }); + return; + } + if (store.get().status === "submitting") { + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + await save(await upload(file), "success"); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.avatarUploadFailed), status: "error" }); + } + }, + }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createBackupCodeSignInController` (const) + +```ts +const createBackupCodeSignInController = (context: ControllerContext, options: { + trustDevice?: boolean; +} = {}): FormController => createFormController(context, { + fallbackError: (localization) => localization.twoFactorFailed, + fields: { code: { validate: (value, _values, localization) => required(value, localization.otpRequired) } }, + sessionChanging: true, + submit: async (values, context_) => { + assertOk(await context_.authClient.twoFactor.verifyBackupCode({ code: values.code.trim(), trustDevice: options.trustDevice })); + return { redirectTo: resolveAfterSignIn(context_.redirects.afterSignIn) }; + }, +}); +``` + +### `createBackupCodesController` (const) + +```ts +const createBackupCodesController = (context: ControllerContext): BackupCodesHandle => { + const codes = createStore<{ + values: ReadonlyArray; + }>({ values: [] }); + const controller = createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { password: { validate: (value, _values, localization) => required(value, localization.passwordRequired) } }, + submit: async (values, context_) => { + const response = assertOk(await context_.authClient.twoFactor.generateBackupCodes({ password: values.password })); + codes.set({ values: response.data?.backupCodes ?? [] }); + return { successMessage: context_.localization.backupCodesRegenerated }; + }, + }); + return { + controller: { + ...controller, + destroy: () => { + controller.destroy(); + codes.clear(); + }, + }, + getCodes: () => codes.get().values, + subscribeCodes: codes.subscribe, + }; +}; +``` + +### `createChangeEmailController` (const) + +```ts +const createChangeEmailController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + newEmail: { validate: (value, _values, localization) => validateEmail(value, localization) }, + }, + submit: async (values, context_) => { + assertOk(await context_.authClient.changeEmail({ + callbackURL: context_.redirects.afterSignIn, + newEmail: values.newEmail.trim(), + })); + return { successMessage: context_.localization.changeEmailSent }; + }, +}); +``` + +### `createChangePasswordController` (const) + +```ts +const createChangePasswordController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + confirmPassword: { + validate: (value, values, localization) => (value === values.newPassword ? undefined : localization.passwordMismatch), + }, + currentPassword: { validate: (value, _values, localization) => required(value, localization.passwordRequired) }, + newPassword: { validate: (value, _values, localization) => validatePassword(value, localization, context.password) }, + }, + submit: async (values, context_) => { + assertOk(await context_.authClient.changePassword({ + currentPassword: values.currentPassword, + newPassword: values.newPassword, + revokeOtherSessions: true, + })); + return { successMessage: context_.localization.changePasswordDone }; + }, +}); +``` + +### `createConsentController` (const) + +```ts +const createConsentController = (context: ControllerContext, options: ConsentOptions = {}): ConsentController => { + const store = createStore({ loading: true, status: "idle" }); + const load = async (): Promise => { + const id = options.consentId?.trim(); + if (id === undefined || id === "") { + store.update({ error: context.localization.consentMissing, loading: false, status: "error" }); + return; + } + store.update({ error: undefined, loading: true }); + try { + const request = assertOk(await context.authClient.oauth2.getConsent({ query: { id } })).data ?? undefined; + store.update({ loading: false, request, status: "idle" }); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.consentMissing), loading: false, status: "error" }); + } + }; + const decide = async (accept: boolean): Promise => { + if (store.get().status === "submitting" || store.get().request === undefined) { + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + const response = assertOk(await context.authClient.oauth2.consent({ accept })); + const redirect = response.data?.redirectURI; + if (redirect === undefined || redirect === "") { + store.update({ error: context.localization.consentExpired, status: "error" }); + return; + } + store.update({ status: "success" }); + context.nav.replace(redirect); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.genericError), status: "error" }); + } + }; + if (options.autoLoad !== false) { + void load(); + } + return { + actions: { accept: () => decide(true), deny: () => decide(false), load }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createDeleteAccountController` (const) + +```ts +const createDeleteAccountController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + password: { validate: (value, _values, localization) => required(value, localization.passwordRequired) }, + }, + sessionChanging: true, + submit: async (values, context_) => { + assertOk(await context_.authClient.deleteUser({ password: values.password })); + return { redirectTo: context_.redirects.afterSignOut }; + }, +}); +``` + +### `createDeviceAuthorizationController` (const) + +```ts +const createDeviceAuthorizationController = (context: ControllerContext, options: DeviceAuthorizationOptions = {}): DeviceAuthorizationController => { + const store = createStore({ code: options.userCode ?? "", status: "idle" }); + const decide = async (decision: "approved" | "denied"): Promise => { + const code = store.get().code.trim(); + if (code === "") { + store.update({ error: context.localization.deviceCodeRequired, status: "error" }); + return; + } + if (store.get().status === "submitting") { + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + await (decision === "approved" + ? context.authClient.device.approve({ userCode: code }).then(assertOk) + : context.authClient.device.deny({ userCode: code }).then(assertOk)); + store.update({ decision, status: "success" }); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.deviceFailed), status: "error" }); + } + }; + return { + actions: { + approve: () => decide("approved"), + deny: () => decide("denied"), + setCode: (value: string) => { + store.update({ code: value, error: undefined, status: "idle" }); + }, + }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createDeviceSessionsController` (const) + +```ts +const createDeviceSessionsController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): DeviceSessionsController => { + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.multiSession.listDeviceSessions()).data ?? [] }; + }, options); + return { + actions: { + refetch: resource.refetch, + revoke: (sessionToken: string) => resource.mutate(async () => { + assertOk(await context.authClient.multiSession.revoke({ sessionToken })); + context.onSessionChange?.(); + }), + setActive: (sessionToken: string) => resource.mutate(async () => { + assertOk(await context.authClient.multiSession.setActive({ sessionToken })); + context.onSessionChange?.(); + }), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createEmailOtpController` (const) + +```ts +const createEmailOtpController = (context: ControllerContext): EmailOtpController => { + const store = createStore({ + code: emptyField(), + email: emptyField(), + status: "idle", + step: "request", + }); + const setEmail = (value: string): void => { + store.update({ email: { ...store.get().email, value }, formError: undefined, status: "idle" }); + }; + const setCode = (value: string): void => { + store.update({ code: { ...store.get().code, value }, formError: undefined, status: "idle" }); + }; + const sendCode = async (): Promise => { + const state = store.get(); + const error = validateEmail(state.email.value, context.localization); + if (error) { + store.update({ email: { ...state.email, error, touched: true }, status: "error" }); + return; + } + store.update({ email: { ...state.email, error: undefined }, formError: undefined, status: "submitting" }); + try { + assertOk(await context.authClient.emailOtp.sendVerificationOtp({ email: state.email.value.trim(), type: "sign-in" })); + store.update({ status: "idle", step: "verify", successMessage: context.localization.emailOtpSent }); + } + catch (error_) { + context.onError?.(error_); + store.update({ formError: mapAuthError(error_, context.localization, context.localization.genericError), status: "error" }); + } + }; + const verify = async (): Promise => { + const state = store.get(); + const error = required(state.code.value, context.localization.otpRequired); + if (error) { + store.update({ code: { ...state.code, error, touched: true }, status: "error" }); + return; + } + store.update({ code: { ...state.code, error: undefined }, formError: undefined, status: "submitting" }); + try { + assertOk(await context.authClient.signIn.emailOtp({ email: state.email.value.trim(), otp: state.code.value.trim() })); + store.update({ status: "success" }); + context.onSessionChange?.(); + context.nav.replace(context.redirects.afterSignIn); + } + catch (error_) { + context.onError?.(error_); + store.update({ formError: mapAuthError(error_, context.localization, context.localization.twoFactorFailed), status: "error" }); + } + }; + const actions: EmailOtpActions = { + back: () => { + store.update({ code: emptyField(), formError: undefined, status: "idle", step: "request", successMessage: undefined }); + }, + reset: () => { + store.set({ code: emptyField(), email: emptyField(), status: "idle", step: "request" }); + }, + sendCode, + setCode, + setEmail, + verify, + }; + return { + actions, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createForgotPasswordController` (const) + +```ts +const createForgotPasswordController = (context: ControllerContext, options: ForgotPasswordOptions = {}): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + email: { validate: (value, _values, localization) => validateEmail(value, localization) }, + }, + submit: async (values, context_) => { + const email = values.email.trim(); + if (context_.forgotPasswordMethod === "otp") { + assertOk(await context_.authClient.emailOtp.sendVerificationOtp({ email, type: "forget-password" })); + return { successMessage: context_.localization.emailOtpSent }; + } + assertOk(await context_.authClient.forgetPassword({ + email, + redirectTo: options.resetPath ?? "/reset-password", + })); + return { successMessage: context_.localization.forgotPasswordSent }; + }, +}); +``` + +### `createFormController` (const) + +```ts +const createFormController = (context: ControllerContext, options: FormControllerOptions): FormController => { + const fieldNames = Object.keys(options.fields) as TField[]; + const buildInitialFields = (): Record => { + const fields = {} as Record; + for (const name of fieldNames) { + fields[name] = { touched: false, value: options.fields[name].initial ?? "" }; + } + return fields; + }; + const initialState = (): FormState => { + return { fields: buildInitialFields(), loading: options.prefill !== undefined, status: "idle" }; + }; + const store = createStore>(initialState()); + let generation = 0; + const edited = new Set(); + const state = (): FormState => store.get(); + const values = (): Record => { + const out = {} as Record; + for (const name of fieldNames) { + out[name] = state().fields[name].value; + } + return out; + }; + const validateField = (name: TField): string | undefined => options.fields[name].validate?.(state().fields[name].value, values(), context.localization); + const setField = (name: TField, value: string): void => { + edited.add(name); + const current = state(); + store.set({ + ...current, + fields: { ...current.fields, [name]: { ...current.fields[name], error: undefined, value } }, + formError: undefined, + status: current.status === "submitting" ? "submitting" : "idle", + successMessage: undefined, + }); + }; + const blur = (name: TField): void => { + const error = validateField(name); + const current = state(); + store.set({ + ...current, + fields: { ...current.fields, [name]: { ...current.fields[name], error, touched: true } }, + }); + }; + const submit = async (): Promise => { + if (state().status === "submitting") { + return; + } + const nextFields = { ...state().fields }; + let hasError = false; + for (const name of fieldNames) { + const error = validateField(name); + nextFields[name] = { ...nextFields[name], error, touched: true }; + if (error) { + hasError = true; + } + } + if (hasError) { + store.set({ ...state(), fields: nextFields, formError: undefined, status: "error" }); + return; + } + store.set({ ...state(), fields: nextFields, formError: undefined, status: "submitting" }); + try { + const result = (await options.submit(values(), context)) ?? {}; + store.set({ + ...state(), + fields: { ...state().fields }, + status: "success", + successMessage: result.successMessage, + }); + if (options.sessionChanging) { + context.onSessionChange?.(); + } + if (result.redirectTo !== undefined) { + context.nav.replace(result.redirectTo); + } + } + catch (error) { + context.onError?.(error); + store.set({ + ...state(), + formError: mapAuthError(error, context.localization, options.fallbackError(context.localization)), + status: "error", + }); + } + }; + const load = async (): Promise => { + if (!options.prefill) { + return; + } + generation += 1; + const ticket = generation; + store.set({ ...state(), loading: true }); + try { + const seeded = await options.prefill(context); + if (ticket !== generation) { + return; + } + const current = state(); + if (current.status === "submitting" || current.status === "success") { + store.set({ ...current, loading: false }); + return; + } + const fields = { ...current.fields }; + for (const name of fieldNames) { + const value = seeded[name]; + if (value !== undefined && !edited.has(name)) { + fields[name] = { ...fields[name], error: undefined, touched: false, value }; + } + } + store.set({ ...current, fields, loading: false }); + } + catch (error) { + context.onError?.(error); + if (ticket === generation) { + store.set({ ...state(), loading: false }); + } + } + }; + const reset = (): void => { + edited.clear(); + store.set(initialState()); + if (options.prefill) { + void load(); + } + }; + if (options.prefill) { + void load(); + } + const actions: FormActions = { blur, load, reset, setField, submit }; + return { + actions, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createMagicLinkController` (const) + +```ts +const createMagicLinkController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + email: { validate: (value, _values, localization) => validateEmail(value, localization) }, + }, + submit: async (values, context_) => { + assertOk(await context_.authClient.signIn.magicLink({ + callbackURL: resolveAfterSignIn(context_.redirects.afterSignIn), + email: values.email.trim(), + })); + return { successMessage: context_.localization.magicLinkSent }; + }, +}); +``` + +### `createMembersController` (const) + +```ts +const createMembersController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): MembersController => { + const store = createStore({ busy: false, invitations: [], loading: true, members: [] }); + const refetch = async (): Promise => { + store.update({ error: undefined, loading: true }); + try { + const organization = assertOk(await context.authClient.organization.getFullOrganization()).data; + store.update({ invitations: organization?.invitations ?? [], loading: false, members: organization?.members ?? [] }); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.genericError), loading: false }); + } + }; + const mutate = async (run: () => Promise): Promise => { + if (store.get().busy) { + return; + } + store.update({ busy: true, error: undefined }); + try { + await run(); + store.update({ busy: false }); + await refetch(); + } + catch (error) { + context.onError?.(error); + store.update({ busy: false, error: mapAuthError(error, context.localization, context.localization.genericError) }); + } + }; + if (options.autoLoad !== false) { + void refetch(); + } + return { + actions: { + cancelInvitation: (invitationId: string) => mutate(async () => assertOk(await context.authClient.organization.cancelInvitation({ invitationId }))), + invite: (email: string, role: string) => mutate(async () => assertOk(await context.authClient.organization.inviteMember({ email, role }))), + refetch, + removeMember: (memberIdOrEmail: string) => mutate(async () => assertOk(await context.authClient.organization.removeMember({ memberIdOrEmail }))), + updateRole: (memberId: string, role: string) => mutate(async () => assertOk(await context.authClient.organization.updateMemberRole({ memberId, role }))), + }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createOrganizationLogoController` (const) + +```ts +const createOrganizationLogoController = (context: ControllerContext, options: LogoUploadOptions = {}): LogoUploadController => { + const store = createStore({ logoUrl: options.initialLogo, status: "idle" }); + const save = async (logo: string | undefined): Promise => { + assertOk(await context.authClient.organization.update({ data: { logo }, organizationId: options.organizationId })); + store.update({ logoUrl: logo, status: "success" }); + }; + const guard = async (run: () => Promise, fallback: string): Promise => { + if (store.get().status === "submitting") { + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + await run(); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, fallback), status: "error" }); + } + }; + return { + actions: { + remove: () => guard(async () => save(undefined), context.localization.genericError), + upload: async (file: File) => { + const { upload } = context.avatar; + if (upload === undefined) { + store.update({ error: context.localization.avatarNoUploader, status: "error" }); + return; + } + const maxSize = context.avatar.maxSize ?? Number.POSITIVE_INFINITY; + if (file.size > maxSize) { + store.update({ error: `${context.localization.avatarTooLarge} (${megabytes(maxSize)})`, status: "error" }); + return; + } + if (file.type !== "" && !ACCEPTED_TYPES.has(file.type)) { + store.update({ error: context.localization.avatarWrongType, status: "error" }); + return; + } + await guard(async () => save(await upload(file)), context.localization.avatarUploadFailed); + }, + }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createOrganizationSettingsController` (const) + +```ts +const createOrganizationSettingsController = (context: ControllerContext, options: OrganizationSettingsOptions = {}): FormController => { + const { organizationId } = options; + return createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + logo: {}, + name: { validate: (value, _values, localization) => required(value, localization.organizationNameRequired) }, + slug: { validate: (value, _values, localization) => required(value, localization.organizationSlugRequired) }, + }, + prefill: options.autoLoad === false + ? undefined + : async (context_) => { + const organization = assertOk(await context_.authClient.organization.getFullOrganization(organizationId === undefined ? undefined : { organizationId })).data; + return { logo: organization?.logo ?? "", name: organization?.name ?? "", slug: organization?.slug ?? "" }; + }, + submit: async (values, context_) => { + const logo = values.logo.trim(); + assertOk(await context_.authClient.organization.update({ + data: { logo: logo === "" ? undefined : logo, name: values.name.trim(), slug: values.slug.trim() }, + organizationId, + })); + return { successMessage: context_.localization.organizationSaved }; + }, + }); +}; +``` + +### `createOrganizationsController` (const) + +```ts +const createOrganizationsController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): OrganizationsController => { + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.organization.list()).data ?? [] }; + }, options); + return { + actions: { + create: (name: string, slug: string) => resource.mutate(async () => assertOk(await context.authClient.organization.create({ name, slug }))), + leave: (organizationId: string) => resource.mutate(async () => { + assertOk(await context.authClient.organization.leave({ organizationId })); + context.onSessionChange?.(); + }), + refetch: resource.refetch, + remove: (organizationId: string) => resource.mutate(async () => assertOk(await context.authClient.organization.delete({ organizationId }))), + setActive: (organizationId: string) => resource.mutate(async () => assertOk(await context.authClient.organization.setActive({ organizationId }))), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createPasskeysController` (const) + +```ts +const createPasskeysController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): PasskeysController => { + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.passkey.listUserPasskeys()).data ?? [] }; + }, options); + return { + actions: { + add: (name?: string) => resource.mutate(async () => { + const trimmed = name?.trim(); + const response = await context.authClient.passkey.addPasskey(trimmed === undefined || trimmed === "" ? undefined : { name: trimmed }); + if (!response || (response.error && CANCELLED_CODES.has(response.error.code ?? ""))) { + return; + } + assertOk(response); + }), + refetch: resource.refetch, + remove: (id: string) => resource.mutate(async () => assertOk(await context.authClient.passkey.deletePasskey({ id }))), + rename: (id: string, name: string) => resource.mutate(async () => assertOk(await context.authClient.passkey.updatePasskey({ id, name: name.trim() }))), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createPhoneForgotPasswordController` (const) + +```ts +const createPhoneForgotPasswordController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { phoneNumber: { validate: (value, _values, localization) => required(value, localization.phoneRequired) } }, + submit: async (values, context_) => { + assertOk(await context_.authClient.phoneNumber.requestPasswordReset({ phoneNumber: values.phoneNumber.trim() })); + return { successMessage: context_.localization.phoneOtpSent }; + }, +}); +``` + +### `createPhoneResetPasswordController` (const) + +```ts +const createPhoneResetPasswordController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + confirmPassword: { + validate: (value, values, localization) => (value === values.newPassword ? undefined : localization.passwordMismatch), + }, + newPassword: { validate: (value, _values, localization) => passwordValidator(value, localization, context.password) }, + otp: { validate: (value, _values, localization) => required(value, localization.otpRequired) }, + phoneNumber: { validate: (value, _values, localization) => required(value, localization.phoneRequired) }, + }, + submit: async (values, context_) => { + assertOk(await context_.authClient.phoneNumber.resetPassword({ + newPassword: values.newPassword, + otp: values.otp.trim(), + phoneNumber: values.phoneNumber.trim(), + })); + return { redirectTo: context_.redirects.signIn, successMessage: context_.localization.resetPasswordDone }; + }, +}); +``` + +### `createPhoneSignInController` (const) + +```ts +const createPhoneSignInController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.signInFailed, + fields: { + password: { validate: (value, _values, localization) => required(value, localization.passwordRequired) }, + phoneNumber: { validate: (value, _values, localization) => required(value, localization.phoneRequired) }, + }, + sessionChanging: true, + submit: async (values, context_) => { + const response = assertOk(await context_.authClient.signIn.phoneNumber({ password: values.password, phoneNumber: values.phoneNumber.trim() })); + if (response.data?.twoFactorRedirect) { + return { redirectTo: withRedirectTo(context_.redirects.twoFactor) }; + } + return { redirectTo: resolveAfterSignIn(context_.redirects.afterSignIn) }; + }, +}); +``` + +### `createPhoneVerifyController` (const) + +```ts +const createPhoneVerifyController = (context: ControllerContext, options: PhoneVerifyOptions = {}): PhoneVerifyController => { + const store = createStore({ phoneNumber: "", status: "idle", step: "request" }); + const run = async (work: () => Promise>, fallback: string): Promise => { + if (store.get().status === "submitting") { + return; + } + store.update({ error: undefined, status: "submitting", successMessage: undefined }); + try { + store.update({ status: "idle", ...(await work()) }); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, fallback), status: "error" }); + } + }; + return { + actions: { + restart: () => { + store.set({ phoneNumber: "", status: "idle", step: "request" }); + }, + send: async (phoneNumber: string) => { + const trimmed = phoneNumber.trim(); + if (trimmed === "") { + store.update({ error: context.localization.phoneRequired, status: "error" }); + return; + } + await run(async () => { + assertOk(await context.authClient.phoneNumber.sendOtp({ phoneNumber: trimmed })); + return { phoneNumber: trimmed, step: "verify", successMessage: context.localization.phoneOtpSent }; + }, context.localization.genericError); + }, + verify: async (code: string) => { + const trimmed = code.trim(); + if (trimmed === "") { + store.update({ error: context.localization.otpRequired, status: "error" }); + return; + } + await run(async () => { + assertOk(await context.authClient.phoneNumber.verify({ + code: trimmed, + phoneNumber: store.get().phoneNumber, + updatePhoneNumber: options.updatePhoneNumber, + })); + context.onSessionChange?.(); + if (options.updatePhoneNumber !== true) { + context.nav.replace(context.redirects.afterSignIn); + } + return { status: "success", successMessage: context.localization.phoneVerified }; + }, context.localization.twoFactorFailed); + }, + }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createProfileController` (const) + +```ts +const createProfileController = (context: ControllerContext, options: ProfileOptions = {}): FormController => { + const seeded = options.initialImage !== undefined || options.initialName !== undefined; + return createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + image: { initial: options.initialImage ?? "" }, + name: { initial: options.initialName ?? "", validate: (value, _values, localization) => required(value, localization.nameRequired) }, + }, + prefill: seeded + ? undefined + : async (context_) => { + const session = await context_.authClient.getSession(); + const user = session.data?.user; + return { image: user?.image ?? "", name: user?.name ?? "" }; + }, + submit: async (values, context_) => { + const image = values.image.trim(); + assertOk(await context_.authClient.updateUser({ image: image === "" ? undefined : image, name: values.name.trim() })); + return { successMessage: context_.localization.profileSaved }; + }, + }); +}; +``` + +### `createResendVerificationController` (const) + +```ts +const createResendVerificationController = (context: ControllerContext, options: { + initialEmail?: string; +} = {}): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { email: { initial: options.initialEmail ?? "", validate: (value, _values, localization) => emailValidator(value, localization) } }, + prefill: options.initialEmail === undefined + ? async (context_) => { + const session = await context_.authClient.getSession(); + return { email: session.data?.user?.email ?? "" }; + } + : undefined, + submit: async (values, context_) => { + assertOk(await context_.authClient.sendVerificationEmail({ callbackURL: context_.redirects.afterSignIn, email: values.email.trim() })); + return { successMessage: context_.localization.verifyEmailSent }; + }, +}); +``` + +### `createResetPasswordController` (const) + +```ts +const createResetPasswordController = (context: ControllerContext, options: ResetPasswordOptions = {}): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + confirmPassword: { + validate: (value, values, localization) => (value === values.password ? undefined : localization.passwordMismatch), + }, + password: { validate: (value, _values, localization) => validatePassword(value, localization, context.password) }, + }, + submit: async (values, context_) => { + assertOk(await context_.authClient.resetPassword({ + newPassword: values.password, + token: options.token, + })); + return { redirectTo: context_.redirects.signIn, successMessage: context_.localization.resetPasswordDone }; + }, +}); +``` + +### `createResetPasswordOtpController` (const) + +```ts +const createResetPasswordOtpController = (context: ControllerContext, options: { + initialEmail?: string; +} = {}): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + confirmPassword: { + validate: (value, values, localization) => (value === values.password ? undefined : localization.passwordMismatch), + }, + email: { initial: options.initialEmail ?? "", validate: (value, _values, localization) => validateEmail(value, localization) }, + otp: { validate: (value, _values, localization) => required(value, localization.otpRequired) }, + password: { validate: (value, _values, localization) => validatePassword(value, localization, context.password) }, + }, + submit: async (values, context_) => { + assertOk(await context_.authClient.emailOtp.resetPassword({ + email: values.email.trim(), + otp: values.otp.trim(), + password: values.password, + })); + return { redirectTo: context_.redirects.signIn, successMessage: context_.localization.resetPasswordDone }; + }, +}); +``` + +### `createResourceController` (const) + +```ts +const createResourceController = >(context: ControllerContext, load: (context: ControllerContext, extra: TExtra) => Promise<{ + extra?: Partial; + items: ReadonlyArray; +}>, options: ResourceOptions = {}): ResourceHandle => { + const store = createStore>({ + busy: false, + extra: options.initialExtra ?? ({} as TExtra), + items: [], + loading: true, + status: "idle", + }); + let generation = 0; + const refetch = async (): Promise => { + generation += 1; + const ticket = generation; + store.update({ error: undefined, loading: true, status: "submitting" }); + try { + const result = await load(context, store.get().extra); + if (ticket !== generation) { + return; + } + const { extra: patched, items } = result; + store.update({ items, loading: false, status: "success" }); + if (patched !== undefined) { + store.update({ extra: { ...store.get().extra, ...patched } }); + } + } + catch (error) { + if (ticket !== generation) { + return; + } + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.genericError), loading: false, status: "error" }); + } + }; + const mutateOk = async (run: () => Promise): Promise => { + if (store.get().busy) { + return false; + } + store.update({ busy: true, error: undefined }); + try { + await run(); + store.update({ busy: false }); + await refetch(); + return true; + } + catch (error) { + context.onError?.(error); + store.update({ busy: false, error: mapAuthError(error, context.localization, context.localization.genericError), status: "error" }); + return false; + } + }; + if (options.autoLoad !== false) { + void refetch(); + } + return { + destroy: store.clear, + getState: store.get, + mutate: async (run: () => Promise) => { + await mutateOk(run); + }, + mutateOk, + patch: (next: Partial) => { + store.update({ extra: { ...store.get().extra, ...next } }); + }, + refetch, + subscribe: store.subscribe, + }; +}; +``` + +### `createSessionController` (const) + +```ts +const createSessionController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): SessionController => { + const store = createStore({ loading: true, settled: false, status: "idle" }); + const refetch = async (): Promise => { + store.update({ error: undefined, loading: true }); + try { + const response = await context.authClient.getSession(); + store.update({ loading: false, settled: true, status: "success", user: response.data?.user }); + } + catch (error) { + context.onError?.(error); + store.update({ + error: mapAuthError(error, context.localization, context.localization.genericError), + loading: false, + settled: true, + status: "error", + user: undefined, + }); + } + }; + if (options.autoLoad !== false) { + void refetch(); + } + return { + actions: { refetch }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createSessionsController` (const) + +```ts +const createSessionsController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): SessionsController => { + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.listSessions()).data ?? [] }; + }, options); + return { + actions: { + refetch: resource.refetch, + revoke: (token: string) => resource.mutate(async () => assertOk(await context.authClient.revokeSession({ token }))), + revokeOthers: () => resource.mutate(async () => assertOk(await context.authClient.revokeOtherSessions())), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createSetUsernameController` (const) + +```ts +const createSetUsernameController = (context: ControllerContext, options: { + initialUsername?: string; +} = {}): FormController => createFormController(context, { + fallbackError: (localization) => localization.genericError, + fields: { + username: { initial: options.initialUsername ?? "", validate: (value, _values, localization) => required(value, localization.usernameRequired) }, + }, + submit: async (values, context_) => { + assertOk(await context_.authClient.updateUser({ username: values.username.trim() })); + return { successMessage: context_.localization.usernameSaved }; + }, +}); +``` + +### `createSignInController` (const) + +```ts +const createSignInController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.signInFailed, + fields: { + email: { validate: (value, _values, localization) => validateEmail(value, localization) }, + password: { validate: (value, _values, localization) => required(value, localization.passwordRequired) }, + }, + sessionChanging: true, + submit: async (values, context_) => { + const response = assertOk(await context_.authClient.signIn.email({ + callbackURL: context_.redirects.afterSignIn, + email: values.email.trim(), + password: values.password, + })); + if (response.data?.twoFactorRedirect === true) { + return { redirectTo: withRedirectTo(context_.redirects.twoFactor) }; + } + return { redirectTo: resolveAfterSignIn(context_.redirects.afterSignIn) }; + }, +}); +``` + +### `createSignUpController` (const) + +```ts +const createSignUpController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.signUpFailed, + fields: { + email: { validate: (value, _values, localization) => validateEmail(value, localization) }, + name: { validate: (value, _values, localization) => required(value, localization.nameRequired) }, + password: { validate: (value, _values, localization) => validatePassword(value, localization, context.password) }, + }, + prefill: () => { + const seeded: Partial> = {}; + const email = readFieldPrefill("email"); + const name = readFieldPrefill("name"); + if (email !== undefined) { + seeded.email = email; + } + if (name !== undefined) { + seeded.name = name; + } + return Promise.resolve(seeded); + }, + sessionChanging: true, + submit: async (values, context_) => { + assertOk(await context_.authClient.signUp.email({ + callbackURL: context_.redirects.afterSignIn, + email: values.email.trim(), + name: values.name.trim(), + password: values.password, + })); + return { redirectTo: resolveAfterSignIn(context_.redirects.afterSignIn) }; + }, +}); +``` + +### `createStore` (const) + +```ts +const createStore = (initial: T): Store => { + let state = initial; + const listeners = new Set<() => void>(); + const notify = (): void => { + for (const listener of listeners) { + listener(); + } + }; + return { + clear: () => { + listeners.clear(); + }, + get: () => state, + set: (next: T) => { + state = next; + notify(); + }, + subscribe: (onChange: () => void) => { + listeners.add(onChange); + return () => { + listeners.delete(onChange); + }; + }, + update: (patch: Partial) => { + state = { ...state, ...patch }; + notify(); + }, + }; +}; +``` + +### `createTeamsController` (const) + +```ts +const createTeamsController = (context: ControllerContext, options: TeamsOptions = {}): TeamsController => { + const query = options.organizationId === undefined ? undefined : { organizationId: options.organizationId }; + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.organization.listTeams(query === undefined ? undefined : { query })).data ?? [] }; + }, { autoLoad: options.autoLoad }); + return { + actions: { + create: (name: string) => resource.mutate(async () => assertOk(await context.authClient.organization.createTeam({ name: name.trim(), organizationId: options.organizationId }))), + refetch: resource.refetch, + remove: (teamId: string) => resource.mutate(async () => assertOk(await context.authClient.organization.removeTeam({ organizationId: options.organizationId, teamId }))), + rename: (teamId: string, name: string) => resource.mutate(async () => assertOk(await context.authClient.organization.updateTeam({ data: { name: name.trim() }, teamId }))), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createThemeModeController` (const) + +```ts +const createThemeModeController = (options: ThemeModeOptions = {}): ThemeModeController => { + const stored = options.persist === false ? undefined : readStored(); + const initial = stored ?? "system"; + const store = createStore({ mode: initial, resolved: initial === "system" ? systemPrefers() : initial }); + const apply = (mode: ThemeMode): void => { + const resolved = mode === "system" ? systemPrefers() : mode; + if (options.apply) { + options.apply(mode, resolved); + } + else { + const dataset = (globalThis as { + document?: { + documentElement?: { + dataset?: Record; + }; + }; + }).document?.documentElement?.dataset; + if (dataset) { + dataset["theme"] = resolved; + } + } + store.update({ mode, resolved }); + }; + if (stored !== undefined) { + apply(stored); + } + return { + actions: { + setMode: (mode: ThemeMode) => { + if (options.persist !== false) { + try { + storage()?.setItem(THEME_STORAGE_KEY, mode); + } + catch { + } + } + apply(mode); + }, + }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createTwoFactorSetupController` (const) + +```ts +const createTwoFactorSetupController = (context: ControllerContext): TwoFactorSetupController => { + const store = createStore(initialState()); + const fail = (error: unknown, fallback: string): void => { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, fallback), status: "error" }); + }; + const enable = async (): Promise => { + const state = store.get(); + const error = required(state.password.value, context.localization.passwordRequired); + if (error) { + store.update({ password: { ...state.password, error, touched: true }, status: "error" }); + return; + } + store.update({ error: undefined, password: { ...state.password, error: undefined }, status: "submitting" }); + try { + const { data } = assertOk(await context.authClient.twoFactor.enable({ password: state.password.value })); + store.update({ backupCodes: data?.backupCodes ?? [], status: "idle", step: "verify", totpUri: data?.totpURI }); + } + catch (error_) { + fail(error_, context.localization.genericError); + } + }; + const verify = async (): Promise => { + const state = store.get(); + const error = required(state.code.value, context.localization.otpRequired); + if (error) { + store.update({ code: { ...state.code, error, touched: true }, status: "error" }); + return; + } + store.update({ code: { ...state.code, error: undefined }, error: undefined, status: "submitting" }); + try { + assertOk(await context.authClient.twoFactor.verifyTotp({ code: state.code.value.trim() })); + store.update({ status: "success", step: "enabled" }); + } + catch (error_) { + fail(error_, context.localization.twoFactorFailed); + } + }; + const disable = async (): Promise => { + const state = store.get(); + const error = required(state.password.value, context.localization.passwordRequired); + if (error) { + store.update({ password: { ...state.password, error, touched: true }, status: "error" }); + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + assertOk(await context.authClient.twoFactor.disable({ password: state.password.value })); + store.set(initialState()); + } + catch (error_) { + fail(error_, context.localization.genericError); + } + }; + return { + actions: { + disable, + enable, + reset: () => { + store.set(initialState()); + }, + setCode: (value: string) => { + store.update({ code: { ...store.get().code, value }, error: undefined, status: "idle" }); + }, + setPassword: (value: string) => { + store.update({ error: undefined, password: { ...store.get().password, value }, status: "idle" }); + }, + verify, + }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createTwoFactorVerifyController` (const) + +```ts +const createTwoFactorVerifyController = (context: ControllerContext, options: TwoFactorVerifyOptions = {}): FormController => createFormController(context, { + fallbackError: (localization) => localization.twoFactorFailed, + fields: { + code: { validate: (value, _values, localization) => required(value, localization.otpRequired) }, + }, + sessionChanging: true, + submit: async (values, context_) => { + const input = { code: values.code.trim(), trustDevice: options.trustDevice }; + assertOk(options.method === "otp" ? await context_.authClient.twoFactor.verifyOtp(input) : await context_.authClient.twoFactor.verifyTotp(input)); + return { redirectTo: resolveAfterSignIn(context_.redirects.afterSignIn) }; + }, +}); +``` + +### `createUserInvitationsController` (const) + +```ts +const createUserInvitationsController = (context: ControllerContext, options: { + autoLoad?: boolean; +} = {}): UserInvitationsController => { + const resource = createResourceController(context, async (context_) => { + return { items: assertOk(await context_.authClient.organization.listUserInvitations()).data ?? [] }; + }, options); + return { + actions: { + accept: (invitationId: string) => resource.mutate(async () => { + assertOk(await context.authClient.organization.acceptInvitation({ invitationId })); + context.onSessionChange?.(); + }), + refetch: resource.refetch, + reject: (invitationId: string) => resource.mutate(async () => assertOk(await context.authClient.organization.rejectInvitation({ invitationId }))), + }, + destroy: resource.destroy, + getState: resource.getState, + subscribe: resource.subscribe, + }; +}; +``` + +### `createUsernameAvailabilityController` (const) + +```ts +const createUsernameAvailabilityController = (context: ControllerContext, options: UsernameAvailabilityOptions = {}): UsernameAvailabilityController => { + const store = createStore({ status: "idle", username: "" }); + const debounceMs = options.debounceMs ?? 400; + const minLength = options.minLength ?? 3; + let timer: ReturnType | undefined; + let inFlight = ""; + const clearTimer = (): void => { + if (timer !== undefined) { + clearTimeout(timer); + timer = undefined; + } + }; + const ask = async (username: string): Promise => { + inFlight = username; + store.set({ status: "checking", username }); + try { + const response = await context.authClient.isUsernameAvailable({ username }); + if (inFlight !== username) { + return; + } + if (response.error) { + store.set({ status: "unknown", username }); + return; + } + store.set({ status: response.data?.available === false ? "taken" : "available", username }); + } + catch (error) { + context.onError?.(error); + if (inFlight === username) { + store.set({ status: "unknown", username }); + } + } + }; + return { + actions: { + check: (username: string) => { + const trimmed = username.trim(); + clearTimer(); + if (trimmed.length < minLength) { + inFlight = ""; + store.set({ status: "idle", username: trimmed }); + return; + } + if (typeof setTimeout !== "function") { + void ask(trimmed); + return; + } + timer = setTimeout(() => { + void ask(trimmed); + }, debounceMs); + }, + reset: () => { + clearTimer(); + inFlight = ""; + store.set({ status: "idle", username: "" }); + }, + }, + destroy: () => { + clearTimer(); + store.clear(); + }, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `createUsernameSignInController` (const) + +```ts +const createUsernameSignInController = (context: ControllerContext): FormController => createFormController(context, { + fallbackError: (localization) => localization.signInFailed, + fields: { + password: { validate: (value, _values, localization) => required(value, localization.passwordRequired) }, + username: { validate: (value, _values, localization) => required(value, localization.usernameRequired) }, + }, + sessionChanging: true, + submit: async (values, context_) => { + const response = assertOk(await context_.authClient.signIn.username({ password: values.password, username: values.username.trim() })); + if (response.data?.twoFactorRedirect) { + return { redirectTo: withRedirectTo(context_.redirects.twoFactor) }; + } + return { redirectTo: resolveAfterSignIn(context_.redirects.afterSignIn) }; + }, +}); +``` + +### `createVerifyEmailController` (const) + +```ts +const createVerifyEmailController = (context: ControllerContext, options: VerifyEmailOptions = {}): VerifyEmailController => { + const store = createStore({ status: "idle" }); + const verify = async (): Promise => { + const token = options.token?.trim(); + if (token === undefined || token === "") { + store.update({ error: context.localization.verifyEmailNoToken, status: "error" }); + return; + } + if (store.get().status === "submitting") { + return; + } + store.update({ error: undefined, status: "submitting" }); + try { + const response = await context.authClient.verifyEmail({ query: { token } }); + if (response.error && !ALREADY_VERIFIED_CODES.has(response.error.code ?? "")) { + assertOk(response); + } + store.update({ status: "success" }); + context.onSessionChange?.(); + context.nav.replace(context.redirects.afterSignIn); + } + catch (error) { + context.onError?.(error); + store.update({ error: mapAuthError(error, context.localization, context.localization.verifyEmailFailed), status: "error" }); + } + }; + if (options.autoVerify !== false) { + void verify(); + } + return { + actions: { verify }, + destroy: store.clear, + getState: store.get, + subscribe: store.subscribe, + }; +}; +``` + +### `defaultNav` (const) + +```ts +const defaultNav: NavAdapter = { + navigate: (to: string): void => { + globalThis.location.assign(to); + }, + replace: (to: string): void => { + globalThis.location.replace(to); + }, +}; +``` + +### `derivePluginFlags` (const) + +```ts +const derivePluginFlags = (authClient: unknown): Required => { + if (authClient === null || (typeof authClient !== "object" && typeof authClient !== "function")) { + return withEveryFlow(true); + } + return registry.get(authClient) ?? withEveryFlow(true); +}; +``` + +### `discoverAuthConfig` (const) + +```ts +const discoverAuthConfig = (basePath: string): DiscoveryHandle => { + const url = `${basePath.endsWith("/") ? basePath.slice(0, -1) : basePath}/ui-config`; + const existing = handles.get(url); + if (existing) { + return existing; + } + const store = createStore({ status: "loading" }); + const handle: DiscoveryHandle = { getState: store.get, subscribe: store.subscribe }; + handles.set(url, handle); + const fetcher = (globalThis as { + fetch?: typeof fetch; + }).fetch; + if (typeof fetcher !== "function") { + handles.delete(url); + store.update({ status: "unavailable" }); + return handle; + } + const origin = (globalThis as { + location?: { + origin?: string; + }; + }).location?.origin; + const hasOrigin = origin !== undefined && origin !== ""; + let requestUrl: string | undefined = url; + if (url.startsWith("/")) { + requestUrl = hasOrigin ? `${origin}${url}` : undefined; + } + if (requestUrl === undefined) { + handles.delete(url); + store.update({ status: "unavailable" }); + return handle; + } + const unavailable = (): void => { + handles.delete(url); + store.update({ status: "unavailable" }); + }; + void (async () => { + try { + const response = await fetcher(requestUrl, { credentials: "include", headers: { accept: "application/json" } }); + if (!response.ok) { + unavailable(); + return; + } + const body: unknown = await response.json(); + if (isConfig(body)) { + store.update({ config: normalize(body), status: "ready" }); + return; + } + unavailable(); + } + catch { + unavailable(); + } + })(); + return handle; +}; +``` + +### `dismissToast` (const) + +```ts +const dismissToast = (id: number): void => { + const timer = timers.get(id); + if (timer !== undefined) { + clearTimeout(timer); + timers.delete(id); + } + store.update({ toasts: store.get().toasts.filter((toast) => toast.id !== id) }); +}; +``` + +### `email` (const) + +```ts +const email = (value: string, localization: Localization): string | undefined => { + const missing = required(value, localization.emailRequired); + if (missing) { + return missing; + } + return EMAIL_RE.test(value.trim()) ? undefined : localization.emailInvalid; +}; +``` + +### `getToasts` (const) + +```ts +const getToasts = (): ReadonlyArray => store.get().toasts; +``` + +### `isFlowEnabled` (const) + +```ts +const isFlowEnabled = (context: { + plugins: Required; +}, flow: FlowName, component: string): boolean => { + if (context.plugins[flow]) { + return true; + } + if (!warned.has(component)) { + warned.add(component); + console.warn(`[lunora-auth-ui] <${component}> did not render: the "${flow}" flow is off. Turn it on in lunora/auth-ui/client.ts, or pass plugins={{ ${flow}: true }} to .`); + } + return false; +}; +``` + +### `isSafeRedirect` (const) + +```ts +const isSafeRedirect = (target: string): boolean => { + const trimmed = target.trim(); + if (trimmed === "" || !trimmed.startsWith("/")) { + return false; + } + if (trimmed.startsWith("//") || trimmed.startsWith("/\\")) { + return false; + } + return !CONTROL_CHARACTERS.test(trimmed); +}; +``` + +### `linkableProviders` (const) + +```ts +const linkableProviders = (accounts: ReadonlyArray, social: ReadonlyArray): ReadonlyArray => { + const linked = new Set(linkedProviderIds(accounts)); + return social.filter((provider) => !linked.has(provider)); +}; +``` + +### `lockedPrefill` (const) + +```ts +const lockedPrefill = (field: string, lock: boolean | undefined): boolean => lock === true && readFieldPrefill(field) !== undefined; +``` + +### `mapAuthError` (const) + +```ts +const mapAuthError = (error: unknown, localization: Localization, fallback: string): string => { + if (error instanceof AuthActionError) { + if (error.code !== undefined && NOT_FRESH_CODES.has(error.code)) { + return localization.sessionNotFresh; + } + return error.message.trim() === "" ? fallback : error.message; + } + if (error instanceof LunoraError) { + return error.message.trim() === "" ? fallback : error.message; + } + return fallback === "" ? localization.genericError : fallback; +}; +``` + +### `notifyError` (const) + +```ts +const notifyError = (context: ControllerContext, error: unknown, fallback: string): void => { + context.onError?.(error); + pushToast(mapAuthError(error, context.localization, fallback)); +}; +``` + +### `passkeyLabel` (const) + +```ts +const passkeyLabel = (passkey: AuthPasskey, localization: Localization): string => { + const name = passkey.name?.trim(); + return name === undefined || name === "" ? localization.passkeyUnnamed : name; +}; +``` + +### `password` (const) + +```ts +const password = (value: string, localization: Localization, policy?: PasswordPolicy): string | undefined => validatePassword(value, localization, policy); +``` + +### `passwordRequirements` (const) + +```ts +const passwordRequirements = (value: string, localization: Localization, policy: PasswordPolicy = {}): ReadonlyArray => { + const minLength = policy.minLength ?? DEFAULT_PASSWORD_POLICY.minLength; + const requirements: PasswordRequirement[] = [ + { label: localization.passwordRuleLength.replace("{min}", String(minLength)), met: value.length >= minLength }, + ]; + if (policy.requireLowercase === true) { + requirements.push({ label: localization.passwordRuleLowercase, met: LOWERCASE.test(value) }); + } + if (policy.requireUppercase === true) { + requirements.push({ label: localization.passwordRuleUppercase, met: UPPERCASE.test(value) }); + } + if (policy.requireDigit === true) { + requirements.push({ label: localization.passwordRuleDigit, met: DIGIT.test(value) }); + } + if (policy.requireSymbol === true) { + requirements.push({ label: localization.passwordRuleSymbol, met: SYMBOL.test(value) }); + } + return requirements; +}; +``` + +### `passwordScore` (const) + +```ts +const passwordScore = (requirements: ReadonlyArray): number => { + if (requirements.length === 0) { + return 0; + } + return requirements.filter((requirement) => requirement.met).length / requirements.length; +}; +``` + +### `promptOneTap` (const) + +```ts +const promptOneTap = async (context: ControllerContext): Promise => { + try { + await context.authClient.oneTap({ callbackURL: resolveAfterSignIn(context.redirects.afterSignIn) }); + context.onSessionChange?.(); + } + catch (error) { + context.onError?.(error); + } +}; +``` + +### `providerLabel` (const) + +```ts +const providerLabel = (provider: string): string => { + const known = PROVIDER_LABELS[provider]; + if (known !== undefined) { + return known; + } + return provider + .split("-") + .map((part) => (part === "" ? part : `${part.charAt(0).toUpperCase()}${part.slice(1)}`)) + .join(" "); +}; +``` + +### `pushToast` (const) + +```ts +const pushToast = (message: string): number => { + const current = store.get().toasts; + const last = current.at(-1); + if (last?.message === message) { + return last.id; + } + nextId += 1; + const toast: Toast = { id: nextId, message }; + store.update({ toasts: [...current, toast] }); + if (typeof setTimeout === "function") { + timers.set(toast.id, setTimeout(() => { + dismissToast(toast.id); + }, TOAST_DURATION_MS)); + } + return toast.id; +}; +``` + +### `readFieldPrefill` (const) + +```ts +const readFieldPrefill = (field: string): string | undefined => { + if (!PREFILLABLE.has(field)) { + return undefined; + } + const value = queryParameter(field); + if (value === undefined) { + return undefined; + } + const trimmed = value.trim(); + return trimmed === "" || CONTROL_CHARACTERS.test(trimmed) ? undefined : trimmed; +}; +``` + +### `readLastLoginMethod` (const) + +```ts +const readLastLoginMethod = (cookieName: string = LAST_LOGIN_METHOD_COOKIE): string | undefined => { + const cookie = (globalThis as { + document?: { + cookie?: string; + }; + }).document?.cookie; + if (cookie === undefined || cookie === "") { + return undefined; + } + for (const part of cookie.split(";")) { + const separator = part.indexOf("="); + if (separator === -1) { + continue; + } + if (part.slice(0, separator).trim() !== cookieName) { + continue; + } + const value = decodeURIComponent(part.slice(separator + 1).trim()); + return value === "" ? undefined : value; + } + return undefined; +}; +``` + +### `readRedirectTo` (const) + +```ts +const readRedirectTo = (parameter = "redirectTo"): string | undefined => { + const value = queryParameter(parameter); + if (value === undefined) { + return undefined; + } + const trimmed = value.trim(); + return isSafeRedirect(trimmed) ? trimmed : undefined; +}; +``` + +### `registerAuthClientPlugins` (const) + +```ts +const registerAuthClientPlugins = (authClient: unknown, plugins: PluginFlags = {}): void => { + if (typeof authClient !== "object" && typeof authClient !== "function") { + return; + } + if (authClient === null) { + return; + } + const flags = withEveryFlow(false); + for (const flow of FLOW_NAMES) { + flags[flow] = plugins[flow] ?? false; + } + registry.set(authClient, flags); +}; +``` + +### `renderCaptcha` (const) + +```ts +const renderCaptcha = (element: Element, options: RenderCaptchaOptions): (() => void) => { + const provider = PROVIDERS[options.provider]; + let widgetId: unknown; + let disposed = false; + let ownToken: string | undefined; + void loadScript(provider.script) + .then(() => { + if (disposed) { + return false; + } + const api = (globalThis as unknown as Record)[provider.global]; + if (api === undefined) { + throw new Error(`${provider.global} did not appear after its script loaded`); + } + widgetId = api.render(element, { + callback: (token: string) => { + ownToken = token; + setCaptchaToken(token); + }, + "expired-callback": () => { + ownToken = undefined; + setCaptchaToken(undefined); + }, + sitekey: options.siteKey, + }); + return true; + }) + .catch((error: unknown) => { + options.onError?.(error); + }); + return () => { + disposed = true; + if (ownToken !== undefined && store.get().token === ownToken) { + setCaptchaToken(undefined); + } + const api = (globalThis as unknown as Record)[provider.global]; + api?.reset?.(widgetId); + }; +}; +``` + +### `required` (const) + +```ts +const required = (value: string, message: string): string | undefined => (value.trim() === "" ? message : undefined); +``` + +### `resetAuthConfigDiscovery` (const) + +```ts +const resetAuthConfigDiscovery = (): void => { + handles.clear(); +}; +``` + +### `resetFlowWarnings` (const) + +```ts +const resetFlowWarnings = (): void => { + warned.clear(); +}; +``` + +### `resetToasts` (const) + +```ts +const resetToasts = (): void => { + for (const timer of timers.values()) { + clearTimeout(timer); + } + timers.clear(); + store.set({ toasts: [] }); +}; +``` + +### `resolveAfterSignIn` (const) + +```ts +const resolveAfterSignIn = (fallback: string): string => readRedirectTo() ?? fallback; +``` + +### `resolveContext` (const) + +```ts +const resolveContext = (config: AuthUIConfig, discovered?: DiscoveredConfig): ControllerContext => { + return { + authClient: config.authClient as AuthClient, + avatar: { maxSize: config.avatar?.maxSize ?? DEFAULT_AVATAR_MAX_SIZE, upload: config.avatar?.upload }, + basePath: config.basePath ?? DEFAULT_BASE_PATH, + credentials: discovered?.emailAndPassword ?? true, + forgotPasswordMethod: config.forgotPassword?.method ?? "link", + localization: resolveLocalization(config.localization), + nav: config.nav, + onError: config.onError, + onSessionChange: config.onSessionChange, + organization: { + allowUserToCreate: discovered?.organization?.allowUserToCreate ?? true, + invitationLimit: discovered?.organization?.invitationLimit, + limit: discovered?.organization?.limit, + membershipLimit: discovered?.organization?.membershipLimit, + roles: config.organization?.roles ?? discovered?.organization?.roles ?? false, + showSlug: config.organization?.showSlug ?? true, + teams: config.organization?.teams ?? discovered?.organization?.teams ?? false, + }, + password: config.password ?? {}, + plugins: resolvePlugins(config.authClient, config.plugins, discovered), + redirects: resolveRedirects(config.redirects), + signUp: discovered?.signUp ?? true, + social: config.social ?? discovered?.socialProviders ?? [], + themeVariables: resolveThemeVariables(config.theme), + viewPaths: resolveViewPaths(config.viewPaths), + }; +}; +``` + +### `resolveLocalization` (const) + +```ts +const resolveLocalization = (overrides?: Partial): Localization => { + return { + ...DEFAULT_LOCALIZATION, + ...overrides, + }; +}; +``` + +### `resolveThemeVariables` (const) + +```ts +const resolveThemeVariables = (theme?: (defaults: ThemeTokens) => ThemeTokens): Readonly> => { + if (!theme) { + return {}; + } + const resolved = theme({ ...DEFAULT_THEME_TOKENS }); + const variables: Record = {}; + for (const token of Object.keys(DEFAULT_THEME_TOKENS) as (keyof ThemeTokens)[]) { + const value = resolved[token]; + if (typeof value === "string" && value !== DEFAULT_THEME_TOKENS[token]) { + variables[toCustomProperty(token)] = value; + } + } + return variables; +}; +``` + +### `scopeLabels` (const) + +```ts +const scopeLabels = (scope?: string): ReadonlyArray => { + const parts = (scope ?? "").split(SCOPE_SEPARATOR).filter((part) => part !== ""); + return parts.map((part) => SCOPE_LABELS[part] ?? part); +}; +``` + +### `sessionLabel` (const) + +```ts +const sessionLabel = (session: AuthSession, localization: Localization): string => { + const agent = session.userAgent?.trim(); + if (agent !== undefined && agent !== "") { + return agent; + } + return session.ipAddress ?? localization.unknownDevice; +}; +``` + +### `setCaptchaToken` (const) + +```ts +const setCaptchaToken = (token: string | undefined): void => { + store.set({ token }); +}; +``` + +### `signInAnonymously` (const) + +```ts +const signInAnonymously = async (context: ControllerContext): Promise => { + try { + assertOk(await context.authClient.signIn.anonymous()); + context.onSessionChange?.(); + context.nav.replace(context.redirects.afterSignIn); + } + catch (error) { + notifyError(context, error, context.localization.signInFailed); + } +}; +``` + +### `signInWithSocial` (const) + +```ts +const signInWithSocial = async (context: ControllerContext, provider: string): Promise => { + try { + assertOk(await context.authClient.signIn.social({ callbackURL: resolveAfterSignIn(context.redirects.afterSignIn), provider })); + } + catch (error) { + notifyError(context, error, context.localization.signInFailed); + } +}; +``` + +### `signOut` (const) + +```ts +const signOut = async (context: ControllerContext): Promise => { + try { + assertOk(await context.authClient.signOut()); + context.onSessionChange?.(); + context.nav.replace(context.redirects.afterSignOut); + } + catch (error) { + context.onError?.(error); + } +}; +``` + +### `slugify` (const) + +```ts +const slugify = (value: string): string => value + .toLowerCase() + .trim() + .replaceAll(/[^a-z0-9]+/gu, "-") + .replaceAll(/^-|-$/gu, ""); +``` + +### `subscribeToasts` (const) + +```ts +const subscribeToasts = (onChange: () => void): (() => void) => store.subscribe(onChange); +``` + +### `totpSecret` (const) + +```ts +const totpSecret = (totpUri?: string): string | undefined => { + if (totpUri === undefined || totpUri === "") { + return undefined; + } + const query = totpUri.slice(totpUri.indexOf("?") + 1); + const secret = new URLSearchParams(query).get("secret"); + return secret === null || secret === "" ? undefined : secret; +}; +``` + +### `useAuthUI` (unknown) + +```ts +useAuthUI +``` + +### `useAuthUILink` (unknown) + +```ts +useAuthUILink +``` + +### `useController` (const) + +```ts +const useController = (factory: (context: ControllerContext) => Controller, deps: DependencyList = []): [ + TState, + TActions +] => { + const context = useAuthUI(); + const controller = useMemo(() => factory(context), [context, ...deps]); + const state = useSyncExternalStore(controller.subscribe, controller.getState, controller.getState); + useEffect(() => controller.destroy, [controller]); + return [state, controller.actions]; +}; +``` + +### `useThemeStyle` (const) + +```ts +const useThemeStyle = (): CSSProperties | undefined => { + const { themeVariables } = useAuthUI(); + return Object.keys(themeVariables).length === 0 ? undefined : themeVariables; +}; +``` + +### `userInitials` (const) + +```ts +const userInitials = (user?: AuthUser): string => { + const name = user?.name?.trim(); + if (name !== undefined && name !== "") { + const parts = name.split(WHITESPACE).filter((part) => part !== ""); + const first = parts.at(0) ?? ""; + const last = parts.at(-1) ?? ""; + const initials = parts.length > 1 ? `${first.charAt(0)}${last.charAt(0)}` : first.slice(0, 2); + return initials.toUpperCase(); + } + const email = user?.email?.trim(); + return email === undefined || email === "" ? "?" : email.charAt(0).toUpperCase(); +}; +``` + +### `userLabel` (const) + +```ts +const userLabel = (user?: AuthUser): string => { + const name = user?.name?.trim(); + if (name !== undefined && name !== "") { + return name; + } + return user?.email ?? ""; +}; +``` + +### `validatePassword` (const) + +```ts +const validatePassword = (value: string, localization: Localization, policy: PasswordPolicy = {}): string | undefined => { + if (value.trim() === "") { + return localization.passwordRequired; + } + const minLength = policy.minLength ?? DEFAULT_PASSWORD_POLICY.minLength; + const maxLength = policy.maxLength ?? DEFAULT_PASSWORD_POLICY.maxLength; + if (value.length < minLength) { + return localization.passwordTooShort.replace("{min}", String(minLength)); + } + if (value.length > maxLength) { + return localization.passwordTooLong.replace("{max}", String(maxLength)); + } + if (policy.requireLowercase === true && !LOWERCASE.test(value)) { + return localization.passwordRuleLowercase; + } + if (policy.requireUppercase === true && !UPPERCASE.test(value)) { + return localization.passwordRuleUppercase; + } + if (policy.requireDigit === true && !DIGIT.test(value)) { + return localization.passwordRuleDigit; + } + if (policy.requireSymbol === true && !SYMBOL.test(value)) { + return localization.passwordRuleSymbol; + } + return undefined; +}; +``` + +### `withRedirectTo` (const) + +```ts +const withRedirectTo = (path: string): string => { + const target = readRedirectTo(); + if (target === undefined) { + return path; + } + const [base, existing = ""] = path.split("?"); + const parameters = new URLSearchParams(existing); + parameters.set("redirectTo", target); + return `${base ?? path}?${parameters.toString()}`; +}; +``` diff --git a/package.json b/package.json index 2ba561c46b..5ed74ecb08 100644 --- a/package.json +++ b/package.json @@ -52,7 +52,7 @@ "lint:types": "vis run lint:types && pnpm run lint:types:registry", "lint:types:registry": "pnpm run build:packages && tsc -p registry/tsconfig.json", "multi-semantic-release": "multi-semantic-release", - "postinstall": "node scripts/generate-package-og-images.js && node scripts/generate-labeler-config.js --skip-ci && node scripts/check-cerebro-peer-lockstep.js && node scripts/check-sibling-peer-ranges.js && node scripts/check-skill-mirrors.js && node scripts/check-registry-catalog-ranges.js", + "postinstall": "node scripts/generate-package-og-images.js && node scripts/generate-labeler-config.js --skip-ci && node scripts/check-cerebro-peer-lockstep.js && node scripts/check-sibling-peer-ranges.js && node scripts/check-skill-mirrors.js && node scripts/check-registry-catalog-ranges.js && node scripts/check-agents-md-packages.js", "prepare": "vis hook install", "test": "vis run test --query \"project!=lunora-e2e&&project!=lunora-playground\"", "test:affected": "vis affected test --fail-fast --query \"project!=lunora-e2e&&project!=lunora-playground\"", diff --git a/packages/advisor/package.json b/packages/advisor/package.json index 5a50a0fa7a..9c9dc83058 100644 --- a/packages/advisor/package.json +++ b/packages/advisor/package.json @@ -61,7 +61,7 @@ "fallow:health": "fallow health --score" }, "dependencies": { - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "@lunora/server": "1.0.0-alpha.56" }, "devDependencies": { diff --git a/packages/agent/package.json b/packages/agent/package.json index 345f695650..c18e920a64 100644 --- a/packages/agent/package.json +++ b/packages/agent/package.json @@ -87,12 +87,12 @@ "test:coverage": "pnpm exec vitest run --coverage" }, "dependencies": { - "@lunora/ai": "1.0.0-alpha.44", - "@lunora/errors": "1.0.0-alpha.10", - "@lunora/mail": "1.0.0-alpha.37", + "@lunora/ai": "1.0.0-alpha.45", + "@lunora/errors": "1.0.0-alpha.11", + "@lunora/mail": "1.0.0-alpha.38", "@lunora/server": "1.0.0-alpha.56", - "@lunora/values": "1.0.0-alpha.13", - "@lunora/workflow": "1.0.0-alpha.15", + "@lunora/values": "1.0.0-alpha.14", + "@lunora/workflow": "1.0.0-alpha.16", "@modelcontextprotocol/sdk": "catalog:mcp", "ai": "catalog:ai" }, diff --git a/packages/auth/package.json b/packages/auth/package.json index 6243d6b953..bd556f456f 100644 --- a/packages/auth/package.json +++ b/packages/auth/package.json @@ -116,9 +116,9 @@ "@better-auth/oauth-provider": "catalog:auth", "@better-auth/passkey": "catalog:auth", "@better-auth/scim": "catalog:auth", - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "@lunora/server": "1.0.0-alpha.56", - "@lunora/values": "1.0.0-alpha.13", + "@lunora/values": "1.0.0-alpha.14", "@visulima/disposable-email-domains": "catalog:email", "@visulima/email-verifier": "catalog:email", "@visulima/free-email-domains": "catalog:email", diff --git a/packages/cli/package.json b/packages/cli/package.json index 1dd4da717d..aa74b6e973 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -68,12 +68,12 @@ "dependencies": { "@bomb.sh/tab": "0.0.21", "@lunora/advisor": "1.0.0-alpha.60", - "@lunora/bindings": "1.0.0-alpha.15", + "@lunora/bindings": "1.0.0-alpha.16", "@lunora/codegen": "1.0.0-alpha.82", "@lunora/config": "1.0.0-alpha.107", - "@lunora/container": "1.0.0-alpha.18", + "@lunora/container": "1.0.0-alpha.19", "@lunora/d1": "1.0.0-alpha.56", - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "@lunora/mcp": "1.0.0-alpha.52", "@lunora/runtime": "1.0.0-alpha.49", "@lunora/seed": "1.0.0-alpha.56", diff --git a/packages/client/package.json b/packages/client/package.json index d367a12921..2bf3d3f866 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -81,7 +81,7 @@ "fallow:health": "fallow health --score" }, "dependencies": { - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "@visulima/storage-client": "catalog:storage" }, "devDependencies": { diff --git a/packages/cloudflare-access/package.json b/packages/cloudflare-access/package.json index 33034b1aec..a63b2d495e 100644 --- a/packages/cloudflare-access/package.json +++ b/packages/cloudflare-access/package.json @@ -68,7 +68,7 @@ "fallow:health": "fallow health --score" }, "dependencies": { - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "jose": "catalog:auth" }, "devDependencies": { diff --git a/packages/codegen/package.json b/packages/codegen/package.json index 3f1bf06b2a..10a2ac5c71 100644 --- a/packages/codegen/package.json +++ b/packages/codegen/package.json @@ -63,13 +63,13 @@ "dependencies": { "@lunora/advisor": "1.0.0-alpha.60", "@lunora/agent": "1.0.0-alpha.35", - "@lunora/container": "1.0.0-alpha.18", - "@lunora/errors": "1.0.0-alpha.10", - "@lunora/platform": "1.0.0-alpha.1", - "@lunora/queue": "1.0.0-alpha.13", - "@lunora/scheduler": "1.0.0-alpha.16", - "@lunora/values": "1.0.0-alpha.13", - "@lunora/workflow": "1.0.0-alpha.15", + "@lunora/container": "1.0.0-alpha.19", + "@lunora/errors": "1.0.0-alpha.11", + "@lunora/platform": "1.0.0-alpha.2", + "@lunora/queue": "1.0.0-alpha.14", + "@lunora/scheduler": "1.0.0-alpha.17", + "@lunora/values": "1.0.0-alpha.14", + "@lunora/workflow": "1.0.0-alpha.16", "jsonc-parser": "catalog:vite", "ts-morph": "catalog:tooling" }, diff --git a/packages/config/package.json b/packages/config/package.json index a2e33ab172..0f5d84a074 100644 --- a/packages/config/package.json +++ b/packages/config/package.json @@ -69,8 +69,8 @@ }, "dependencies": { "@lunora/codegen": "1.0.0-alpha.82", - "@lunora/container": "1.0.0-alpha.18", - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/container": "1.0.0-alpha.19", + "@lunora/errors": "1.0.0-alpha.11", "@lunora/seed": "1.0.0-alpha.56", "@visulima/colorize": "2.0.0", "@visulima/find-ai-runner": "1.0.0", diff --git a/packages/d1/package.json b/packages/d1/package.json index f0f4334a05..532c74ee2b 100644 --- a/packages/d1/package.json +++ b/packages/d1/package.json @@ -65,9 +65,9 @@ "fallow:health": "fallow health --score" }, "dependencies": { - "@lunora/errors": "1.0.0-alpha.10", - "@lunora/platform": "1.0.0-alpha.1", - "@lunora/shard-engine": "1.0.0-alpha.4", + "@lunora/errors": "1.0.0-alpha.11", + "@lunora/platform": "1.0.0-alpha.2", + "@lunora/shard-engine": "1.0.0-alpha.5", "@lunora/sql-store": "1.0.0-alpha.58", "drizzle-orm": "catalog:drizzle" }, diff --git a/packages/db/package.json b/packages/db/package.json index b5e8329d0c..1c15d27f1c 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -70,7 +70,7 @@ }, "dependencies": { "@lunora/client": "1.0.0-alpha.35", - "@lunora/errors": "1.0.0-alpha.10" + "@lunora/errors": "1.0.0-alpha.11" }, "devDependencies": { "@codspeed/vitest-plugin": "catalog:test", diff --git a/packages/dispatch/package.json b/packages/dispatch/package.json index c641fd30d8..c30e4e2b0f 100644 --- a/packages/dispatch/package.json +++ b/packages/dispatch/package.json @@ -54,7 +54,7 @@ "fallow:health": "fallow health --score" }, "dependencies": { - "@lunora/errors": "1.0.0-alpha.8" + "@lunora/errors": "1.0.0-alpha.11" }, "devDependencies": { "@types/node": "catalog:types", diff --git a/packages/do/package.json b/packages/do/package.json index 1bb2cd5b17..0b643ee9e4 100644 --- a/packages/do/package.json +++ b/packages/do/package.json @@ -61,11 +61,11 @@ "fallow:health": "fallow health --score" }, "dependencies": { - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "@lunora/observability": "1.0.0-alpha.4", - "@lunora/platform": "1.0.0-alpha.1", - "@lunora/platform-cloudflare": "1.0.0-alpha.1", - "@lunora/shard-engine": "1.0.0-alpha.4", + "@lunora/platform": "1.0.0-alpha.2", + "@lunora/platform-cloudflare": "1.0.0-alpha.2", + "@lunora/shard-engine": "1.0.0-alpha.5", "drizzle-orm": "catalog:drizzle" }, "devDependencies": { diff --git a/packages/hyperdrive/package.json b/packages/hyperdrive/package.json index aa7aafa1ca..0a4c94499f 100644 --- a/packages/hyperdrive/package.json +++ b/packages/hyperdrive/package.json @@ -64,8 +64,8 @@ "fallow:health": "fallow health --score" }, "dependencies": { - "@lunora/errors": "1.0.0-alpha.10", - "@lunora/shard-engine": "1.0.0-alpha.4", + "@lunora/errors": "1.0.0-alpha.11", + "@lunora/shard-engine": "1.0.0-alpha.5", "@lunora/sql-store": "1.0.0-alpha.58", "drizzle-orm": "catalog:drizzle" }, diff --git a/packages/lunora/package.json b/packages/lunora/package.json index 5e47d6d2d5..df6e09b469 100644 --- a/packages/lunora/package.json +++ b/packages/lunora/package.json @@ -161,14 +161,14 @@ "@lunora/cli": "1.0.0-alpha.131", "@lunora/client": "1.0.0-alpha.35", "@lunora/do": "1.0.0-alpha.61", - "@lunora/errors": "1.0.0-alpha.10", - "@lunora/flags": "1.0.0-alpha.18", + "@lunora/errors": "1.0.0-alpha.11", + "@lunora/flags": "1.0.0-alpha.19", "@lunora/observability": "1.0.0-alpha.4", - "@lunora/platform": "1.0.0-alpha.1", + "@lunora/platform": "1.0.0-alpha.2", "@lunora/ratelimit": "1.0.0-alpha.14", "@lunora/runtime": "1.0.0-alpha.49", "@lunora/server": "1.0.0-alpha.56", - "@lunora/values": "1.0.0-alpha.13" + "@lunora/values": "1.0.0-alpha.14" }, "devDependencies": { "@codspeed/vitest-plugin": "catalog:test", diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 891feb229f..9dc9684411 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -68,7 +68,7 @@ }, "dependencies": { "@lunora/client": "1.0.0-alpha.35", - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "@modelcontextprotocol/sdk": "catalog:mcp" }, "devDependencies": { diff --git a/packages/observability/package.json b/packages/observability/package.json index 8fd1a49036..8d93ae0bed 100644 --- a/packages/observability/package.json +++ b/packages/observability/package.json @@ -58,9 +58,9 @@ "test:coverage": "vitest run --coverage" }, "dependencies": { - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "@lunora/fingerprint": "1.0.0-alpha.4", - "@lunora/shard-engine": "1.0.0-alpha.4", + "@lunora/shard-engine": "1.0.0-alpha.5", "@visulima/redact": "catalog:redact" }, "devDependencies": { diff --git a/packages/payment/package.json b/packages/payment/package.json index 97e8df9f12..2d5c7f4078 100644 --- a/packages/payment/package.json +++ b/packages/payment/package.json @@ -85,9 +85,9 @@ "fallow:health": "fallow health --score" }, "dependencies": { - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "@lunora/server": "1.0.0-alpha.56", - "@lunora/values": "1.0.0-alpha.13", + "@lunora/values": "1.0.0-alpha.14", "dinero.js": "2.0.2" }, "devDependencies": { diff --git a/packages/platform-node/package.json b/packages/platform-node/package.json index 3b8edccd76..58e8750a3c 100644 --- a/packages/platform-node/package.json +++ b/packages/platform-node/package.json @@ -60,7 +60,7 @@ "fallow:health": "fallow health --score" }, "dependencies": { - "@lunora/platform": "1.0.0-alpha.1", + "@lunora/platform": "1.0.0-alpha.2", "better-sqlite3": "^12.11.1" }, "devDependencies": { diff --git a/packages/ratelimit/package.json b/packages/ratelimit/package.json index 459eb0a56d..bbf96e93cc 100644 --- a/packages/ratelimit/package.json +++ b/packages/ratelimit/package.json @@ -61,7 +61,7 @@ "fallow:health": "fallow health --score" }, "dependencies": { - "@lunora/errors": "1.0.0-alpha.10" + "@lunora/errors": "1.0.0-alpha.11" }, "devDependencies": { "@codspeed/vitest-plugin": "catalog:test", diff --git a/packages/react/package.json b/packages/react/package.json index 57a08f4cfa..c73f3e70f3 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -70,7 +70,7 @@ }, "dependencies": { "@lunora/client": "1.0.0-alpha.35", - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "@lunora/ratelimit": "1.0.0-alpha.14", "@visulima/storage-client": "catalog:storage" }, diff --git a/packages/runtime/package.json b/packages/runtime/package.json index cbcdbbb084..d4b5e59ec8 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -61,9 +61,9 @@ "fallow:health": "fallow health --score" }, "dependencies": { - "@lunora/bindings": "1.0.0-alpha.15", - "@lunora/errors": "1.0.0-alpha.10", - "@lunora/platform": "1.0.0-alpha.1" + "@lunora/bindings": "1.0.0-alpha.16", + "@lunora/errors": "1.0.0-alpha.11", + "@lunora/platform": "1.0.0-alpha.2" }, "devDependencies": { "@cloudflare/vitest-pool-workers": "catalog:cloudflare", diff --git a/packages/seed/package.json b/packages/seed/package.json index 8a3d9083c5..a744a702d4 100644 --- a/packages/seed/package.json +++ b/packages/seed/package.json @@ -62,7 +62,7 @@ }, "dependencies": { "@faker-js/faker": "catalog:data", - "@lunora/errors": "1.0.0-alpha.10" + "@lunora/errors": "1.0.0-alpha.11" }, "devDependencies": { "@lunora/server": "1.0.0-alpha.56", diff --git a/packages/server/package.json b/packages/server/package.json index 0862b4ab7e..ab434654b2 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -81,9 +81,9 @@ "fallow:health": "fallow health --score" }, "dependencies": { - "@lunora/errors": "1.0.0-alpha.10", - "@lunora/scheduler": "1.0.0-alpha.16", - "@lunora/values": "1.0.0-alpha.13", + "@lunora/errors": "1.0.0-alpha.11", + "@lunora/scheduler": "1.0.0-alpha.17", + "@lunora/values": "1.0.0-alpha.14", "drizzle-orm": "catalog:drizzle", "hono": "catalog:http" }, diff --git a/packages/solid/package.json b/packages/solid/package.json index 5c9b204e9c..b39e1367b0 100644 --- a/packages/solid/package.json +++ b/packages/solid/package.json @@ -69,7 +69,7 @@ }, "dependencies": { "@lunora/client": "1.0.0-alpha.35", - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "@lunora/ratelimit": "1.0.0-alpha.14", "@visulima/storage-client": "catalog:storage" }, diff --git a/packages/sql-store/package.json b/packages/sql-store/package.json index f28943a45b..2cf8f8df20 100644 --- a/packages/sql-store/package.json +++ b/packages/sql-store/package.json @@ -65,8 +65,8 @@ "fallow:health": "fallow health --score" }, "dependencies": { - "@lunora/errors": "1.0.0-alpha.10", - "@lunora/shard-engine": "1.0.0-alpha.4", + "@lunora/errors": "1.0.0-alpha.11", + "@lunora/shard-engine": "1.0.0-alpha.5", "drizzle-orm": "catalog:drizzle" }, "devDependencies": { diff --git a/packages/studio/package.json b/packages/studio/package.json index 0107381fe6..1daa3a7079 100644 --- a/packages/studio/package.json +++ b/packages/studio/package.json @@ -78,9 +78,9 @@ "@lingui/core": "catalog:i18n", "@lingui/message-utils": "catalog:i18n", "@lunora/advisor": "1.0.0-alpha.60", - "@lunora/bindings": "1.0.0-alpha.15", + "@lunora/bindings": "1.0.0-alpha.16", "@lunora/client": "1.0.0-alpha.35", - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "@lunora/react": "1.0.0-alpha.39", "@tanstack/react-query": "catalog:frontend", "@tanstack/react-router": "catalog:frontend", diff --git a/packages/svelte/package.json b/packages/svelte/package.json index 64a04f8126..0998f7d406 100644 --- a/packages/svelte/package.json +++ b/packages/svelte/package.json @@ -73,7 +73,7 @@ }, "dependencies": { "@lunora/client": "1.0.0-alpha.35", - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "@lunora/ratelimit": "1.0.0-alpha.14", "@lunora/runtime": "1.0.0-alpha.49", "@visulima/storage-client": "catalog:storage" diff --git a/packages/testing/package.json b/packages/testing/package.json index 4ed8e69b32..1e35d2a457 100644 --- a/packages/testing/package.json +++ b/packages/testing/package.json @@ -65,10 +65,10 @@ }, "dependencies": { "@lunora/agent": "1.0.0-alpha.35", - "@lunora/errors": "1.0.0-alpha.10", - "@lunora/mail": "1.0.0-alpha.37", + "@lunora/errors": "1.0.0-alpha.11", + "@lunora/mail": "1.0.0-alpha.38", "@lunora/server": "1.0.0-alpha.56", - "@lunora/shard-engine": "1.0.0-alpha.4" + "@lunora/shard-engine": "1.0.0-alpha.5" }, "devDependencies": { "@lunora/do": "1.0.0-alpha.61", diff --git a/packages/vite/package.json b/packages/vite/package.json index 252feeedb9..42dd7a72b6 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -62,7 +62,7 @@ "@cloudflare/vite-plugin": "catalog:vite", "@lunora/codegen": "1.0.0-alpha.82", "@lunora/config": "1.0.0-alpha.107", - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "@visulima/vite-overlay": "catalog:vite", "jsonc-parser": "catalog:vite", "ts-morph": "catalog:tooling" diff --git a/packages/vue/package.json b/packages/vue/package.json index 423b58e357..cbd5e07ae6 100644 --- a/packages/vue/package.json +++ b/packages/vue/package.json @@ -73,7 +73,7 @@ }, "dependencies": { "@lunora/client": "1.0.0-alpha.35", - "@lunora/errors": "1.0.0-alpha.10", + "@lunora/errors": "1.0.0-alpha.11", "@lunora/ratelimit": "1.0.0-alpha.14", "@lunora/runtime": "1.0.0-alpha.49", "@visulima/storage-client": "catalog:storage" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b2dd2cabf4..a0fd27ba82 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2809,7 +2809,7 @@ importers: specifier: workspace:* version: link:../platform '@lunora/platform-cloudflare': - specifier: 1.0.0-alpha.1 + specifier: 1.0.0-alpha.2 version: link:../platform-cloudflare '@lunora/shard-engine': specifier: workspace:* diff --git a/scripts/api-snapshot.js b/scripts/api-snapshot.js index a70ca6c9b5..d9f7737cb0 100644 --- a/scripts/api-snapshot.js +++ b/scripts/api-snapshot.js @@ -6,6 +6,8 @@ * `dist/*.d.ts` entries, and pins it in committed `api-snapshots/.api.md` * files. A breaking change to a covered surface must land together with an * explicit, reviewable snapshot update — it cannot ship on a reviewer's memory. + * A source-shipping package (exports pointing at `.ts`/`.tsx` instead of a build + * output) is extracted straight from that source instead — see `collectEntries`. * * node scripts/api-snapshot.js check # (default) fail if the surface drifted * node scripts/api-snapshot.js update # regenerate the snapshots @@ -57,6 +59,13 @@ const snapshotsDir = join(rootDir, "api-snapshots"); * deploy driver, capabilities mostly `unsupported`/`emulated`), and its public * surface is still expected to move. Add it here once it graduates past spike * stage, alongside `platform`/`platform-cloudflare`. + * + * `auth-ui` IS covered (TIER_2) despite being `private: true` with no build + * step — privacy and "no dist" are not exemptions (see `dispatch`, also + * private, also covered). Its `core`/`react` exports point at `.ts`/`.tsx` + * source and are extracted via the source-file fallback in `collectEntries`. + * Only `./core` and `./react` are wired into its exports map today; `solid`, + * `svelte`, `vue`, `angular` aren't covered until they are. */ const TIER_1 = [ "server", @@ -92,6 +101,7 @@ const TIER_2 = [ "astro", "nuxt", "auth", + "auth-ui", "storage", "scheduler", "mail", @@ -151,6 +161,11 @@ const collectEntries = (pkgDir) => { if (types) { entries.push({ dts: resolve(pkgDir, types), subpath }); + } else if (typeof value === "string" && /\.(ts|tsx)$/.test(value)) { + // Source-shipping packages (no build step, no `dist`) point their + // exports map straight at `.ts`/`.tsx` source — extract from that + // directly instead of a built `.d.ts`. + entries.push({ dts: resolve(pkgDir, value), subpath }); } } } else if (typeof manifest.types === "string") { diff --git a/scripts/check-agents-md-packages.js b/scripts/check-agents-md-packages.js new file mode 100644 index 0000000000..7c952e9263 --- /dev/null +++ b/scripts/check-agents-md-packages.js @@ -0,0 +1,73 @@ +/** + * Guards the `AGENTS.md` (`CLAUDE.md` symlinks to it) `### Packages` table + * against `packages/*` actually existing on disk. + * + * AGENTS.md is the file every coding agent reads to decide which package owns + * a change. A package added or extracted without a table row (or at least a + * prose mention) is invisible to that decision — five packages (`auth-ui`, + * `platform`, `platform-cloudflare`, `platform-node`, `shard-engine`) drifted + * out of the file this way before plan 287 fixed it. This check keeps the fix + * from silently rotting again. + * + * Coverage: `packages/` only — `apps/`, `examples/`, `tests/` are out of + * scope for the table by design (plan 287 §9 records the decision). + * + * Match rule: substring match on the exact manifest `name` anywhere in + * AGENTS.md — a table cell or a prose mention both count. Parsing the table + * structure would be more precise but brittle to reformatting; a name that + * shows up in prose (like the platform-family paragraph) is still coverage a + * reader can act on, which is what keeps this check honest without being + * brittle. + * + * Run on every `pnpm install` via the root `postinstall` script. + */ +import { readdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const rootDir = join(__dirname, ".."); +const packagesDir = join(rootDir, "packages"); +const agentsMdPath = join(rootDir, "AGENTS.md"); + +const agentsMd = readFileSync(agentsMdPath, "utf8"); + +const missing = []; + +for (const entry of readdirSync(packagesDir, { withFileTypes: true })) { + if (!entry.isDirectory()) { + continue; + } + + const manifestPath = join(packagesDir, entry.name, "package.json"); + + let manifest; + + try { + manifest = JSON.parse(readFileSync(manifestPath, "utf8")); + } catch { + // Unreadable/missing package.json — nothing to name-check. + continue; + } + + if (typeof manifest.name !== "string") { + continue; + } + + if (!agentsMd.includes(manifest.name)) { + missing.push(manifest.name); + } +} + +if (missing.length > 0) { + console.error(`❌ AGENTS.md does not mention ${missing.length} packages/* package(s):`); + + for (const name of missing.sort()) { + console.error(` - ${name}`); + } + + console.error(" Add a `### Packages` table row (or at least a prose mention) to AGENTS.md."); + process.exit(1); +} + +console.log("✅ AGENTS.md mentions every packages/* package."); diff --git a/scripts/check-sibling-peer-ranges.js b/scripts/check-sibling-peer-ranges.js index 4ad797ca23..8fad00d799 100644 --- a/scripts/check-sibling-peer-ranges.js +++ b/scripts/check-sibling-peer-ranges.js @@ -26,6 +26,18 @@ * this guard then fails the next install so a maintainer widens the range * floor instead of shipping a fresh time bomb. * + * A second, report-only mode covers exact sibling `dependencies` pins (as + * opposed to `peerDependencies`). Exact-pinned regular dependencies are this + * repo's *deliberate* lockstep convention (see point 1 above) — "satisfy" + * bumps them in lockstep whenever the CONSUMER package itself releases. But a + * consumer with no triggering commits since its dependency's last release + * keeps its stale pin indefinitely — the terminal case is a `private: true` + * package that never releases at all. That drift is invisible today (nothing + * walks `dependencies`) and, for a published sibling, means two installers of + * two different `@lunora/*` packages can resolve two physical copies of a + * shared dependency. This mode never fails the install — it only reports — + * because mid-release-train drift between trains is normal and expected. + * * Run on every `pnpm install` via the root `postinstall` script. */ @@ -42,23 +54,30 @@ const EXACT_VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/; const isSibling = (name) => name === "lunorash" || name.startsWith("@lunora/"); -let hasFailure = false; +const packageDirs = readdirSync(packagesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()); -for (const entry of readdirSync(packagesDir, { withFileTypes: true })) { - if (!entry.isDirectory()) { - continue; - } +const manifests = []; +const versions = {}; +for (const entry of packageDirs) { const manifestPath = join(packagesDir, entry.name, "package.json"); - let manifest; - try { - manifest = JSON.parse(readFileSync(manifestPath, "utf8")); + const manifest = JSON.parse(readFileSync(manifestPath, "utf8")); + + manifests.push({ dir: entry.name, manifest }); + + if (typeof manifest.name === "string" && typeof manifest.version === "string") { + versions[manifest.name] = manifest.version; + } } catch { continue; } +} + +let hasFailure = false; +for (const { dir, manifest } of manifests) { for (const [name, specifier] of Object.entries(manifest.peerDependencies ?? {})) { if (!isSibling(name) || typeof specifier !== "string" || !EXACT_VERSION_RE.test(specifier)) { continue; @@ -66,12 +85,39 @@ for (const entry of readdirSync(packagesDir, { withFileTypes: true })) { hasFailure = true; - console.error(`❌ packages/${entry.name}'s peerDependency "${name}" is an exact pin (${specifier}).`); + console.error(`❌ packages/${dir}'s peerDependency "${name}" is an exact pin (${specifier}).`); console.error(` Exact sibling peers break on the next release of ${name} (and on 1.0 promotion).`); console.error(` Use a range instead, e.g. ">=${specifier} <2.0.0-0".`); } } +// Report-only: exact sibling `dependencies` pins that have drifted behind the +// dependency's current published version. Never fails the install — see the +// doc comment above for why this is a report, not a gate. +let dependencyWarnings = 0; + +for (const { dir, manifest } of manifests) { + for (const [name, specifier] of Object.entries(manifest.dependencies ?? {})) { + if (!isSibling(name) || typeof specifier !== "string" || specifier.startsWith("workspace:")) { + continue; + } + + const current = versions[name]; + + if (!current || specifier === current) { + continue; + } + + dependencyWarnings += 1; + + console.warn(`⚠️ packages/${dir} depends on "${name}": "${specifier}" — current is "${current}".`); + } +} + +if (dependencyWarnings > 0) { + console.warn(`⚠️ ${dependencyWarnings} sibling dependency pin(s) are behind the current published version (report-only, does not fail install).`); +} + // The range fix only holds while multi-semantic-release runs with // `deps.bump: "satisfy"` — under the default "override" the next release // rewrites every sibling range back to an exact pin. Fail if that config drifts.