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-vue

v4.0.2

Published

Vue framework bindings for molecule.dev

Readme

@molecule/app-vue

Vue framework bindings for molecule.dev.

Provides Vue composables and an app plugin for all molecule core interfaces: install moleculePlugin with your providers, then consume them in components via useAuth, useTheme, useTranslation, useStore, and the other composables.

Render session-dependent UI from the three-way status, never a boolean signed-out branch: status === 'loading' is undecided, redirect only on status === 'unauthenticated', and 'unavailable' keeps a session candidate for retry — a restore failure other than 401/403 never signs out.

Component tests: list @molecule/app-vue/testing/setup in vitest's setupFiles. A test's events then land after the render they follow, as a user's do: Vue skips a listener attached in the millisecond an event was first handled, so without it a test whose container and item both listen passes in one run and fails in the next. It also fails a test when the component fires an event itself (focus(), dispatchEvent()) into a listener mounted in the same task, which a browser can skip too.

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

import { createApp, defineComponent, h } from 'vue'
import { Link, moleculePlugin, useAuth, useTheme } from '@molecule/app-vue'
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'

const Dashboard = defineComponent({
  setup() {
    // Composables are inject()-based: call them here in setup(), nowhere else.
    const { user, isAuthenticated, logout } = useAuth<{ name?: string }>()
    const { theme, toggleTheme } = useTheme()
    return () =>
      isAuthenticated.value
        ? h('div', { style: { background: theme.value.colors.background } }, [
            h('h1', `Welcome, ${user.value?.name ?? ''}!`),
            h('button', { onClick: toggleTheme }, 'Toggle theme'),
            h('button', { onClick: () => logout() }, 'Log out'),
          ])
        : h(Link, { to: '/login' }, () => 'Log in')
  },
})

const app = createApp(Dashboard)
app.use(moleculePlugin, {
  state: stateProvider,
  auth: createJWTAuthClient({ baseURL: '/api' }),
  theme: themeProvider,
})
app.mount('#app')
import { defineComponent, h, type PropType } from 'vue'
import { useHttpClient, useOptimisticValue, useTranslation } from '@molecule/app-vue'

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

const FavoriteButton = defineComponent({
  props: {
    article: { type: Object as PropType<FavoriteRecord>, required: true },
    onChanged: {
      type: Function as PropType<(saved: FavoriteRecord) => void>,
      default: undefined,
    },
  },
  setup(props) {
    const http = useHttpClient()
    const { t } = useTranslation()
    const favorite = useOptimisticValue({
      value: { favorited: props.article.favorited, count: props.article.favoritesCount },
      commit: async (next) => {
        const path = `/articles/${props.article.slug}/favorite`
        const response = next.favorited
          ? await http.post<{ article: FavoriteRecord }>(path)
          : await http.delete<{ article: FavoriteRecord }>(path)
        const saved = response.data.article
        props.onChanged?.(saved)
        return { favorited: saved.favorited, count: saved.favoritesCount }
      },
    })
    return () =>
      h(
        'button',
        {
          'aria-pressed': favorite.value.value.favorited,
          'aria-label': t('article.favorite', undefined, { defaultValue: 'Favorite article' }),
          onClick: () =>
            favorite.update((current) => ({
              favorited: !current.favorited,
              count: current.count + (current.favorited ? -1 : 1),
            })),
        },
        String(favorite.value.value.count),
      )
  },
})

const FavoriteControl = defineComponent({
  props: {
    article: { type: Object as PropType<FavoriteRecord | null>, default: null },
  },
  setup(props) {
    return () =>
      props.article ? h(FavoriteButton, { key: props.article.slug, article: props.article }) : null
  },
})

Type

framework

Installation

npm install @molecule/app-vue @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 vue

API

Interfaces

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.)

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>[]
}

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
}

UseCapacitorAppResult

Return type for the useCapacitorApp composable.

