npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@molecule/app-svelte

v4.0.3

Published

Svelte framework bindings for molecule.dev

Readme

@molecule/app-svelte

Svelte framework bindings for molecule.dev.

Provides Svelte stores and context utilities for all molecule core interfaces: call setMoleculeContext(config) once in the root layout, then consume services anywhere below via store factories (createAuthStores, createThemeStores, createI18nStores, …).

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

<!-- +layout.svelte — wire providers ONCE, during component init -->
<script lang="ts">
  import type { Snippet } from 'svelte'
  import { setMoleculeContext } from '@molecule/app-svelte'
  import { provider as stateProvider } from '@molecule/app-state-zustand'
  import { provider as themeProvider } from '@molecule/app-theme-css-variables'
  import { createJWTAuthClient } from '@molecule/app-auth'

  setMoleculeContext({
    state: stateProvider,
    auth: createJWTAuthClient({ baseURL: '/api' }),
    theme: themeProvider,
  })

  let { children }: { children: Snippet } = $props()
</script>

{@render children()}
<!-- Component.svelte — consume via stores -->
<script lang="ts">
  import { createAuthStores, createThemeStores } from '@molecule/app-svelte'

  const { user, isAuthenticated, logout } = createAuthStores<{ name?: string }>()
  const { theme, toggleTheme, mode } = createThemeStores()
</script>