interface UseCapacitorAppResult {
  ready: ComputedRef<boolean>
  deviceReady: ComputedRef<boolean>
  pushReady: ComputedRef<boolean>
  error: ComputedRef<Error | null>
  initialize: () => Promise<void>
}

UseChangePasswordReturn

Return type for the {@link useChangePassword} composable.

interface UseChangePasswordReturn {
  status: ComputedRef<PromiseStatus>
  error: ComputedRef<Error | null>
  changePassword: (oldPassword: string, newPassword: string) => Promise<void>
  reset: () => void
}

UseDeviceResult

Return type for the useDevice composable.

interface UseDeviceResult {
  deviceInfo: DeviceInfo
  screenInfo: ScreenInfo
  hardwareInfo: HardwareInfo
  featureSupport: FeatureSupport
  supports: (feature: keyof FeatureSupport) => boolean
  isOnline: () => boolean
  isStandalone: () => boolean
  language: string
  languages: string[]
}

UseFormOptions

Options for useForm composable.

Every FormOptions field is supported. createForm is only an override — omit it and the composable 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

Return type for useForm composable.

interface UseFormResult<T extends FormValuesConstraint<T>> {
  // State
  formState: ComputedRef<FormState<T>>
  isValid: ComputedRef<boolean>
  isDirty: ComputedRef<boolean>
  isSubmitting: ComputedRef<boolean>

  // Field methods
  register: (
    name: keyof T,
    options?: Omit<RegisterOptions, 'name'> & { name?: string },
  ) => FieldRegistration
  getValue: <K extends keyof T>(name: K) => T[K]
  setValue: <K extends keyof T>(name: K, value: T[K]) => void
  getError: (name: keyof T) => string | undefined
  setError: (name: keyof T, error: string | undefined) => void
  clearErrors: () => void

  // Form methods
  handleSubmit: (
    onSubmit: (values: T) => void | Promise<void>,
    onError?: (errors: Partial<Record<keyof T, string>>) => void,
  ) => (event?: { preventDefault?: () => void }) => Promise<void>
  reset: (values?: Partial<T>) => void
  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,
  ]
  validate: () => Promise<boolean>

  // Form controller (for use with useWatch/useFieldState); follows a resetKey
  // change to the fresh controller.
  form: FormController<T>
}

UseLoginReturn

Return type for the {@link useLogin} composable.

interface UseLoginReturn<T = unknown> {
  status: ComputedRef<PromiseStatus>
  value: ComputedRef<AuthResult<T> | null>
  error: ComputedRef<Error | null>
  login: (credentials: LoginCredentials) => Promise<AuthResult<T>>
  reset: () => void
}

OAuthSessionClient

The auth-client surface {@link useOAuth} needs to establish a session after the callback exchange: seed the token, seed the user, then let the client's own initialize() flip authenticated. A full AuthClient satisfies it.

interface OAuthSessionClient {
  /** Stores the exchanged bearer token. */
  setAccessToken(token: string): void
  /** Stores the exchanged user. */
  setUser(user: unknown): void
  /** Settles the client's session state after the seeds above. */
  initialize(): Promise<void>
}

UseOAuthOptions

OAuth configuration options. {@link UseOAuthConfig} is the same type under the name every framework binding uses.

interface UseOAuthOptions {
  /** 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 initiation routes. Defaults to `/oauth`. */
  oauthEndpoint?: string
  /** Path for the OAuth login POST endpoint. Defaults to `/users/log-in/oauth`. */
  loginEndpoint?: string
  /** Callback fired after a successful OAuth login. */
  onSuccess?: () => void
  /** Callback fired with an error message when the OAuth login fails. */
  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
  /**
   * Explicit auth client used to establish the session after the callback
   * exchange. Defaults to the injected client ({@link AuthKey}) when the
   * composable runs during component setup — pass one explicitly for
   * callers/tests outside an auth provider.
   */
  authClient?: OAuthSessionClient
}

UseOAuthReturn

Return type for the {@link useOAuth} composable.

interface UseOAuthReturn {
  /** Available OAuth provider names. */
  providers: ComputedRef<string[]>
  /** Builds the OAuth initiation URL for a provider. */
  getOAuthUrl: (provider: string) => string
  /** Full-page redirect to the provider's OAuth initiation endpoint. */
  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 `onSuccess` fires;
   * on failure `onError` fires. Falls back to a full-page {@link redirect}
   * when the popup is blocked.
   */
  loginViaPopup: (provider: string) => void
  /**
   * Handles an OAuth callback: when the current URL carries a `code` param and
   * a provider was stashed by {@link redirect}, exchanges the code for a
   * session. A guarded no-op otherwise. Runs automatically on mount when the
   * composable is used inside a component; exposed for manual invocation
   * outside components (e.g. tests or custom callback screens).
   */
  handleCallback: () => Promise<void>
}

UsePasswordResetReturn

Return type for usePasswordReset composable.

interface UsePasswordResetReturn {
  requestStatus: ComputedRef<PromiseStatus>
  requestError: ComputedRef<Error | null>
  confirmStatus: ComputedRef<PromiseStatus>
  confirmError: ComputedRef<Error | null>
  requestReset: (data: PasswordResetRequest) => Promise<void>
  confirmReset: (data: PasswordResetConfirm) => Promise<void>
  reset: () => void
}

UsePlatformResult

Return type for the usePlatform composable.

interface UsePlatformResult {
  platform: Platform
  isNative: boolean
  isMobile: boolean
  isDesktop: boolean
  isWeb: boolean
  isDevelopment: boolean
  isProduction: boolean
  isPlatform: (...platforms: Platform[]) => boolean
}

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' | 'formState'
> {
  /** The shared auth user's current profile. */
  user: Ref<TUser | null>
  /** A user has been loaded; disable submission until this is true. */
  ready: Ref<boolean>
  /**
   * The latest save/propagation failure. Rejected saves retain edits; a failed
   * onSaved callback can be retried by submit without repeating the mutation.
   */
  error: Ref<unknown>
  /** The form state with the save-in-progress flag merged into isSubmitting. */
  formState: UseFormResult<TValues>['formState']
  /** 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

The state of the latest tracked call, as the tuple's first element reads it.

interface UsePromiseState<T> {
  /** Current status of the async operation. */
  status: PromiseStatus
  /** Resolved value, or null if not resolved. */
  value: T | null
  /** Rejection error, or null if not rejected. */
  error: Error | null
  /** Cancels the tracked call. */
  cancel: (message?: string) => void
  /** Resets to idle. */
  reset: () => void
}

UseSignupReturn

Return type for useSignup composable.

interface UseSignupReturn<T = unknown> {
  status: ComputedRef<PromiseStatus>
  value: ComputedRef<AuthResult<T> | null>
  error: ComputedRef<Error | null>
  signup: (data: RegisterData) => Promise<AuthResult<T>>
  reset: () => void
}

Returns: The result.

UseStorageValueOptions

Options for useStorageValue composable.

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
}

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: Ref<VerifyPaymentReturnStatus>

  /**
   * `true` while the URL identifies a purchase to verify. React re-reads the
   * URL on every render, so after a verified purchase cleans the address bar
   * this reads `false` again.
   */
  isReturn: ComputedRef<boolean>

  /** The provider named by the URL (or the `provider` option); `null` once the URL is clean. */
  provider: ComputedRef<string | null>

  /** The provider transaction/session id read from the URL; `null` once the URL is clean. */
  transactionId: ComputedRef<string | null>

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

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

UseVersionResult

Return type for the useVersion composable.