{#if $isAuthenticated}
  <div style:background={$theme.colors.background}>
    <h1>Welcome, {$user?.name}!</h1>
    <button onclick={toggleTheme}>Toggle ({$mode})</button>
    <button onclick={() => logout()}>Logout</button>
  </div>
{/if}
<!-- Dashboard.svelte — the session, the theme and translations as stores -->
<script lang="ts">
  import { useAuth, useTheme, useTranslation } from '@molecule/app-svelte'

  const { user, status, logout } = useAuth<{ name?: string }>()
  const { t } = useTranslation()
  const { theme, toggleTheme } = useTheme()
</script>

{#if $status === 'loading'}
  <p>{t('auth.restoring', undefined, { defaultValue: 'Restoring session...' })}</p>
{:else if $status === 'unauthenticated'}
  <p>{t('auth.required', undefined, { defaultValue: 'Please log in.' })}</p>
{:else}
  <div style:background={$theme.colors.background}>
    <h1>
      {t('greeting.welcome', { name: $user?.name ?? '' }, { defaultValue: 'Welcome, {{name}}!' })}
    </h1>
    <button onclick={toggleTheme}>
      {t('theme.toggle', undefined, { defaultValue: 'Toggle theme' })}
    </button>
    <button onclick={() => logout()}>
      {t('auth.logout', undefined, { defaultValue: 'Log out' })}
    </button>
  </div>
{/if}
<!-- FavoriteButton.svelte — a server-backed favorite that changes at once -->
<script lang="ts">
  import { useHttpClient, useOptimisticValue, useTranslation } from '@molecule/app-svelte'

  interface FavoriteRecord {
    slug: string
    favorited: boolean
    favoritesCount: number
  }

  let {
    article,
    onChanged,
  }: {
    article: FavoriteRecord
    onChanged?: (saved: FavoriteRecord) => void
  } = $props()

  const http = useHttpClient()
  const { t } = useTranslation()
  const { value: favorite, update } = useOptimisticValue({
    value: { favorited: article.favorited, count: article.favoritesCount },
    commit: async (next) => {
      const path = `/articles/${article.slug}/favorite`
      const response = next.favorited
        ? await http.post<{ article: FavoriteRecord }>(path)
        : await http.delete<{ article: FavoriteRecord }>(path)
      const saved = response.data.article
      onChanged?.(saved)
      return { favorited: saved.favorited, count: saved.favoritesCount }
    },
  })
</script>

<button
  aria-pressed={$favorite.favorited}
  aria-label={t('article.favorite', undefined, { defaultValue: 'Favorite article' })}
  onclick={() =>
    update((current) => ({
      favorited: !current.favorited,
      count: current.count + (current.favorited ? -1 : 1),
    }))}>{$favorite.count}</button
>
<!-- PortaledNode.svelte — content in document.body, exactly as React renders it -->
<script lang="ts">
  import { BodyPortal } from '@molecule/app-svelte'
</script>

<BodyPortal><div role="dialog">…</div></BodyPortal>

Session state is a three-way decision, not a boolean: status === 'loading' is undecided, so wait for it and redirect only on status === 'unauthenticated'; 'unavailable' keeps the session candidate for retry, so a restore that failed with anything other than a 401/403 never signs the user out.

Type

framework

Installation

npm install @molecule/app-svelte @molecule/app-device @molecule/app-forms @molecule/app-i18n @molecule/app-logger @molecule/app-platform @molecule/app-routing @molecule/app-state @molecule/app-storage @molecule/app-version svelte

API

Interfaces

Readable

Readable interface for subscribing.

interface Readable<T> {
  /**
   * Subscribe on value changes.
   * @param run subscription callback
   * @param invalidate cleanup callback
   */
  subscribe(this: void, run: Subscriber<T>, invalidate?: () => void): Unsubscriber
}

Writable

Writable interface for both updating and subscribing.

interface Writable<T> extends Readable<T> {
  /**
   * Set value and inform subscribers.
   * @param value to set
   */
  set(this: void, value: T): void

  /**
   * Update value using callback and inform subscribers.
   * @param updater callback
   */
  update(this: void, updater: Updater<T>): void
}

AuthState

Reactive authentication state snapshot (initialized, authenticated, user, loading, and error).

interface AuthState<T = UserProfile> {
  /**
   * The session's state as one value — render from this instead of combining
   * `initialized`/`authenticated`/`loading`. `'loading'` is undecided, so wait
   * and redirect only on `'unauthenticated'`; `'unavailable'` keeps the candidate
   * for retry and can have a null profile. A restore failure other than 401/403
   * never signs out. See {@link AuthStatus}.
   */
  status: AuthStatus

  /**
   * Whether auth state has been initialized.
   */
  initialized: boolean

  /**
   * Whether the client has an authenticated session. This is not a server
   * confirmation flag: during `'unavailable'` it can be false for a retained
   * token/cookie-only candidate with no cached profile. Use `status` for redirects.
   */
  authenticated: boolean

  /**
   * Current user, or null when none is cached. In particular, an `'unavailable'`
   * token/cookie-only restore has a retained candidate but no profile yet.
   */
  user: T | null

  /**
   * Whether an auth operation is in progress.
   */
  loading: boolean

  /**
   * Last auth error (if any).
   */
  error: string | null
}

AuthClient

Auth client interface that all auth bond packages must implement. Provides login/logout/register flows, token management, profile updates, and auth state subscription.

interface AuthClient<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  /**
   * Returns the current authentication state snapshot.
   *
   * READING the state starts the client's one session restore when nobody has called
   * {@link initialize} yet — lazily and exactly once, sharing the promise an explicit
   * `initialize()` returns. A hook (`useAuth()`), a subscriber, `isAuthenticated()` and
   * `getUser()` are reads too, so a client whose entry file dropped the template's
   * `authClient.initialize()` line still restores instead of reporting `'loading'`
   * forever.
   */
  getState(): AuthState<T>

  /**
   * Returns whether the user is currently authenticated.
   */
  isAuthenticated(): boolean

  /**
   * Gets the current user.
   */
  getUser(): T | null

  /**
   * Optional ownership marker for the current session. Compare values only within
   * this client: replacing or ending a session changes it, including re-adopting
   * the same token and user. Profile updates and same-session refreshes keep it.
   * Consumers can use it to discard stale async work without treating editable
   * user fields as an immutable account identifier. Providers without this
   * capability require the consumer's own stable identity check.
   */
  getSessionRevision?(): number

  /** Updates the cached user object (state + persistent storage) without hitting the network. */
  setUser(user: T | null): void

  /**
   * Gets the current access token.
   */
  getAccessToken(): string | null

  /**
   * Stores the access token in the configured token storage adapter (in a
   * browser, Web Storage; `'memory'` where no browser store exists). Use this
   * to seed the token after an out-of-band exchange (e.g. the OAuth
   * code→token redirect) instead of writing to `localStorage` directly,
   * which would violate the storage contract and make a stored bearer token
   * JS-readable (XSS-exfiltratable). Pass `null` to clear it.
   *
   * Passing `null` does not by itself sign a signed-in client out: use
   * {@link logout} to end a session, or {@link setUser} with `null` for
   * local-only sign-out. A non-null token on a client that is not signed in is
   * the first or second half of the app's own sign-in pair: together with
   * {@link setUser} it adopts the session (see there). Prefer {@link setSession}
   * with the token and user, or {@link login} / {@link register} for a
   * credential exchange.
   */
  setAccessToken(token: string | null): void

  /**
   * Adopts a session an out-of-band exchange already established: stores the
   * access token (and the refresh token when given), caches the user, and
   * sets the COMPLETE state — `initialized`, `authenticated`, `status:
   * 'authenticated'`, no error — in one update, with one subscriber
   * notification. Every hook reading the shared client sees the user as
   * signed in immediately.
   *
   * This is the way to seed an OAuth/custom sign-in. The field-setter pair
   * ({@link setAccessToken} then {@link setUser}, or the reverse) on a client
   * that is not signed in adopts the session the same way.
   */
  setSession(session: AuthSessionSeed<T>): void

  /**
   * Gets the refresh token.
   */
  getRefreshToken(): string | null

  /**
   * Logs in with credentials.
   */
  login(credentials: LoginCredentials): Promise<AuthResult<T>>

  /**
   * Logs out the current user. The server request is best-effort: a missing
   * logout route (404), any other HTTP failure, or a network error never makes
   * this method reject. It always clears the access token, refresh token and
   * cached user, stops automatic refresh, and publishes one settled
   * `authenticated: false`, `status: 'unauthenticated'` transition. Every pending
   * session operation loses ownership; a persistent marker prevents reload from
   * restoring an older session, and late credentials are revoked best-effort.
   *
   * When the API has no logout route, set {@link AuthClientConfigOptions.logoutEndpoint}
   * to `null` (or `''`) to skip the request. Local sign-out still happens.
   */
  logout(): Promise<void>

  /**
   * Registers a new user. Accepts the base fields plus the app's own fields
   * (`TRegister`) at the top level — see {@link RegisterData}.
   */
  register(data: RegisterData<TRegister>): Promise<AuthResult<T>>

  /**
   * Exchanges a stored refresh token, or re-reads `currentUserEndpoint` with the
   * existing access token/session cookie when the API has no refresh credential.
   * That fallback maps, stores and publishes the server user without renewing
   * the access token. Failures reject. A 401/403 ends the session, as does an
   * additional {@link AuthClientConfigOptions.currentUserRejectionStatuses}
   * code from the fallback. Transient failures retain it as unavailable. Use {@link updateProfile} for a profile
   * save, or {@link setUser} with the canonical row from an app-owned mutation.
   */
  refresh(): Promise<AuthResult<T>>

  /**
   * Requests a password reset.
   */
  requestPasswordReset(data: PasswordResetRequest): Promise<void>

  /**
   * Confirms a password reset.
   */
  confirmPasswordReset(data: PasswordResetConfirm): Promise<void>

  /**
   * Updates the current user's profile.
   * Returns the saved profile: the answer applied onto the signed-in user field
   * by field, with or without an `id` — a field it carries replaces the value
   * (`null` clears it), one it omits or leaves `undefined` is kept, so a field
   * cleared by omission must arrive as `null`. A non-object answer is returned
   * as it came. An answer for a replaced or ended session leaves the current one
   * untouched.
   */
  updateProfile(data: Partial<T>): Promise<T>

  /**
   * Changes the current user's password.
   */
  changePassword(oldPassword: string, newPassword: string): Promise<void>

  /** Initializes auth state (e.g., from stored tokens). */
  initialize(): Promise<void>

  /** Re-checks a restored session against the server, in the background — the boot-time validation an app with a stored token needs when a revoked or expired token… */
  validateSession?(): Promise<void>

  /** Resolves when the session restore started by `initialize()` has settled — the point after which the client knows whether this visitor is signed in. */
  whenRestored?(): Promise<void>

  /**
   * Subscribes to auth state changes.
   */
  subscribe(callback: (state: AuthState<T>) => void): () => void

  /**
   * Subscribes to auth state changes (alias for subscribe).
   */
  onAuthChange(callback: (state: AuthState<T>) => void): () => void

  /**
   * Gets the current access token (alias for getAccessToken).
   */
  getToken?(): string | null

  /**
   * Adds an auth event listener.
   *
   * The listener is typed by this client's profile: one signature,
   * `AuthEventListener<T>`, so an inline arrow is contextually typed and `event`
   * is never implicitly `any`. A client whose profile extends
   * {@link UserProfile} also accepts a default {@link AuthEventListener}: when
   * `T` extends `UserProfile`, `AuthEvent<T>` is assignable to
   * `AuthEvent<UserProfile>`, so a listener that takes the wider default event
   * accepts every event this client emits and keeps compiling. (`UserProfile`
   * is the wider type here — it has fewer required fields — and the assignable
   * direction runs from the client's `AuthEvent<T>` to the listener's
   * `AuthEvent<UserProfile>`.) A profile that does not extend `UserProfile`
   * (no `id`) rejects the default listener: an `AuthEvent<UserProfile>` would
   * promise an `id` the runtime user does not have, and the narrower-typed
   * event is not assignable to it.
   */
  addEventListener(listener: AuthEventListener<T>): () => void

  /**
   * Destroys the auth client.
   */
  destroy(): void
}

(The 4 longest member comments are shortened to their first sentence to fit; the full declaration is in node_modules/@molecule/app-auth/dist/types.d.ts.)

FormController

Form controller interface.

All form providers must implement this interface.

interface FormController<T extends FormValuesConstraint<T> = Record<string, unknown>> {
  /**
   * Gets the current form state.
   */
  getState(): FormState<T>

  /**
   * Gets the value of a specific field.
   */
  getValue(name: string): unknown
  getValue<K extends keyof T>(name: K): T[K]

  /**
   * Gets all form values.
   */
  getValues(): T

  /**
   * Sets the value of a specific field.
   */
  setValue(
    name: string,
    value: unknown,
    options?: { shouldValidate?: boolean; shouldDirty?: boolean; shouldTouch?: boolean },
  ): void

  /**
   * Sets multiple values at once.
   */
  setValues(values: Partial<T>, options?: { shouldValidate?: boolean }): void

  /**
   * Gets the error for a specific field.
   */
  getError(name: string): string | undefined

  /**
   * Sets the error for a specific field.
   */
  setError(name: string, error: string | undefined): void

  /**
   * Clears the error for a specific field.
   */
  clearError<K extends keyof T>(name: K): void

  /**
   * Clears all errors.
   */
  clearErrors(): void

  /**
   * Gets the field state for a specific field.
   */
  getFieldState<K extends keyof T>(name: K): FieldState<T[K]>

  /**
   * Registers a field for form management. A `defaultValue` that fills an
   * empty field is announced to subscribers once, in a microtask, so a field
   * registered during a render does not update other components mid-render.
   */
  register(nameOrOptions: string | RegisterOptions, options?: RegisterOptions): FieldRegistration

  /**
   * Unregisters a field.
   */
  unregister(name: string): void

  /**
   * Validates a specific field.
   */
  validateField<K extends keyof T>(name: K): Promise<boolean>

  /**
   * Validates all fields.
   */
  validate(): Promise<boolean>

  /**
   * Resets the form and clears errors, touched fields and submission state.
   *
   * With no argument it restores the current baseline — the initial
   * `defaultValues`, or the values a previous `reset(values)` established.
   * Passing `values` merges them over the current baseline and makes the
   * result the new baseline, so a form reset to freshly loaded or saved data
   * reads clean (`isDirty === false`). A changed non-null `id` replaces the
   * record and cancels a pending submit.
   */
  reset(values?: Partial<T>): void

  /**
   * Applies externally loaded values without clearing submission state.
   *
   * The new clean baseline is the original `defaultValues` plus this latest
   * record, never a merge of earlier records. With `keepDirtyValues`, edited
   * fields retain their values while pristine fields take the loaded values.
   * A changed non-null `id` still replaces the record and cancels a pending
   * submit. Equal-content baselines cause no update. `keepOmittedValues` opts
   * into incremental top-level field fills using the current clean baseline.
   */
  updateValues(values: Partial<T>, resetOptions?: FormUpdateOptions): void

  /**
   * Handles form submission.
   */
  handleSubmit(
    onSubmit: (values: T) => void | Promise<void>,
    onError?: (errors: Partial<Record<keyof T, string>>) => void,
  ): (event?: { preventDefault?: () => void }) => Promise<void>

  /**
   * Sets focus to a field.
   */
  setFocus(name: keyof T): void

  /**
   * Subscribes to form state changes.
   */
  subscribe(callback: (state: FormState<T>) => void): () => void

  /**
   * Destroys the form controller.
   */
  destroy(): void
}

FormResetOptions

Options controlling how externally supplied values replace a form's baseline.

interface FormResetOptions {
  /**
   * Keep fields whose current value differs from their baseline when `values`
   * changes. Pristine fields still take the new values. False by default, so a
   * new record can replace edits from the previous record.
   */
  keepDirtyValues?: boolean
}

FormOptions

Form creation options.

interface FormOptions<T extends FormValuesConstraint<T>> {
  /**
   * Default values, captured as the form's clean baseline when the controller
   * is created. Mutating this object afterwards does not change the baseline.
   */
  defaultValues?: Partial<T>

  /**
   * Externally loaded values, merged over `defaultValues` as the clean
   * baseline. Framework bindings also apply later content changes; use
   * `resetOptions.keepDirtyValues` to preserve edits while pristine fields fill.
   */
  values?: Partial<T>

  /** Controls how framework bindings apply changed `values`. */
  resetOptions?: FormResetOptions

  /**
   * Validation mode.
   */
  mode?: 'onSubmit' | 'onChange' | 'onBlur' | 'all'

  /**
   * Revalidation mode.
   */
  reValidateMode?: 'onChange' | 'onBlur' | 'onSubmit'

  /**
   * Whether to focus the first error field on submit.
   */
  shouldFocusError?: boolean

  /**
   * Form-level validation function.
   */
  validate?: (
    values: T,
  ) => Partial<Record<keyof T, string>> | Promise<Partial<Record<keyof T, string>>>
}

HttpClient

HTTP client interface.

All HTTP providers must implement this interface. An explicit text, blob or arraybuffer parser determines the data type even when a JSON generic is supplied. Keep JSON as the default for mutations returning a record. A successful DELETE with no body already resolves with null data.

Every verb also takes a URL alone, through a signature with the same three parameters on every verb, so a verb chosen at runtime (client[verb](url)) type-checks and a wrapper can implement a verb with an arrow (get: (url, config) => inner.get(url, config)). With a body or a config, choose the verb through request({ method, url, data }) instead: the second argument is the body for post/put/patch but the config for get/delete, so one call cannot serve both.

interface HttpClient {
  /**
   * Base URL for all requests.
   */
  baseURL: string

  /**
   * Default headers for all requests.
   */
  defaultHeaders: Record<string, string>

  /**
   * Makes a generic HTTP request. `data` is a field of THIS config object — the same body
   * `post(url, data, config)` takes as its second argument.
   */
  request<T = unknown>(
    config: FullRequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  request<T = unknown>(
    config: FullRequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  request<T = unknown>(
    config: FullRequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  request<T = unknown>(config: FullRequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a GET request.
   */
  get<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  get<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  get<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  get<T = unknown>(url: string, config?: undefined, unused?: undefined): Promise<HttpResponse<T>>
  get<T = unknown>(url: string, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a POST request. `data` is the request BODY, not a config object: the wire body is
   * `data` itself, so `post(url, { data: body })` sends `{"data":body}` — pass `body` directly.
   * A config (headers, params) is the THIRD argument.
   */
  post<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  post<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  post<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  post<T = unknown>(url: string, data?: undefined, config?: undefined): Promise<HttpResponse<T>>
  post<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a PUT request. `data` is the request BODY (second argument) — never `{ data: body }`,
   * which sends `{"data":body}`; a config is the THIRD argument.
   */
  put<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  put<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  put<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  put<T = unknown>(url: string, data?: undefined, config?: undefined): Promise<HttpResponse<T>>
  put<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a PATCH request. `data` is the request BODY (second argument) — never `{ data: body }`,
   * which sends `{"data":body}`; a config is the THIRD argument.
   */
  patch<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  patch<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  patch<T = unknown>(
    url: string,
    data: unknown,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  patch<T = unknown>(url: string, data?: undefined, config?: undefined): Promise<HttpResponse<T>>
  patch<T = unknown>(url: string, data?: unknown, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Makes a DELETE request.
   */
  delete<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'text' },
  ): Promise<HttpResponse<string>>
  delete<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'blob' },
  ): Promise<HttpResponse<Blob>>
  delete<T = unknown>(
    url: string,
    config: RequestConfig & { responseType: 'arraybuffer' },
  ): Promise<HttpResponse<ArrayBuffer>>
  delete<T = unknown>(url: string, config?: undefined, unused?: undefined): Promise<HttpResponse<T>>
  delete<T = unknown>(url: string, config?: RequestConfig): Promise<HttpResponse<T>>

  /**
   * Adds a request interceptor.
   * Returns a function to remove the interceptor.
   */
  addRequestInterceptor(interceptor: RequestInterceptor): () => void

  /**
   * Adds a response interceptor.
   * Returns a function to remove the interceptor.
   */
  addResponseInterceptor(interceptor: ResponseInterceptor): () => void

  /**
   * Adds an error interceptor.
   * Returns a function to remove the interceptor.
   */
  addErrorInterceptor(interceptor: ErrorInterceptor): () => void

  /**
   * Sets the authorization token.
   *
   * A static token: every request carries it until the next `setAuthToken` call. A client
   * that has a {@link HttpClient.setAuthTokenResolver | resolver} (registered through
   * `@molecule/app-http`'s `setAuthTokenSource`) ignores this value when it assembles a
   * request — the resolver IS the session, and reading it per request is what keeps a
   * session adopted without an auth event from sending the previous account's bearer. Once
   * the resolver is removed, the static token is sent again.
   */
  setAuthToken(token: string | null): void

  /**
   * Returns the token the client applies to its next request: the resolver's answer when one
   * is registered, else the static token from `setAuthToken`.
   */
  getAuthToken(): string | null

  /** Registers the LIVE token resolver every request of this client reads, or clears it with `null`. */
  setAuthTokenResolver?(resolver: AuthTokenResolver | null): void

  /**
   * Registers a handler for authentication errors (401), with the rejected request's metadata.
   *
   * @param handler - Receives the method, URL and credential state of the rejected request.
   * @returns An unsubscribe function.
   */
  onAuthError(handler: (event: HttpAuthErrorEvent) => void): () => void
}

(The longest member comment is shortened to its first sentence to fit; the full declaration is in node_modules/@molecule/app-http/dist/client.d.ts.)

Logger

Logger instance with leveled logging methods, child logger creation, and transport management.

interface Logger {
  /**
   * Logs a trace message.
   */
  trace(message: string, ...args: unknown[]): void

  /**
   * Logs a debug message.
   */
  debug(message: string, ...args: unknown[]): void

  /**
   * Logs an info message.
   */
  info(message: string, ...args: unknown[]): void

  /**
   * Logs a warning message.
   */
  warn(message: string, ...args: unknown[]): void

  /**
   * Logs an error message.
   */
  error(message: string | Error, ...args: unknown[]): void

  /**
   * Sets the log level.
   */
  setLevel(level: LogLevel): void

  /**
   * Gets the current log level.
   */
  getLevel(): LogLevel

  /**
   * Creates a child logger with a namespace.
   */
  child(name: string, context?: Record<string, unknown>): Logger

  /**
   * Adds additional context to the logger.
   */
  withContext(context: Record<string, unknown>): Logger

  /**
   * Adds a transport.
   */
  addTransport(transport: LogTransport): () => void

  /**
   * Removes a transport.
   */
  removeTransport(transport: LogTransport): void
}

RouteLocation

Current URL decomposed into pathname, search string, hash, navigation state, and unique key.

interface RouteLocation {
  /**
   * Current pathname.
   */
  pathname: string

  /**
   * Query string (including leading ?).
   */
  search: string

  /**
   * Hash (including leading #).
   */
  hash: string

  /**
   * State data passed with navigation.
   */
  state?: unknown

  /**
   * Unique key for this location.
   */
  key?: string
}

Router

Client-side router providing navigation, guards, route matching, and history control.

All routing providers must implement this interface.

interface Router {
  /**
   * Returns the current route location (pathname, search, hash, state).
   */
  getLocation(): RouteLocation

  /**
   * Gets the current route params.
   */
  getParams<T extends RouteParams = RouteParams>(): T

  /**
   * Gets the current query params.
   */
  getQuery(): QueryParams

  /**
   * Gets a specific query parameter.
   */
  getQueryParam(key: string): string | undefined

  /**
   * Gets the current hash.
   */
  getHash(): string

  /**
   * Navigates to a path. A path that is only a query or a hash (`'?tab=2'`, `'#top'`) stays on
   * the current page, as React Router's `navigate` does; a hash alone drops the current query.
   */
  navigate(path: string, options?: NavigateOptions): void

  /**
   * Navigates to a named route.
   */
  navigateTo(
    name: string,
    params?: RouteParams,
    query?: QueryParams,
    options?: NavigateOptions,
  ): void

  /**
   * Goes back in history.
   */
  back(): void

  /**
   * Goes forward in history.
   */
  forward(): void

  /**
   * Goes to a specific point in history.
   */
  go(delta: number): void

  /**
   * Updates the current query params.
   */
  setQuery(params: QueryParams, options?: NavigateOptions): void

  /**
   * Updates a specific query parameter.
   */
  setQueryParam(key: string, value: string | undefined, options?: NavigateOptions): void

  /**
   * Updates the current hash.
   */
  setHash(hash: string, options?: NavigateOptions): void

  /**
   * Checks if a path matches the current location.
   *
   * @returns `true` if the path matches the current route.
   */
  isActive(path: string, exact?: boolean): boolean

  /**
   * Matches a path pattern against a pathname.
   */
  matchPath<Params extends RouteParams = RouteParams>(
    pattern: string,
    pathname: string,
  ): RouteMatch<Params> | null

  /**
   * Generates a URL from a named route.
   */
  generatePath(name: string, params?: RouteParams, query?: QueryParams): string

  /**
   * The `href` an anchor to the in-app `path` carries, as the native router's own link
   * writes it (its base path prefixed, or `#/…` under a hash history), so a middle-click,
   * a new tab or a copied link opens the same page a click does. A `path` that is only a
   * query or a hash (`'?tab=2'`, `'#top'`) is the current page's, as `navigate` reads it
   * and as React Router's `<Link>` writes it: `'#top'` on `/docs?x=1` is `/docs#top`.
   *
   * @param path - Pathname with optional query string and hash, as passed to `navigate`.
   * @returns The `href`.
   */
  createHref(path: string): string

  /**
   * Calls `listener` once after each navigation the router commits, however it started (a
   * link, the back button, `navigate`), with the new location and the navigation action.
   * A router calls it before the browser paints the new page, so a component that renders
   * from a listener (the framework bindings' `useLocation` and `useParams` do) shows the new
   * location in the same paint as the new page. Molecule's router conformance tests check
   * that at every paint.
   *
   * @param listener - Called with the new location and the navigation action.
   * @returns Stops calling `listener`.
   */
  subscribe(listener: RouteChangeListener): () => void

  /**
   * Adds a navigation guard.
   */
  addGuard(guard: NavigationGuard): () => void

  /**
   * Registers route definitions.
   */
  registerRoutes(routes: RouteDefinition[]): void

  /**
   * Gets all registered routes.
   */
  getRoutes(): RouteDefinition[]

  /**
   * Destroys the router.
   */
  destroy(): void
}

RouterConfig (deprecated)

Deprecated: Use BrowserRouterConfig (createBrowserRouter) or MemoryRouterConfig (createMemoryRouter): each takes only the options it acts on.

Configuration options for creating a router instance.

interface RouterConfig {
  /**
   * Router mode.
   */
  mode?: 'history' | 'hash' | 'memory'

  /**
   * Base path.
   */
  basePath?: string

  /**
   * Initial routes.
   */
  routes?: RouteDefinition[]
}

StoreConfig

Configuration for creating a store (initial state, optional name, and middleware chain).

interface StoreConfig<T> {
  /**
   * Initial state value.
   */
  initialState: T

  /**
   * Optional name for debugging.
   */
  name?: string

  /**
   * Optional middleware functions.
   */
  middleware?: StoreMiddleware<T>[]
}

MoleculeStore

Reactive state container with getState, setState, subscribe, and destroy.

All state management providers must implement this interface.

interface Store<T> {
  /**
   * Gets the current state.
   */
  getState(): T

  /**
   * Sets the state (partial or via updater function).
   */
  setState(partial: Partial<T> | ((state: T) => Partial<T>)): void

  /**
   * Subscribes to state changes.
   * Returns an unsubscribe function.
   */
  subscribe(listener: StateListener<T>): () => void

  /**
   * Destroys the store and cleans up subscriptions.
   */
  destroy(): void
}

Store

Reactive state container with getState, setState, subscribe, and destroy.

All state management providers must implement this interface.

interface Store<T> {
  /**
   * Gets the current state.
   */
  getState(): T

  /**
   * Sets the state (partial or via updater function).
   */
  setState(partial: Partial<T> | ((state: T) => Partial<T>)): void

  /**
   * Subscribes to state changes.
   * Returns an unsubscribe function.
   */
  subscribe(listener: StateListener<T>): () => void

  /**
   * Destroys the store and cleans up subscriptions.
   */
  destroy(): void
}

Theme

Complete theme definition.

interface Theme {
  name: string
  mode: 'light' | 'dark'
  colors: ThemeColors
  breakpoints: ThemeBreakpoints
  spacing: ThemeSpacing
  typography: ThemeTypography
  borderRadius: ThemeBorderRadius
  shadows: ThemeShadows
  transitions: ThemeTransitions
  zIndex: ThemeZIndex
}

UseAuthOptions

Options for {@link useAuth}.

interface UseAuthOptions {
  /**
   * Whether to automatically refresh the session on mount, and again whenever
   * the flag turns on or the session decision changes while it is on.
   */
  autoRefresh?: boolean
}

UseAuthResult

What {@link useAuth} returns: the session's value fields as readable stores ($status, $user, …) and the client's actions as plain functions.

interface UseAuthResult<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  /**
   * The session state as one value — render from this instead of combining
   * `initialized`/`authenticated`/`loading`. Only `'loading'` means "no
   * decision yet"; redirect on `'unauthenticated'` alone.
   */
  status: Readable<AuthState<T>['status']>
  /** The whole session state. */
  state: Readable<AuthState<T>>
  /** The client's `login`. */
  login: AuthClient<T>['login']
  /** The client's `logout`. */
  logout: AuthClient<T>['logout']
  /** The client's `register` (there is no separate `useRegister`). */
  register: AuthClient<T, TRegister>['register']
  /** The client's `refresh`. */
  refresh: AuthClient<T>['refresh']
  /** Saves through the configured auth transport and publishes the saved user. */
  updateProfile: AuthClient<T>['updateProfile']
  /** Caches a user without signing in. */
  setUser: AuthClient<T>['setUser']
  /**
   * Adopts a session an exchange outside the client already established (an
   * OAuth code→token redirect, the app's own sign-in endpoint) in one update.
   */
  setSession: AuthClient<T>['setSession']
  /** Whether a session is authenticated locally. */
  isAuthenticated: Readable<boolean>
  /** Whether the client is working on a decision. */
  isLoading: Readable<boolean>
  /** The cached profile, which can be null while an unavailable candidate is retained. */
  user: Readable<T | null>
}

UseChangePasswordReturn

What {@link useChangePassword} returns.

interface UseChangePasswordReturn {
  /** The latest call's status. */
  status: Readable<UsePromiseState<void>['status']>
  /** The latest call's rejection. */
  error: Readable<UsePromiseState<void>['error']>
  /** Runs the password change. */
  changePassword: (oldPassword: string, newPassword: string) => Promise<void>
  /** Returns the tracker to idle. */
  reset: () => void
}

UseDeviceResult

Hook return type.

interface UseDeviceResult {
  /** The parsed device identity. */
  deviceInfo: DeviceInfo
  /** The screen dimensions and mode. */
  screenInfo: ScreenInfo
  /** The hardware capabilities. */
  hardwareInfo: HardwareInfo
  /** The feature flags. */
  featureSupport: FeatureSupport
  /** Whether a feature is supported. */
  supports: (feature: keyof FeatureSupport) => boolean
  /** Whether the device is online. */
  isOnline: () => boolean
  /** Whether the app runs standalone. */
  isStandalone: () => boolean
  /** The preferred language. */
  language: string
  /** The preferred languages, best first. */
  languages: string[]
}

UseEditorResult

Hook result for useEditor: the tab state as readable stores and the editor actions as plain functions.

interface UseEditorResult {
  /** The provider's open tabs. */
  tabs: Readable<EditorTab[]>
  /** The path of the tab marked active, or null when none is. */
  activeFile: Readable<string | null>
  /** Opens a file in a tab and activates it. */
  openFile: (file: EditorFile) => void
  /** Closes a tab. */
  closeFile: (path: string) => void
  /** The active tab's content. */
  getContent: () => string | null
  /** Writes a tab's content. */
  setContent: (path: string, content: string) => void
  /** Activates the tab with the given path. */
  setActiveTab: (path: string) => void
  /** Mounts the editor into an element. */
  mount: EditorProvider['mount']
  /** Disposes the editor. */
  dispose: () => void
  /** Focuses the editor. */
  focus: () => void
  /** Opens a diff tab (provider optional method). */
  openDiff: (file: DiffFile) => void
  /** Closes the diff tab (provider optional method). */
  closeDiff: () => void
  /** Converts a preview tab into a normal one (provider optional method). */
  pinTab: (path: string) => void
  /** Adds an extra type library (provider optional method). */
  addExtraLib: (content: string, filePath: string) => void
  /** Subscribes a Fix-with-AI request listener; returns its unsubscribe. */
  onFixWithAI: (callback: (request: FixWithAIRequest) => void) => () => void
}

UseFormOptions

Options for useForm hook.

Every FormOptions field is supported. createForm is only an override — omit it and the hook creates the controller through the bonded forms provider (createForm from @molecule/app-forms), which uses the built-in native provider until the app bonds its own.

interface UseFormOptions<T extends FormValuesConstraint<T>> extends FormOptions<T> {
  /** External values preserve dirty fields by default. Set keepDirtyValues: false to replace them explicitly. */
  resetOptions?: FormResetOptions
  /** New record identity. Serialize composite keys; fresh objects/arrays must not reset drafts on each mount. */
  resetKey?: string | number | boolean | bigint | null
  /**
   * Explicit form factory for this one form. Defaults to the bonded forms
   * provider; pass it only to pin a specific provider instance.
   */
  createForm?: (options: FormOptions<T>) => FormController<T>
}

UseFormResult

Result of useForm hook: the state fields as readable stores, the methods as plain functions.

interface UseFormResult<T extends FormValuesConstraint<T>> {
  /** The whole form state. */
  formState: Readable<FormState<T>>
  /** Whether every field passes validation. */
  isValid: Readable<boolean>
  /** Whether any field differs from the baseline. */
  isDirty: Readable<boolean>
  /** Whether a submit is running. */
  isSubmitting: Readable<boolean>

  /** Registers a field; returns its native bindings. */
  register: (
    name: keyof T,
    options?: Omit<RegisterOptions, 'name'> & { name?: string },
  ) => FieldRegistration
  /** Reads one field's value. */
  getValue: <K extends keyof T>(name: K) => T[K]
  /** Writes one field's value (marks it touched and dirty). */
  setValue: <K extends keyof T>(name: K, value: T[K]) => void
  /** Reads one field's error. */
  getError: (name: keyof T) => string | undefined
  /** Sets or clears one field's error. */
  setError: (name: keyof T, error: string | undefined) => void
  /** Clears every field error. */
  clearErrors: () => void

  /** Validates and runs the handler; returns the submit runner. */
  handleSubmit: (
    onSubmit: (values: T) => void | Promise<void>,
    onError?: (errors: Partial<Record<keyof T, string>>) => void,
  ) => (event?: { preventDefault?: () => void }) => Promise<void>
  /** Restores the baseline (optionally a new one) and clears touched, errors and submit state. */
  reset: (values?: Partial<T>) => void
  /** Applies externally loaded values without clearing submission state. */
  updateValues: (values: Partial<T>, resetOptions?: FormUpdateOptions) => void
  /** Whole-form state tuple: edits mark only changed fields dirty; fills preserve them. */
  asState(): readonly [
    T,
    (value: T | ((previous: T) => T)) => void,
    (value: Partial<T> | ((previous: T) => Partial<T>)) => void,
  ]
  /** One field as [value, edit, fill]. Fill preserves edits made before data arrives. */
  asState<K extends keyof T>(
    name: K,
  ): readonly [
    T[K],
    (value: T[K] | ((previous: T[K]) => T[K])) => void,
    (value: T[K] | ((previous: T[K]) => T[K])) => void,
  ]
  /** Runs every registered rule and publishes field errors. */
  validate: () => Promise<boolean>
}

UseHttpState

State for async HTTP operations.

interface UseHttpState<T> {
  data: T | null
  loading: boolean
  error: Error | null
}

UseHttpResult

What {@link useHttp} returns: the state fields as stores plus execute and reset.

interface UseHttpResult<T> {
  /** The newest request's data, or null. */
  data: Readable<T | null>
  /** Whether a request is in flight. */
  loading: Readable<boolean>
  /** The newest request's failure. */
  error: Readable<Error | null>
  /**
   * Runs the request and resolves with its own data, or `null` on failure,
   * even when a newer request or `reset` has superseded its displayed state.
   *
   * This function keeps ONE identity for the component's life, so it is safe
   * wherever a stable function matters. Its request options are read when it
   * is CALLED.
   */
  execute: () => Promise<T | null>
  /** Clears the state and supersedes any in-flight request. */
  reset: () => void
}

UseHttpOptions

Options for the {@link useHttp} hooks.

Every request option — headers, params, body data, signal, onSuccess, onError — is read at the moment execute runs, not when the hook was called. Only immediate is read on mount.

interface UseHttpOptions<T> extends RequestConfig {
  /** Whether to execute the request immediately on mount. */
  immediate?: boolean
  /**
   * Callback for each request that succeeds while mounted, including a request
   * superseded by another `execute` or `reset`. Read `data` from the hook when
   * only the newest request's result should drive the UI.
   */
  onSuccess?: (data: T) => void
  /** Callback for each request that fails while mounted, including a superseded one. */
  onError?: (error: Error) => void
}

UseLoginReturn

What {@link useLogin} returns: the promise state's value fields as stores plus the action.

interface UseLoginReturn<T = unknown> {
  /** The latest call's status. */
  status: Readable<UsePromiseState<AuthResult<T>>['status']>
  /** The latest call's resolved value. */
  value: Readable<UsePromiseState<AuthResult<T>>['value']>
  /** The latest call's rejection. */
  error: Readable<UsePromiseState<AuthResult<T>>['error']>
  /** Runs the login. */
  login: (credentials: LoginCredentials) => Promise<AuthResult<T>>
  /** Returns the tracker to idle. */
  reset: () => void
}

UseOAuthReturn

Return type for useOAuth hook.

interface UseOAuthReturn {
  /**
   * The configured provider names (React's `string[]`), read live: each read
   * returns the list the current config holds, and a read in markup or
   * `$derived` re-runs when a config store changes. Read it off the result
   * (`oauth.providers`); a destructured copy keeps the list of the moment it
   * was taken.
   */
  readonly providers: string[]
  /** Builds the provider's initiation URL (provider encoded as one path segment). */
  getOAuthUrl: (provider: string) => string
  /** Full-page redirect to the provider (default). The opener page navigates away. */
  redirect: (provider: string) => void
  /**
   * Open the provider in a popup so the opener page does NOT navigate. On success
   * the session is established in the opener in place and `config.onSuccess` fires;
   * on failure `config.onError` fires. Falls back to a full-page {@link redirect}
   * when the popup is blocked.
   */
  loginViaPopup: (provider: string) => void
}

UseOAuthConfig

OAuth configuration override options.

interface UseOAuthConfig {
  /** Base URL for the API server (e.g. "https://api.example.com"). */
  baseURL?: string
  /** List of supported OAuth provider names (e.g. ["google", "github"]). */
  oauthProviders?: string[]
  /** Path prefix for OAuth routes (defaults to "/oauth"). */
  oauthEndpoint?: string
  /** Path for the OAuth login POST endpoint (defaults to "/users/log-in/oauth"). */
  loginEndpoint?: string
  /** Callback after successful OAuth login. */
  onSuccess?: () => void
  /** Callback on OAuth login failure. */
  onError?: (error: string) => void
  /**
   * How the page leaves for the provider: {@link UseOAuthReturn.redirect} and the
   * blocked-popup fallback call it with the provider URL. Defaults to a full-page
   * navigation (`window.location.href = url`); pass an in-app browser opener on
   * native, or a router's external navigation.
   */
  navigate?: (url: string) => void
}

UseOptimisticToggleOptions

Options for {@link useOptimisticToggle}.

interface UseOptimisticToggleOptions {
  /** The loaded server value. Mount the control only after its record exists. */
  value: boolean
  /** Saves the DESIRED value and returns the server-confirmed value; reject on failure. */
  commit: (desired: boolean) => Promise<boolean>
  /** Receives the newest failed save and the confirmed value restored by the controller. */
  onError?: (error: unknown, value: boolean) => void
}

UseOptimisticToggleResult

What {@link useOptimisticToggle} returns: the boolean to render as readable stores and an argument-free action (the same names React returns).

interface UseOptimisticToggleResult {
  /** The value to render. */
  value: Readable<boolean>
  /** Whether a save is running or waiting. */
  pending: Readable<boolean>
  /** The failure of the newest change. */
  error: Readable<unknown>
  /** Flips the value shown now and saves it; the same function for the component's life. */
  toggle: () => void
}

UseOptimisticValueResult

What {@link useOptimisticValue} returns: the state to render as readable stores and the two ways to change it (the same names React returns).

interface UseOptimisticValueResult<T> {
  /** The value to render. */
  value: Readable<T>
  /** Whether a save is running or waiting. */
  pending: Readable<boolean>
  /** The failure of the newest change. */
  error: Readable<unknown>
  /** Shows `next` at once and saves it, after any save already running. */
  set: (next: T) => void
  /** Like `set`, computed from the value shown now (`update((on) => !on)`). */
  update: (change: (current: T) => T) => void
}

UsePasswordResetReturn

What {@link usePasswordReset} returns: two independent trackers plus a combined reset.

interface UsePasswordResetReturn {
  /** The request step's status. */
  requestStatus: Readable<UsePromiseState<void>['status']>
  /** The request step's rejection. */
  requestError: Readable<UsePromiseState<void>['error']>
  /** The confirm step's status. */
  confirmStatus: Readable<UsePromiseState<void>['status']>
  /** The confirm step's rejection. */
  confirmError: Readable<UsePromiseState<void>['error']>
  /** Sends the reset email (step 1). */
  requestReset: (data: PasswordResetRequest) => Promise<void>
  /** Sets the new password (step 2). */
  confirmReset: (data: PasswordResetConfirm) => Promise<void>
  /** Returns BOTH trackers to idle. */
  reset: () => void
}

UsePlatformResult

Hook return type.

interface UsePlatformResult {
  /** The detected platform. */
  platform: Platform
  /** Whether the app runs in a native shell. */
  isNative: boolean
  /** Whether the platform is a phone or tablet. */
  isMobile: boolean
  /** Whether the platform is a desktop. */
  isDesktop: boolean
  /** Whether the platform is the web. */
  isWeb: boolean
  /** Whether the app runs in development. */
  isDevelopment: boolean
  /** Whether the app runs in production. */
  isProduction: boolean
  /** Whether the current platform is one of the candidates. */
  isPlatform: (...platforms: Platform[]) => boolean
}

UsePreviewResult

Hook result for usePreview: the preview state as a readable store and the controls as plain functions.

interface UsePreviewResult {
  /** The preview's full state (url, currentUrl, isLoading, device, error, isConnected, canGoBack, canGoForward, loadNonce). */
  state: Readable<PreviewState>
  /** Loads a url. */
  setUrl: (url: string) => void
  /** Reloads the current document. */
  refresh: () => void
  /** Switches the device frame. */
  setDevice: (device: DeviceFrame) => void
  /** Opens the current url outside the app. */
  openExternal: () => void
  /**
   * Records a navigation the running preview reported via its `molecule:navigate`
   * message — updates the displayed current location without reloading the iframe.
   * Pass `isReplace` when the preview REPLACED its current history entry (a
   * `replaceState` redirect/canonicalization) so the forward stack is preserved
   * instead of truncated (a `pushState`, the default, truncates forward).
   */
  recordNavigation: (url: string, isReplace?: boolean) => void
  /** Navigates the preview to the previous navigation-history entry (Back). */
  back: () => void
  /** Navigates the preview to the next navigation-history entry (Forward). */
  forward: () => void
}

UseProfileFormOptions

Configuration for a profile form; transport stays in the auth bond.

TValues is the page's own controlled-values type, named once as an interface or a type alias — both satisfy the shared form-values constraint.

interface UseProfileFormOptions<TUser, TValues extends FormValuesConstraint<TValues>> extends Omit<
  UseFormOptions<TValues>,
  'defaultValues'
> {
  /** Complete controlled-field defaults, including blank write-only fields. */
  defaultValues: TValues
  /**
   * Optional additional account identity check; changing it discards prior edits.
   * By default ownership follows the auth client's session revision, so editable
   * fields can change during a save. Providers without getSessionRevision must
   * supply this callback with an identity that remains stable across profile edits.
   */
  getIdentity?: (user: TUser) => string
  /** Maps the current/saved user into controlled values, e.g. nullable text to ''. */
  toValues: (user: TUser) => TValues
  /**
   * Maps ONLY changed fields into an API patch. Omit blank optional credentials
   * here; preserve undefined/absent fields rather than turning them into null.
   * The second argument is the complete value snapshot taken at submit time.
   */
  toPatch: (changes: Partial<TValues>, values: Readonly<TValues>) => Partial<TUser>
  /**
   * Propagates the server's saved user to other caches, then navigates if needed.
   * Awaited before submission finishes. The auth client already persists and
   * publishes the saved user; never seed caches from the submitted patch.
   */
  onSaved?: (user: TUser) => void | Promise<void>
}

UseProfileFormResult

Controlled profile form state and native form bindings.

interface UseProfileFormResult<TUser, TValues extends FormValuesConstraint<TValues>> extends Omit<
  UseFormResult<TValues>,
  'register' | 'handleSubmit' | 'reset'
> {
  /** The shared auth user's current profile, as a readable store. */
  user: Readable<TUser | null>
  /** A user has been loaded; disable submission until this is true. */
  ready: Readable<boolean>
  /**
   * The latest save/propagation failure. Rejected saves retain edits; a failed
   * onSaved callback can be retried by submit without repeating the mutation.
   */
  error: Readable<unknown>
  /** Native input/textarea bindings with the field's concrete value type. */
  register: <K extends keyof TValues>(
    name: K,
    options?: Parameters<UseFormResult<TValues>['register']>[1],
  ) => Omit<FieldRegistration, 'value'> & { value: TValues[K] }
  /** Bind to the native form, with a type="submit" button inside it. */
  formProps: { onSubmit: (event: { preventDefault: () => void }) => void }
  /**
   * Validates and saves one submit-time snapshot. Concurrent submits share the
   * same promise. Resolves undefined on validation, save or propagation failure.
   */
  submit: () => Promise<TUser | undefined>
  /** Discards edits and restores the newest loaded/saved profile baseline. */
  reset: () => void
}

UsePromiseState

Extended promise state with actions, React's UsePromiseState.

interface UsePromiseState<T> {
  status: PromiseStatus
  value: T | null
  error: Error | null
  cancel: (message?: string) => void
  reset: () => void
}

UseRouterResult

What {@link useRouter} returns.

interface UseRouterResult {
  /** The current location. */
  location: Readable<RouteLocation>
  /** The current route's path parameters. */
  params: Readable<Record<string, string>>
  /** The current query parameters. */
  query: Readable<QueryParams>
  /** Navigates to a path. */
  navigate: Router['navigate']
  /** Navigates to a named route. */
  navigateTo: Router['navigateTo']
  /** Goes back one history entry. */
  back: Router['back']
  /** Goes forward one history entry. */
  forward: Router['forward']
  /** Whether a path is active (prefix, or exact with `exact`). */
  isActive: Router['isActive']
}

UseListRouteResult

What {@link useListRoute} returns: each list field as a readable store, the actions as plain functions.

interface UseListRouteResult<Filter extends string = string, Selection extends string = string> {
  /** The current 1-indexed page. */
  page: Readable<number>
  /** The configured items per page. */
  pageSize: Readable<number>
  /** The zero-indexed item offset for an API request. */
  offset: Readable<number>
  /** The current URL filter values, including values supplied by path parameters. */
  filters: Readable<Record<Filter, string | undefined>>
  /** The matching view, or the configured fallback. */
  selection: Readable<Selection | undefined>
  /** The decoded current path parameters, also usable as API-only filters. */
  params: Readable<RouteParams>
  /** False while a protected selection is awaiting auth, signed out, or unavailable. */
  canLoad: Readable<boolean>
  /** Readiness for the current view; a public view always stays ready. */
  status: Readable<ListRouteResult<Filter, Selection>['status']>
  /** The sign-in destination while a signed-out protected view is being redirected. */
  redirectTo: Readable<string | undefined>
  /** Builds a real link target, preserving the pathname, unrelated query values and hash. */
  href: ListRouteResult<Filter, Selection>['href']
  /** Navigates atomically; location state is preserved unless options replace it. */
  navigate: ListRouteResult<Filter, Selection>['navigate']
  /** Changes only the page, retaining the current filters and view. */
  setPage: ListRouteResult<Filter, Selection>['setPage']
  /** Patches URL filters and returns to page one. */
  setFilters: ListRouteResult<Filter, Selection>['setFilters']
  /** Selects a configured view at page one. */
  select: ListRouteResult<Filter, Selection>['select']
}

UseSignupReturn

What {@link useSignup} returns.

interface UseSignupReturn<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  /** The latest call's status. */
  status: Readable<UsePromiseState<AuthResult<T>>['status']>
  /** The latest call's resolved value. */
  value: Readable<UsePromiseState<AuthResult<T>>['value']>
  /** The latest call's rejection. */
  error: Readable<UsePromiseState<AuthResult<T>>['error']>
  /** Runs the signup. */
  signup: (data: RegisterData<TRegister>) => Promise<AuthResult<T>>
  /** Returns the tracker to idle. */
  reset: () => void
}

UseStorageValueOptions

Options for {@link useStorageValue}.

interface UseStorageValueOptions<T> {
  /**
   * Default value if key doesn't exist.
   */
  defaultValue?: T
  /**
   * Whether to sync across tabs/windows (if supported by storage provider).
   */
  sync?: boolean
}

UseStorageValueResult

Result of {@link useStorageValue}.

interface UseStorageValueResult<T> {
  /** The stored value, or the default while none is stored. */
  value: Readable<T | undefined>
  /** Persists the value; rejects when the provider refuses the write. */
  setValue: (value: T) => Promise<void>
  /** Removes the key and falls back to the default; rejects on failure. */
  removeValue: () => Promise<void>
  /** Whether the first read is still in flight. */
  loading: Readable<boolean>
  /** The failing read's or write's error. */
  error: Readable<Error | null>
}

UseStoragePreferenceOptions

Options for {@link useStoragePreference}.

interface UseStoragePreferenceOptions<T> {
  /**
   * Value reported until the provider supplies one. It is NEVER written to
   * storage: a default is a display fallback, not a decision the user made.
   */
  defaultValue?: T
}

UseStoragePreferenceResult

Result of {@link useStoragePreference}.

interface UseStoragePreferenceResult<T> {
  /** The persisted value, or `defaultValue` while none is known. */
  value: Readable<T | undefined>
  /**
   * Writes the value through the preference store: subscribers update
   * immediately and persistence is best-effort.
   */
  setValue: (next: T | ((previous: T | undefined) => T)) => void
  /** Removes the key through the preference store. */
  removeValue: () => void
  /**
   * `true` once the store has a definite answer — the synchronous snapshot on
   * a synchronous provider, or the hydration result on an asynchronous one.
   */
  ready: Readable<boolean>
}

UseStoreOptions

Options for {@link useStore}.

interface UseStoreOptions<T, S> {
  /** Selects part of the state. */
  selector?: (state: T) => S
  /** Compares two selected values; equal keeps the previous result. */
  equalityFn?: (a: S, b: S) => boolean
}

SelectingStoreOptions

Options for {@link useStore} that pick part of the store: a selector is required, so the selected type S always comes from it.

interface SelectingStoreOptions<T, S> extends UseStoreOptions<T, S> {
  /** Picks the value the hook returns from the store's state. */
  selector: (state: T) => S
}

UseThemeResult

What {@link useTheme} returns.

interface UseThemeResult {
  /** The current theme object. */
  theme: Readable<Theme>
  /** The current theme's name. */
  themeName: Readable<string>
  /** Switches the active theme by name. */
  setTheme: (name: string) => void
  /** Toggles light/dark (the provider's `toggleMode`, or an index cycle). */
  toggleTheme: () => void
  /** The current mode: 'light' or 'dark'. */
  mode: Readable<'light' | 'dark'>
}

UseTranslationResult

What {@link useTranslation} returns: the locale-reactive values as readable stores and the provider's functions as plain functions.

interface UseTranslationResult {
  /**
   * Translates a key in the active locale. A call made while markup, `$derived` or an
   * effect evaluates re-runs on every locale switch (like React's `t`, which is
   * rebuilt on every locale change), so `{t('key', {}, { defaultValue })}` needs no
   * store read beside it.
   */
  t: I18nProvider['t']
  /** The active locale code. */
  locale: Readable<string>
  /** Switches the active locale. */
  setLocale: I18nProvider['setLocale']
  /** The registered locales. */
  locales: Readable<ReturnType<I18nProvider['getLocales']>>
  /** Formats a number for the active locale. */
  formatNumber: I18nProvider['formatNumber']
  /** Formats a date for the active locale. */
  formatDate: I18nProvider['formatDate']
  /** The active locale's text direction. */
  direction: Readable<'ltr' | 'rtl'>
}

UseVerifyPaymentReturnOptions

Options for {@link useVerifyPaymentReturn}.

interface UseVerifyPaymentReturnOptions {
  /**
   * Provider name to verify with, when the return URL carries no `provider`
   * query parameter. Leave unset to verify only what the URL names.
   */
  provider?: string

  /** Set `false` to skip verification entirely (e.g. behind a feature flag). */
  enabled?: boolean

  /**
   * Remove the provider's query parameters from the address bar once the
   * purchase is verified, so a reload (or a shared link) cannot replay the
   * verification. Defaults to `true`.
   */
  cleanUrl?: boolean

  /** Called once, after the purchase verifies. */
  onVerified?: () => void

  /** Called when verification fails. */
  onError?: (error: Error) => void
}

UseVerifyPaymentReturnResult

State of the post-checkout verification.

interface UseVerifyPaymentReturnResult {
  /**
   * `idle` when this page load is not a checkout return (no transaction id in
   * the URL) or auth is still hydrating; `verifying` while the API call is in
   * flight; then `verified` or `failed`.
   */
  status: Readable<VerifyPaymentReturnStatus>

  /** `true` when the URL identifies a purchase to verify. */
  isReturn: Readable<boolean>

  /** The provider named by the URL (or the `provider` option). */
  provider: Readable<string | null>

  /** The provider transaction/session id read from the URL. */
  transactionId: Readable<string | null>

  /** Why verification failed, when it did. */
  error: Readable<Error | null>

  /** Re-run the verification — wire this to a retry button. */
  retry: () => void
}

UseVersionResult

Hook return type.

interface UseVersionResult {
  /** The provider's full state. */
  state: Readable<VersionState>
  /** Whether an update is available. */
  isUpdateAvailable: Readable<boolean>
  /** Whether a check is running. */
  isChecking: Readable<boolean>
  /** Whether a service worker waits to activate. */
  isServiceWorkerWaiting: Readable<boolean>
  /** The version an available update reports. */
  newVersion: Readable<string | undefined>
  /** Checks the provider for an update. */
  checkForUpdates: () => Promise<boolean>
  /** Applies an available update. */
  applyUpdate: (options?: { force?: b