interface UseVersionResult {
  state: ComputedRef<VersionState>
  isUpdateAvailable: ComputedRef<boolean>
  isChecking: ComputedRef<boolean>
  isServiceWorkerWaiting: ComputedRef<boolean>
  newVersion: ComputedRef<string | undefined>
  checkForUpdates: () => Promise<boolean>
  applyUpdate: (options?: { force?: boolean }) => void
  dismissUpdate: () => void
  startPeriodicChecks: (options?: UpdateCheckOptions) => void
  stopPeriodicChecks: () => void
}

LinkProps

Props for {@link Link}. Every other attribute (class, target, rel, aria-*, onClick) goes on the anchor.

interface LinkProps {
  /**
   * Destination: an app path (`/settings?tab=billing#plan`) or a URL. An app path's `href` is the
   * one the router writes for it (`routerLinkHref`), base path included; a URL's is the URL as
   * written.
   */
  to: string
  /**
   * Replace the current history entry instead of pushing one. When omitted, a
   * link to the location already shown replaces it and any other link pushes,
   * as with react-router's `<Link>`.
   */
  replace?: boolean
  /** State stored with the new history entry (read back with `useLocation()`). */
  state?: unknown
}

MoleculePluginOptions

Options for the molecule Vue plugin.

interface MoleculePluginOptions {
  state?: StateProvider
  auth?: AuthClient<unknown>
  theme?: ThemeProvider
  router?: Router
  i18n?: I18nProvider
  http?: HttpClient
  storage?: StorageProvider
  logger?: LoggerProvider
  /** The IDE workspace provider `useWorkspace` and `useWorkspaceProvider` use. */
  workspace?: WorkspaceProvider
  /** The code editor provider `useEditor` and `useEditorProvider` use. */
  editor?: EditorProvider
  /** The live preview provider `usePreview` and `usePreviewProvider` use. */
  preview?: PreviewProvider
}

UseStoreOptions

Options for useStore composable.

interface UseStoreOptions<T, S> {
  /** Derives the subscribed value from the whole state. */
  selector?: (state: T) => S
  /**
   * Decides whether a newly selected value differs from the previous one; an
   * equal value keeps the previous snapshot. Without a selector, whole states
   * are compared.
   */
  equalityFn?: (previous: S, next: S) => boolean
}

SelectingStoreOptions

Options for 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 composable returns from the store's state. */
  selector: (state: T) => S
}

UseAuthOptions

Options for useAuth composable.

interface UseAuthOptions {
  /**
   * Whether to probe the session with one `refresh` on mount while signed out
   * and not loading (the token may have expired since the last visit).
   */
  autoRefresh?: boolean
}

SessionReadyProps

The SessionReady component's slots. React passes these nodes as the children and fallback props; a Vue component takes nodes as slots, so they are its default and fallback slots.

interface SessionReadyProps {
  /** What renders once the initial restore settles — signed in, signed out, or unavailable. */
  default?: () => VNode[]
  /** What renders while the session restore is still undecided; default nothing. */
  fallback?: () => VNode[]
}

ProviderProps

What every provider component takes besides its service. React passes the tree as children; a Vue component takes it as its default slot.

interface ProviderProps {
  /** The tree that reads the provided service (the default slot). */
  default?: () => VNode[]
}

StateProviderProps

Props for the {@link StateProvider} component.

interface StateProviderProps extends ProviderProps {
  provider: StateProvider
}

AuthProviderProps

Props for the {@link AuthProvider} component.

interface AuthProviderProps<T = unknown> extends ProviderProps {
  client: AuthClient<T>
  /** Wait for initial session restoration by default. Set false for a deliberately ungated shell or synchronous SSR. */
  awaitSession?: boolean
  /** Content shown while the initial session status is loading (the `sessionFallback` slot); default nothing. */
  sessionFallback?: () => VNode[]
}

ThemeProviderProps

Props for the {@link ThemeProvider} component.

interface ThemeProviderProps extends ProviderProps {
  provider: ThemeProvider
  /**
   * Not read: the theme a page starts on comes from the theme provider itself (`defaultTheme` and the
   * saved choice in `@molecule/app-theme-css-variables`), and setting one here would overwrite a
   * visitor's saved theme on every load.
   *
   * @deprecated Ignored. Pass `defaultTheme` to the theme provider (`createCSSVariablesThemeProvider({ defaultTheme })`) instead.
   */
  initialTheme?: string
}

RouterProviderProps

Props for the {@link RouterProvider} component.

interface RouterProviderProps extends ProviderProps {
  router: Router
  /**
   * The component that renders the matched child route where a layout or guard puts it (Vue
   * Router's `RouterView`), so `<RoutedView />` works under any routing bond. A routing bond
   * passes it; leave it out when the bond has no such component, and `<RoutedView />` then
   * throws an error saying so.
   */
  routedView?: Component
}

I18nProviderProps

Props for the {@link I18nProvider} component.

interface I18nProviderProps extends ProviderProps {
  provider: I18nProvider
}

HttpProviderProps

Props for the {@link HttpProvider} component.

interface HttpProviderProps extends ProviderProps {
  client: HttpClient
}

StorageProviderProps

Props for the {@link StorageProvider} component.

interface StorageProviderProps extends ProviderProps {
  provider: StorageProvider
}

LoggerProviderProps

Props for the {@link LoggerProvider} component.

interface LoggerProviderProps extends ProviderProps {
  provider: LoggerProvider
}

WorkspaceProviderProps

Props for the {@link WorkspaceProvider} component.

interface WorkspaceProviderProps extends ProviderProps {
  provider: WorkspaceProvider
}

EditorProviderProps

Props for the {@link EditorProvider} component.

interface EditorProviderProps extends ProviderProps {
  provider: EditorProvider
}

PreviewProviderProps

Props for the {@link PreviewProvider} component.

interface PreviewProviderProps extends ProviderProps {
  provider: PreviewProvider
}

MoleculeProviderProps

Props for the {@link MoleculeProvider} component: each service is optional, and only the services passed are provided (state falls back to the bonded state provider).

interface MoleculeProviderProps extends ProviderProps {
  state?: StateProvider
  auth?: AuthClient<unknown>
  /**
   * Render the app only once `auth` leaves its initial loading status ({@link SessionReadyProps}). Defaults to true.
   * With the bundled JWT client, a stored token AND cached user restore synchronously.
   * Token-only and cookie-only sessions need an asynchronous current-user request;
   * until it answers `useAuth().user.value` is `null` — a public page's signed-in action
   * (`if (!user.value) return`, a redirect to `/login`) then treats a signed-in visitor as signed out.
   * When restoration succeeds, every page's first render reads the restored user. An
   * `'unavailable'` session also renders, but remains unconfirmed and may have a null user.
   * A visitor with no session candidate settles synchronously without a request.
   * Ignored without `auth`.
   */
  awaitSession?: boolean
  /** Rendered instead of the app while {@link MoleculeProviderProps.awaitSession} waits (the `sessionFallback` slot); default nothing. */
  sessionFallback?: () => VNode[]
  theme?: ThemeProvider
  router?: Router
  i18n?: I18nProvider
  http?: HttpClient
  storage?: StorageProvider
  logger?: LoggerProvider
  workspace?: WorkspaceProvider
  editor?: EditorProvider
  preview?: PreviewProvider
}

UseAuthResult

Return type for the useAuth composable.

interface UseAuthResult<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  /**
   * The session's state as one value — render from this instead of combining
   * `initialized`/`authenticated`/`loading`. Only `'loading'` means "no decision
   * yet", so `SessionReady` waits on that and nothing else. `'unavailable'` keeps
   * a session candidate for retry and can have a null profile; redirect only on
   * `'unauthenticated'`.
   */
  status: ComputedRef<AuthState<T>['status']>
  state: ComputedRef<AuthState<T>>
  user: ComputedRef<T | null>
  isAuthenticated: ComputedRef<boolean>
  isLoading: ComputedRef<boolean>
  login: AuthClient<T>['login']
  logout: AuthClient<T>['logout']
  register: AuthClient<T, TRegister>['register']
  refresh: AuthClient<T>['refresh']
  /** Save through the configured auth transport and persist/publish its canonical profile. */
  updateProfile: AuthClient<T>['updateProfile']
  /** Cache a profile without signing in. */
  setUser: AuthClient<T>['setUser']
  /**
   * Adopt a session an exchange outside the client already established (an
   * OAuth code→token redirect, the app's own sign-in endpoint) in ONE update:
   * the token and user are stored and every consumer sees the client as
   * `authenticated` immediately.
   *
   * `setUser` alone does NOT sign the client in, and `setAccessToken` changes
   * storage only — using those two for a caller-issued session leaves every
   * `authenticated` read signed out.
   */
  setSession: AuthClient<T>['setSession']
}

UseThemeResult

Return type for useTheme composable.

interface UseThemeResult {
  theme: ComputedRef<Theme>
  themeName: ComputedRef<string>
  mode: ComputedRef<'light' | 'dark'>
  setTheme: (name: string) => void
  toggleTheme: () => void
}

UseRouterResult

Return type for useRouter composable.

interface UseRouterResult {
  location: ComputedRef<ReturnType<Router['getLocation']>>
  params: ComputedRef<RouteParams>
  query: ComputedRef<QueryParams>
  navigate: Router['navigate']
  navigateTo: Router['navigateTo']
  back: Router['back']
  forward: Router['forward']
  isActive: Router['isActive']
}

UseTranslationResult

Return type for useTranslation composable.

interface UseTranslationResult {
  t: I18nProvider['t']
  locale: ComputedRef<string>
  direction: ComputedRef<'ltr' | 'rtl'>
  locales: ComputedRef<ReturnType<I18nProvider['getLocales']>>
  setLocale: I18nProvider['setLocale']
  formatNumber: I18nProvider['formatNumber']
  formatDate: I18nProvider['formatDate']
}

UseHttpState

State for async HTTP operations.

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

UseHttpResult

Return type for useHttp composable.

interface UseHttpResult<T> extends UseHttpState<T> {
  execute: () => Promise<T | null>
  reset: () => void
}

UseHttpOptions

Options for useHttp composable: every request option, plus the hook's own.

Request options (headers, params, body data) travel with the request; immediate is read on mount only, and the callbacks fire for every request's own outcome, superseded or not.

interface UseHttpOptions<T> extends RequestConfig {
  /** Whether to execute the request immediately on mount (once per host). */
  immediate?: boolean
  /** Reports each request that succeeds, superseded or not. */
  onSuccess?: (data: T) => void
  /** Reports each request that fails, superseded or not. */
  onError?: (error: Error) => void
}

UseStorageValueResult

Return type for useStorageValue composable.

interface UseStorageValueResult<T> {
  value: Ref<T | undefined>
  loading: Ref<boolean>
  error: Ref<Error | null>
  setValue: (value: T) => Promise<void>
  removeValue: () => Promise<void>
}

UseStoragePreferenceOptions

Options for useStoragePreference composable.

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

Return type for useStoragePreference composable.

interface UseStoragePreferenceResult<T> {
  /** The persisted value, or `defaultValue` while none is known. */
  value: Ref<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: Ref<boolean>
}

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 and an argument-free action.

interface UseOptimisticToggleResult {
  /** The newest value the person chose, or the server's value when nothing is being saved. */
  value: Ref<boolean>
  /** Whether a save is running or waiting to run. */
  pending: Ref<boolean>
  /** The failure of the newest change, after the value went back; `null` otherwise. */
  error: Ref<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 and the two ways to change it.

interface UseOptimisticValueResult<T> {
  /** The newest value the person chose, or the server's value when nothing is being saved. */
  value: Ref<T>
  /** Whether a save is running or waiting to run. */
  pending: Ref<boolean>
  /** The failure of the newest change, after the value went back; `null` otherwise. */
  error: Ref<unknown>
  /**
   * Shows `next` at once and saves it, after any save already running.
   *
   * @param next - The value the person chose.
   */
  set: (next: T) => void
  /**
   * Like `set`, computed from the value shown now (`update((on) => !on)`).
   *
   * @param change - Computes the next value from the value shown now.
   */
  update: (change: (current: T) => T) => void
}

UseWorkspaceResult

Return type for useWorkspace composable.

interface UseWorkspaceResult {
  /** The panel layout: the panel list and the sizes per position. */
  layout: ComputedRef<WorkspaceLayout>
  /** The panel with keyboard focus, if any. */
  activePanel: ComputedRef<PanelId | null>
  /** The panels currently collapsed. */
  collapsedPanels: ComputedRef<Set<PanelId>>
  /**
   * Shows or hides one panel.
   *
   * @param panelId - The panel to toggle.
   */
  togglePanel: (panelId: PanelId) => void
  /**
   * Rewrites one panel's size in its position.
   *
   * @param panelId - The panel to resize.
   * @param size - The new size.
   */
  resizePanel: (panelId: PanelId, size: number) => void
  /**
   * Moves keyboard focus to a panel.
   *
   * @param panelId - The panel to activate.
   */
  setActivePanel: (panelId: PanelId) => void
  /** Restores the default layout and clears the active/collapsed/fullscreen state. */
  resetLayout: () => void
}

UseEditorResult

Return type for useEditor composable.

interface UseEditorResult {
  /** The provider's tab list, refreshed on every change event and tab action. */
  tabs: Ref<EditorTab[]>
  /** The path of the tab marked `isActive`, or `null` when none is. */
  activeFile: ComputedRef<string | null>
  /**
   * Opens a file in a tab and makes it active.
   *
   * @param file - The file to open.
   */
  openFile: (file: EditorFile) => void
  /**
   * Closes a file's tab.
   *
   * @param path - The path to close.
   */
  closeFile: (path: string) => void
  /** The active tab's content, or `null` with no active tab. */
  getContent: () => string | null
  /**
   * Writes a tab's content and marks it dirty.
   *
   * @param path - The tab's path.
   * @param content - The new content.
   */
  setContent: (path: string, content: string) => void
  /**
   * Activates a tab by path.
   *
   * @param path - The tab to activate.
   */
  setActiveTab: (path: string) => void
  /** Mounts the editor into a DOM element with the given config. */
  mount: EditorProvider['mount']
  /** Disposes the editor. */
  dispose: () => void
  /** Focuses the editor. */
  focus: () => void
  /**
   * Opens a diff tab for a file.
   *
   * @param file - The original and modified content to compare.
   */
  openDiff: (file: DiffFile) => void
  /** Closes any open diff tab. */
  closeDiff: () => void
  /**
   * Converts a preview tab into a normal (pinned) one.
   *
   * @param path - The tab to pin.
   */
  pinTab: (path: string) => void
  /**
   * Adds an extra TypeScript declaration library.
   *
   * @param content - The declaration source.
   * @param filePath - The virtual file name it appears under.
   */
  addExtraLib: (content: string, filePath: string) => void
  /**
   * Registers a Fix-with-AI request handler.
   *
   * @param callback - Called with each fix request.
   * @returns The unsubscriber.
   */
  onFixWithAI: (callback: (request: FixWithAIRequest) => void) => () => void
}

UsePreviewResult

Return type for usePreview composable.

interface UsePreviewResult {
  /** The provider's preview state (url, device, loading, connection, history flags). */
  state: ComputedRef<PreviewState>
  /**
   * Loads a new document; repeating the current url changes nothing.
   *
   * @param url - The document to load.
   */
  setUrl: (url: string) => void
  /** Reloads the current document (bumps the load nonce). */
  refresh: () => void
  /**
   * Switches the device frame