@molecule/app-solid

Framework · framework · App (browser) · v4.0.2 · Apache-2.0

Solid.js framework bindings for molecule.dev

npm install @molecule/app-solid

npm · Source on GitHub

How it works

@molecule/app-solid adapts the @molecule/* cores to the framework framework on the app (browser) side.

import { Link, MoleculeProvider, createAuth, createTheme } from '@molecule/app-solid'
import { Show } from 'solid-js'
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 authClient = createJWTAuthClient({ baseURL: '/api' })

function UserProfile() {
  const { user, isAuthenticated, logout } = createAuth<{ name?: string }>()
  const { theme, toggleTheme } = createTheme()

  return (
    <Show when={isAuthenticated()} fallback={<Link to="/login">Log in</Link>}>
      <div style={{ background: theme().colors.background }}>
        <h1>Welcome, {user()?.name}</h1>
        <button onClick={toggleTheme}>Toggle Theme</button>
        <button onClick={() => logout()}>Logout</button>
      </div>
    </Show>
  )
}

function App() {
  return (
    <MoleculeProvider state={stateProvider} auth={authClient} theme={themeProvider}>
      <UserProfile />
    </MoleculeProvider>
  )
}

Works with: @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

Reference

Solid.js framework bindings for molecule.dev.

Provides Solid-specific implementations of molecule.dev core interfaces using Solid's reactive primitives (signals, effects, resources): wrap the app in MoleculeProvider, given its services as props, then consume them through createAuth, createTheme, createRouter, createI18n, and the other primitives.

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 { Link, MoleculeProvider, createAuth, createTheme } from '@molecule/app-solid'
import { Show } from 'solid-js'
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 authClient = createJWTAuthClient({ baseURL: '/api' })

function UserProfile() {
  const { user, isAuthenticated, logout } = createAuth<{ name?: string }>()
  const { theme, toggleTheme } = createTheme()

  return (
    <Show when={isAuthenticated()} fallback={<Link to="/login">Log in</Link>}>
      <div style={{ background: theme().colors.background }}>
        <h1>Welcome, {user()?.name}</h1>
        <button onClick={toggleTheme}>Toggle Theme</button>
        <button onClick={() => logout()}>Logout</button>
      </div>
    </Show>
  )
}

function App() {
  return (
    <MoleculeProvider state={stateProvider} auth={authClient} theme={themeProvider}>
      <UserProfile />
    </MoleculeProvider>
  )
}

Authentication is a three-way decision, never a boolean signed-out branch: status === 'loading' is undecided (wait for it, do not redirect), status === 'unauthenticated' is a rejected session, and 'unavailable' is a check that failed for another reason (a network error, a 5xx). Only a 401/403 answer signs a user out, so a store outage never drops a session. Read the accessor where a component branches: status().

Type

framework

Installation

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

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 `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
   * `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
   * `logout` to end a session, or `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
   * `setUser` it adopts the session (see there). Prefer `setSession`
   * with the token and user, or `login` / `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
   * (`setAccessToken` then `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 `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 `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 `AuthClientConfigOptions.currentUserRejectionStatuses`
   * code from the fallback. Transient failures retain it as unavailable. Use `updateProfile` for a profile
   * save, or `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
   * `UserProfile` also accepts a default `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 `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
}

BodyPortalProps

Props for BodyPortal.

interface BodyPortalProps {
  /** The content to render into the target, as React's `createPortal` children. */
  children?: JSX.Element
  /**
   * The node the content renders into. `undefined` mounts into
   * `document.body`; `null` renders nothing until it becomes a node (for a
   * target the caller does not have yet).
   */
  mount?: Node | null
}

LinkProps

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

interface LinkProps extends Omit<JSX.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'> {
  /**
   * 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
}

ResolveNodeProps

Props for ResolveNode.

interface ResolveNodeProps {
  /** The node prop, as the component received it (`local.footer`). */
  node: unknown
  /**
   * Renders from the resolved node: `node()` is the node to insert (insert it once: resolved nodes
   * are real DOM nodes, and a second insertion moves them), `present()` whether it renders
   * anything by React's `slot(node)` rule. The callback runs once, like a component body, so return
   * JSX and read both inside it (`(node) => <>{node()}</>`, `<Show when={present()} fallback={…}>`):
   * a `node()` or `present() ? a : b` returned from the callback itself is read once and never
   * updates (molecule's lint rule `no-once-read-resolved-node` reports it). It is untracked already
   * (a component child), so it needs no `untrack`.
   */
  children: (node: Accessor<ResolvedChildren>, present: Accessor<boolean>) => JSX.Element
}

PresentWhileNodeProps

Props for PresentWhileNode.

interface PresentWhileNodeProps {
  /** The node prop, as the component received it (`local.footer`). */
  node: unknown
  /**
   * Renders the wrapper around the resolved node; insert `node()` once, inside the JSX it returns.
   * It runs once each time the node starts to render something, untracked, like
   * `ResolveNodeProps.children`.
   */
  children: (node: Accessor<ResolvedChildren>) => JSX.Element
}

NodePresence

What createNodePresence returns.

interface NodePresence {
  /** Whether the node renders something while its scope is rendered; false while it is not. */
  present: Accessor<boolean>
  /** Call inside the scope's callback with its `present` accessor. */
  report: (present: Accessor<boolean>) => void
}

CreateAsyncStateReturn

Return type for createAsyncState.

interface CreateAsyncStateReturn<T> {
  state: () => T
  setState: (value: T | ((prev: T) => T) | Promise<T | ((prev: T) => T)>) => void
  extendState: (
    partial:
      Partial<T> | ((prev: T) => Partial<T>) | Promise<Partial<T> | ((prev: T) => Partial<T>)>,
  ) => void
}

UseAuthOptions

Hook options for useAuth.

interface UseAuthOptions {
  /** Whether to automatically refresh the token on mount. */
  autoRefresh?: boolean
}

UseAuthResult

What useAuth returns: the session fields as accessors and the auth actions as plain functions (the same names React's useAuth returns).

interface UseAuthResult<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  /** The session status as an accessor. */
  status: Accessor<AuthState<T>['status']>
  /** The whole session state as an accessor. */
  state: Accessor<AuthState<T>>
  login: AuthClient<T>['login']
  logout: AuthClient<T>['logout']
  register: AuthClient<T, TRegister>['register']
  refresh: AuthClient<T>['refresh']
  /** Save through the configured auth transport and publish its canonical profile. */
  updateProfile: AuthClient<T>['updateProfile']
  setUser: AuthClient<T>['setUser']
  /** Adopt a session an exchange outside the client already established, in ONE update. */
  setSession: AuthClient<T>['setSession']
  /** Whether a session is authenticated locally, as an accessor. */
  isAuthenticated: Accessor<boolean>
  /** Whether the session is still undecided, as an accessor. */
  isLoading: Accessor<boolean>
  /** The cached profile as an accessor; null while none is known. */
  user: Accessor<T | null>
}

CapacitorAppPrimitives

Capacitor app primitives return type.

interface CapacitorAppPrimitives {
  state: Accessor<CapacitorAppState>
  ready: Accessor<boolean>
  initialize: () => Promise<void>
}

CreateChangePasswordReturn

Return type for createChangePassword primitive.

interface CreateChangePasswordReturn {
  state: Accessor<PromiseState<void>>
  changePassword: (oldPassword: string, newPassword: string) => Promise<void>
  reset: () => void
}

UseChangePasswordReturn

What useChangePassword returns (the same names React returns).

interface UseChangePasswordReturn {
  /** The tracked change status, as an accessor. */
  status: Accessor<UsePromiseState<void>['status']>
  /** The change failure, as an accessor. */
  error: Accessor<UsePromiseState<void>['error']>
  changePassword: (oldPassword: string, newPassword: string) => Promise<void>
  reset: () => void
}

UseDeviceResult

Device primitives return type.

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

CreateFormResult

Result of createForm primitive.

interface CreateFormResult<T extends FormValuesConstraint<T>> {
  /** Reactive form state accessor. */
  formState: Accessor<FormState<T>>

  /** Whether the form is currently valid. */
  isValid: Accessor<boolean>

  /** Whether any field has been modified. */
  isDirty: Accessor<boolean>

  /** Whether the form is currently submitting. */
  isSubmitting: Accessor<boolean>

  /** Current field errors. */
  errors: Accessor<Partial<Record<keyof T, string>>>

  /** Register a field for form management. */
  register: (name: keyof T, options?: RegisterOptions) => FieldRegistration

  /** Get the current value of a field. */
  getValue: <K extends keyof T>(name: K) => T[K]

  /** Set the value of a field. */
  setValue: <K extends keyof T>(name: K, value: T[K]) => void

  /** Get the error message for a field. */
  getError: (name: keyof T) => string | undefined

  /** Set an error message for a field. */
  setError: (name: keyof T, error: string | undefined) => void

  /** Clear all field errors. */
  clearErrors: () => void

  /** Create a submit handler function. */
  handleSubmit: (
    onSubmit: (values: T) => void | Promise<void>,
  ) => (event?: { preventDefault?: () => void }) => Promise<void>

  /** Apply a newly loaded record without clearing submission state. */
  updateValues: (values: Partial<T>, resetOptions?: FormResetOptions) => void

  /** Reset the form to initial or provided values. */
  reset: (values?: Partial<T>) => void

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

  /** The raw FormController instance for advanced use. */
  controller: FormController<T>
}

UseHttpState

State for async HTTP operations (the fields useHttp adds its controls to).

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

UseHttpResult

What useHttp returns: the request state as accessors and the controls as plain functions.

interface UseHttpResult<T> {
  /**
   * 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 is IDENTITY-STABLE for as long as `method`, `url` and the
   * HTTP client do not change. Its request options are read when it is
   * CALLED, from the latest committed render.
   */
  /** The response data as an accessor; null until a request answers. */
  data: Accessor<T | null>
  /** Whether a request is in flight, as an accessor. */
  loading: Accessor<boolean>
  /** The request failure as an accessor. */
  error: Accessor<Error | null>
  execute: () => Promise<T | null>
  reset: () => void
}

UseHttpOptions

Options for useHttp.

Every request option — headers, params, body data, signal, onSuccess, onError — is read at the moment execute runs, not when the hook ran, so an inline object or callback needs no memoizing. 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. */
  onError?: (error: Error) => void
}

UseTranslationResult

What useTranslation returns (the same names React returns).

interface UseTranslationResult {
  /**
   * Translates a key in the active locale. Follows locale changes, so text
   * read through it re-renders, and its identity follows a locale switch (one
   * function per locale, as React's `useTranslation` returns); `useT()`
   * returns one that also keeps its identity across locale changes.
   */
  t: I18nProvider['t']
  /** The active locale code, as an accessor. */
  locale: Accessor<string>
  /** Switches the active locale. Same function while the provider is unchanged. */
  setLocale: I18nProvider['setLocale']
  /** The registered locales, as an accessor; a new list once per notification. */
  locales: Accessor<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, as an accessor. */
  direction: Accessor<'ltr' | 'rtl'>
}

UseWorkspaceResult

What useWorkspace returns: the layout fields as accessors and the layout actions as plain functions (the same names React returns).

interface UseWorkspaceResult {
  /** The panel layout as an accessor. */
  layout: Accessor<WorkspaceState['layout']>
  /** The active panel id as an accessor. */
  activePanel: Accessor<PanelId | null>
  /** The collapsed panels as an accessor. */
  collapsedPanels: Accessor<Set<PanelId>>
  togglePanel: (panelId: PanelId) => void
  resizePanel: (panelId: PanelId, size: number) => void
  setActivePanel: (panelId: PanelId) => void
  resetLayout: () => void
}

UseEditorResult

What useEditor returns: the tab fields as accessors and the editor controls as plain functions (the same names React returns).

interface UseEditorResult {
  /** The provider's tab list, as an accessor. */
  tabs: Accessor<EditorTab[]>
  /** The active tab's path (null when no tab is active), as an accessor. */
  activeFile: Accessor<string | null>
  openFile: (file: EditorFile) => void
  closeFile: (path: string) => void
  getContent: () => string | null
  setContent: (path: string, content: string) => void
  setActiveTab: (path: string) => void
  mount: EditorProvider['mount']
  dispose: () => void
  focus: () => void
  openDiff: (file: DiffFile) => void
  closeDiff: () => void
  pinTab: (path: string) => void
  addExtraLib: (content: string, filePath: string) => void
  onFixWithAI: (callback: (request: FixWithAIRequest) => void) => () => void
}

UsePreviewResult

What usePreview returns: the state as an accessor and the preview controls as plain functions (the same names React returns).

interface UsePreviewResult {
  /** The preview state as an accessor. */
  state: Accessor<PreviewState>
  setUrl: (url: string) => void
  refresh: () => void
  setDevice: (device: DeviceFrame) => void
  openExternal: () => void
  /** Records a navigation the running preview reported. */
  recordNavigation: (url: string, isReplace?: boolean) => void
  /** Navigates the preview to the previous history entry (Back). */
  back: () => void
  /** Navigates the preview to the next history entry (Forward). */
  forward: () => void
}

CreateLoginReturn

Return type for createLogin primitive.

interface CreateLoginReturn<T = unknown> {
  state: Accessor<PromiseState<AuthResult<T>>>
  login: (credentials: LoginCredentials) => Promise<AuthResult<T>>
  reset: () => void
}

UseLoginReturn

What useLogin returns (the same names React returns).

interface UseLoginReturn<T = unknown> {
  /** The tracked login status, as an accessor. */
  status: Accessor<UsePromiseState<AuthResult<T>>['status']>
  /** The settled login result, as an accessor. */
  value: Accessor<UsePromiseState<AuthResult<T>>['value']>
  /** The login failure, as an accessor. */
  error: Accessor<UsePromiseState<AuthResult<T>>['error']>
  login: (credentials: LoginCredentials) => Promise<AuthResult<T>>
  reset: () => void
}

UseOAuthReturn

What useOAuth returns (the same names React returns).

interface UseOAuthReturn {
  /**
   * The configured provider names (React's `string[]`), read live: each read returns the
   * list the current config holds, so a read inside JSX or an effect follows a changed
   * config. Read it off the result (`oauth.providers`); a destructured copy keeps the
   * list of the moment it was taken, like a destructured Solid prop.
   */
  readonly providers: string[]
  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; falls
   * back to a full-page redirect when the popup is blocked.
   */
  loginViaPopup: (provider: string) => void
}

UseOAuthConfig

Configuration override for useOAuth.

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; defaults to a full-page navigation. */
  navigate?: (url: string) => void
}

CreateOAuthOptions

OAuth configuration options.

interface CreateOAuthOptions {
  /** Base URL for the API server (e.g. `https://api.example.com`). */
  baseURL?: string
  /** List of supported OAuth provider names (e.g. `['github', 'google']`). */
  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
  /** Called after a successful OAuth login (session established). */
  onSuccess?: () => void
  /** Called with a failure message when the OAuth login fails. */
  onError?: (error: string) => void
  /**
   * Auth client used to establish the session after the code exchange.
   * Overrides context resolution — when omitted, the client is resolved from
   * the surrounding `MoleculeProvider` (tolerated when absent; see the
   * cookie-session fallback documented on
   * `CreateOAuthReturn.handleCallback`).
   */
  authClient?: AuthClient<unknown>
}

CreateOAuthReturn

Return type for createOAuth primitive.

interface CreateOAuthReturn {
  /** Accessor for the configured OAuth provider names. */
  providers: Accessor<string[]>
  /** Builds the OAuth initiation URL for a provider. */
  getOAuthUrl: (provider: string) => string
  /** Starts the full-page redirect flow for a provider. */
  redirect: (provider: string) => void
  /**
   * Handles the OAuth callback: exchanges the `code` URL parameter for a
   * session. Invoked automatically at creation (see `createOAuth`);
   * exposed for callers that need to re-run it manually. No-ops unless
   * running in a browser with a `code` URL parameter and a stashed provider.
   *
   * When an auth client is available (explicit option or context), the
   * session is established locally (`setAccessToken` + `setUser` +
   * `initialize`). When no client is available, the server has already
   * established the httpOnly-cookie session during the exchange, so a
   * user-carrying response still counts as success.
   */
  handleCallback: () => Promise<void>
}

UseOptimisticToggleOptions

Options for 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 useOptimisticToggle returns: the boolean to render as accessors and an argument-free action (the same names React returns).

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

UseOptimisticValueResult

What useOptimisticValue returns: the state to render as accessors and the two ways to change it (the same names React returns).

interface UseOptimisticValueResult<T> {
  /** The value to render, as an accessor. */
  value: Accessor<T>
  /** Whether a save is running or waiting, as an accessor. */
  pending: Accessor<boolean>
  /** The failure of the newest change, as an accessor. */
  error: Accessor<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
}

CreatePasswordResetReturn

Return type for createPasswordReset primitive.

interface CreatePasswordResetReturn {
  requestState: Accessor<PromiseState<void>>
  confirmState: Accessor<PromiseState<void>>
  requestReset: (data: PasswordResetRequest) => Promise<void>
  confirmReset: (data: PasswordResetConfirm) => Promise<void>
  reset: () => void
}

UsePasswordResetReturn

What usePasswordReset returns (the same names React returns).

interface UsePasswordResetReturn {
  /** The tracked request status, as an accessor. */
  requestStatus: Accessor<UsePromiseState<void>['status']>
  /** The request failure, as an accessor. */
  requestError: Accessor<UsePromiseState<void>['error']>
  /** The tracked confirm status, as an accessor. */
  confirmStatus: Accessor<UsePromiseState<void>['status']>
  /** The confirm failure, as an accessor. */
  confirmError: Accessor<UsePromiseState<void>['error']>
  requestReset: (data: PasswordResetRequest) => Promise<void>
  confirmReset: (data: PasswordResetConfirm) => Promise<void>
  reset: () => void
}

PlatformPrimitives

Platform primitives return type.

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

UsePlatformResult

What usePlatform returns (the same names React returns).

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

CreatePromiseReturn

Promise state accessor with actions.

interface CreatePromiseReturn<T, Args extends unknown[] = unknown[]> {
  state: () => PromiseState<T>
  call: (...args: Args) => Promise<T>
  cancel: (message?: string) => void
  reset: () => void
}

UsePromiseState

Extended promise state with actions (React's usePromise shape).

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

UseFormOptions

Options for useForm.

Every FormOptions field is supported. createForm is only an override — omit it and the hook creates the controller through the bonded forms provider, 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 render. */
  resetKey?: string | number | boolean | bigint | null
  /** Explicit form factory for this one form. Defaults to the bonded forms provider. */
  createForm?: (options: FormOptions<T>) => FormController<T>
}

UseFormResult

What useForm returns: the form state fields as accessors and the field and form methods as plain functions (the same names React returns).

interface UseFormResult<T extends FormValuesConstraint<T>> {
  /** The whole form state, as an accessor. */
  formState: Accessor<FormState<T>>
  /** Whether the form is valid, as an accessor. */
  isValid: Accessor<boolean>
  /** Whether any field is dirty, as an accessor. */
  isDirty: Accessor<boolean>
  /** Whether the form is submitting, as an accessor. */
  isSubmitting: Accessor<boolean>

  /** Registers a field, returning its bindings. */
  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

  /**
   * Builds a submit runner that validates, then calls the handler with the
   * values while the form is mounted.
   */
  handleSubmit: (
    onSubmit: (values: T) => void | Promise<void>,
  ) => (event?: unknown) => 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. One field as [value, edit, fill] with a field name.
   */
  asState(): readonly [
    T,
    (value: T | ((previous: T) => T)) => void,
    (values: Partial<T> | ((previous: T) => Partial<T>)) => void,
  ]
  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>
}

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 stays
   * 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 an accessor. */
  user: Accessor<TUser | null>
  /** A user has been loaded; disable submission until this is true. */
  ready: Accessor<boolean>
  /**
   * The latest save/propagation failure. Rejected saves retain edits; a failed
   * `onSaved` callback can be retried by submit without repeating the mutation.
   */
  error: Accessor<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: Event) => 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
}

CreateSignupReturn

Return type for createSignup primitive.

interface CreateSignupReturn<T = unknown> {
  state: Accessor<PromiseState<AuthResult<T>>>
  signup: (data: RegisterData) => Promise<AuthResult<T>>
  reset: () => void
}

UseSignupReturn

What useSignup returns (the same names React returns).

interface UseSignupReturn<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  /** The tracked signup status, as an accessor. */
  status: Accessor<UsePromiseState<AuthResult<T>>['status']>
  /** The settled signup result, as an accessor. */
  value: Accessor<UsePromiseState<AuthResult<T>>['value']>
  /** The signup failure, as an accessor. */
  error: Accessor<UsePromiseState<AuthResult<T>>['error']>
  signup: (data: RegisterData<TRegister>) => Promise<AuthResult<T>>
  reset: () => void
}

UseStoreOptions

Hook options for useStore.

interface UseStoreOptions<T, S> {
  /** Derives the subscribed value from the whole state. */
  selector?: (state: T) => S
  /** Keeps the previous result when it says the new selection equals it. */
  equalityFn?: (a: S, b: S) => boolean
}

SelectingStoreOptions

Hook options 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
}

UseStorageValueOptions

Options for 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

What useStorageValue returns (the same names React returns).

interface UseStorageValueResult<T> {
  /** The current value as an accessor. */
  value: Accessor<T | undefined>
  /** Persists the value and updates the state. */
  setValue: (value: T) => Promise<void>
  /** Removes the key and restores the default value. */
  removeValue: () => Promise<void>
  /** Whether the first read is still in flight, as an accessor. */
  loading: Accessor<boolean>
  /** The read/write failure, as an accessor. */
  error: Accessor<Error | null>
}

UseStoragePreferenceOptions

Options for 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

What useStoragePreference returns (the same names React returns).

interface UseStoragePreferenceResult<T> {
  /** The persisted value (or `defaultValue` while none is known), as an accessor. */
  value: Accessor<T | undefined>
  /**
   * Writes the value through the preference store: subscribers update
   * immediately and persistence is best-effort. Accepts an updater function.
   */
  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, as an accessor. */
  ready: Accessor<boolean>
}

UseThemeResult

What useTheme returns: the theme fields as accessors and the actions as plain functions (the same names React's useTheme returns).

interface UseThemeResult {
  /** The current theme as an accessor. */
  theme: Accessor<Theme>
  /** The current theme's name as an accessor. */
  themeName: Accessor<string>
  /** Sets the theme by name. */
  setTheme: (name: string) => void
  /** Toggles light/dark through the provider's `toggleMode`. */
  toggleTheme: () => void
  /** The current mode as an accessor. */
  mode: Accessor<'light' | 'dark'>
}

UseVerifyPaymentReturnOptions

Options for 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 (the same names React returns).

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`. As an accessor.
   */
  status: Accessor<VerifyPaymentReturnStatus>

  /** Whether the URL identifies a purchase to verify, as an accessor. */
  isReturn: Accessor<boolean>

  /** The provider named by the URL (or the `provider` option), as an accessor. */
  provider: Accessor<string | null>

  /** The provider transaction/session id read from the URL, as an accessor. */
  transactionId: Accessor<string | null>

  /** Why verification failed, when it did, as an accessor. */
  error: Accessor<Error | null>

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

UseVersionResult

Version primitives return type.

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

MoleculeConfig

Configuration for molecule Solid context.

interface MoleculeConfig {
  state?: StateProvider
  auth?: AuthClient<unknown>
  /**
   * Render the app only once `auth` has decided the session (`SessionReadyProps`). Defaults
   * to true, as React's `MoleculeProvider` does.
   * With the bundled JWT client, a stored token AND cached user restore synchronously without
   * a request. Token-only and cookie-only sessions need an asynchronous current-user request;
   * until it answers `createAuth().user()` is `null` — a public page's
   * signed-in action (`if (!user()) return`, a redirect to `/login`) then treats a
   * signed-in visitor as signed out. With this set, every page's first render reads the
   * restored user when restoration succeeds. `'unavailable'` is unconfirmed and may still
   * have a null user. Without a session hint, an anonymous visitor settles in microtasks
   * without a request. Ignored without `auth`.
   */
  awaitSession?: boolean
  /** Rendered instead of the app while `MoleculeConfig.awaitSession` waits; default nothing. */
  sessionFallback?: JSX.Element
  theme?: ThemeProvider
  router?: Router
  i18n?: I18nProvider
  http?: HttpClient
  storage?: StorageProvider
  logger?: LoggerProvider
  /** The IDE workspace service useWorkspace and useWorkspaceProvider use. */
  workspace?: WorkspaceProvider
  /** The code editor service useEditor and useEditorProvider use. */
  editor?: EditorProvider
  /** The live preview service usePreview and usePreviewProvider use. */
  preview?: PreviewProvider
}

ProviderProps

Props for provider components.

interface ProviderProps {
  /** The tree the provider wraps. */
  children: JSX.Element
}

StateProviderProps

Props for the StateProvider component.

interface StateProviderProps extends ProviderProps {
  provider: StateProvider
}

AuthProviderProps

Props for the AuthProvider component.

interface AuthProviderProps<T = unknown> extends ProviderProps {
  /** The auth client the tree reads. */
  client: AuthClient<T>
  /**
   * Hold rendering until `client` has decided the session, as React's
   * `AuthProvider` does; default `true`. Set `false` for a deliberately ungated
   * shell.
   */
  awaitSession?: boolean
  /** Rendered while the session restore is undecided; default nothing. */
  sessionFallback?: JSX.Element
}

ThemeProviderProps

Props for the 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 RouterProvider component.

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

I18nProviderProps

Props for the I18nProvider component.

interface I18nProviderProps extends ProviderProps {
  provider: I18nProvider
}

HttpProviderProps

Props for the HttpProvider component.

interface HttpProviderProps extends ProviderProps {
  client: HttpClient
}

StorageProviderProps

Props for the StorageProvider component.

interface StorageProviderProps extends ProviderProps {
  provider: StorageProvider
}

LoggerProviderProps

Props for the LoggerProvider component.

interface LoggerProviderProps extends ProviderProps {
  provider: LoggerProvider
}

WorkspaceProviderProps

Props for the WorkspaceProvider component.

interface WorkspaceProviderProps extends ProviderProps {
  provider: WorkspaceProvider
}

EditorProviderProps

Props for the EditorProvider component.

interface EditorProviderProps extends ProviderProps {
  provider: EditorProvider
}

PreviewProviderProps

Props for the PreviewProvider component.

interface PreviewProviderProps extends ProviderProps {
  provider: PreviewProvider
}

MoleculeProviderProps

Props for the MoleculeProvider component, React's flat props: each service is optional, and only the services passed are provided (state falls back to the bonded state provider).

interface MoleculeProviderProps extends ProviderProps, MoleculeConfig {
  /** Only in the deprecated `MoleculeConfigProviderProps` form. */
  config?: never
}

MoleculeConfigProviderProps (deprecated)

Deprecated: Pass the services as props, as @molecule/app-react does: <MoleculeProvider auth={client}> instead of <MoleculeProvider config={{ auth: client }}>.

The MoleculeProvider props before it took React's flat props: the services inside one config object. Same defaults as the flat form.

interface MoleculeConfigProviderProps extends ProviderProps, NoFlatServices {
  /** The services to provide. */
  config: MoleculeConfig
}

SessionReadyProps

Props for the SessionReady component.

interface SessionReadyProps {
  /** What renders once the session is decided — signed in, signed out, or unavailable. */
  children: JSX.Element
  /** What renders while the session restore is still undecided; default nothing. */
  fallback?: JSX.Element
}

HttpState

State for async HTTP operations.

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

StorageValueState

State for async storage values.

interface StorageValueState<T> {
  value: T | undefined
  loading: boolean
  error: Error | null
}

AuthPrimitives

Auth primitives return type.

interface AuthPrimitives<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  state: Accessor<AuthState<T>>
  user: Accessor<T | null>
  isAuthenticated: Accessor<boolean>
  isLoading: Accessor<boolean>
  login: AuthClient<T>['login']
  logout: AuthClient<T>['logout']
  register: AuthClient<T, TRegister>['register']
  refresh: AuthClient<T>['refresh']
}

ThemePrimitives

Theme primitives return type.

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

UseRouterResult

Router primitives return type.

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

Types

Accessor

type Accessor<T> = () => T

Setter

type Setter<in out T> = {
  <U extends T>(
    ...args: undefined extends T ? [] : [value: Exclude<U, Function> | ((prev: T) => U)]
  ): undefined extends T ? undefined : U
  <U extends T>(value: (prev: T) => U): U
  <U extends T>(value: Exclude<U, Function>): U
  <U extends T>(value: Exclude<U, Function> | ((prev: T) => U)): U
}

RouteParams

URL path parameter key-value map extracted from dynamic route segments (e.g. { id: '123' }).

type RouteParams = Record<string, string>

QueryParams

URL query string parameter map (single values or arrays for repeated keys).

type QueryParams = Record<string, string | string[] | undefined>

AsyncSetState

Async-capable setState function: a value, an updater, or a promise of either (React's useAsyncState shape).

type AsyncSetState<T> = (
  value: T | ((prev: T) => T) | Promise<T | ((prev: T) => T)>,
) => Promise<void>

AsyncExtendState

Async-capable extendState function for partial updates (React's shape).

type AsyncExtendState<T> = (
  partial: Partial<T> | ((prev: T) => Partial<T>) | Promise<Partial<T> | ((prev: T) => Partial<T>)>,
) => Promise<void>

UseCapacitorAppResult

What useCapacitorApp returns: the coordinator's state fields as accessors plus initialize (the same names React returns).

type UseCapacitorAppResult = {
  readonly [K in keyof CapacitorAppState]: Accessor<CapacitorAppState[K]>
} & {
  initialize: () => Promise<void>
}

DevicePrimitives (deprecated)

Deprecated: Renamed to UseDeviceResult, @molecule/app-react's name for it.

The former name of UseDeviceResult.

type DevicePrimitives = UseDeviceResult

UseTShorthandOptions

Options for the shorthand form of UseTFunction: the fallback text is passed positionally, so only count remains here.

type UseTShorthandOptions = Omit<TranslateOptions, 'defaultValue'>

UseTFunction

Translation function returned by useT.

Two compatible call forms:

  • t(key, values?, options?) — the I18nProvider.t signature.
  • t(key, fallback, options?) — a string second argument is the inline English defaultValue, with optional count for pluralization.

Its identity is stable while the i18n provider instance is unchanged, so it can be used directly as an effect dependency.

type UseTFunction = TranslateFunctionWithFallback

MaybeAccessor

A plain value or a Solid accessor holding it.

type MaybeAccessor<T> = T | Accessor<T>

UseListRouteResult

What useListRoute returns: each list-state field as an accessor, and the link builder and navigation actions as plain functions (React's ListRouteResult under this binding's value shape).

type UseListRouteResult<Filter extends string = string, Selection extends string = string> = {
  /** Current 1-indexed page. */
  readonly page: Accessor<number>
  /** Configured items per page. */
  readonly pageSize: Accessor<number>
  /** Zero-indexed item offset for an API request. */
  readonly offset: Accessor<number>
  /** Current URL filter values, including values supplied by path parameters. */
  readonly filters: Accessor<Record<Filter, string | undefined>>
  /** Matching view, or the configured fallback. */
  readonly selection: Accessor<Selection | undefined>
  /** Decoded current path parameters, also usable as API-only filters. */
  readonly params: Accessor<RouteParams>
  /** False while a protected selection is awaiting auth, signed out, or unavailable. */
  readonly canLoad: Accessor<boolean>
  /** Readiness for the current view. A public view always stays ready. */
  readonly status: Accessor<ListRouteResult<Filter, Selection>['status']>
  /** Sign-in destination while a signed-out protected view is being redirected. */
  readonly redirectTo: Accessor<string | undefined>
  /** Build a real link target, preserving the current pathname, unrelated query values and hash. */
  readonly href: ListRouteResult<Filter, Selection>['href']
  /** Navigate atomically. Location state is preserved unless options explicitly replace it. */
  readonly navigate: ListRouteResult<Filter, Selection>['navigate']
  /** Change only the page, retaining the current filters and view. */
  readonly setPage: ListRouteResult<Filter, Selection>['setPage']
  /** Patch URL filters and return to page one. */
  readonly setFilters: ListRouteResult<Filter, Selection>['setFilters']
  /** Select a configured view at page one, preserving current route parameters. */
  readonly select: ListRouteResult<Filter, Selection>['select']
}

VerifyPaymentReturnStatus

How far the return-page verification has got.

type VerifyPaymentReturnStatus = 'idle' | 'verifying' | 'verified' | 'failed'

VersionPrimitives (deprecated)

Deprecated: Renamed to UseVersionResult, @molecule/app-react's name for it.

The former name of UseVersionResult.

type VersionPrimitives = UseVersionResult

LazyNode

An item a consumer writes as a function, so the component decides when to create it: React's child element, created only where the component renders it. () => <Row row={row} /> is one.

type LazyNode = () => JSX.Element

NodeItems

The type of a node prop whose items a component counts or slices before it renders them (a show-more list): plain JSX, an accessor item (LazyNode), or an array of either. Each accessor item is created once, when the component first shows it, and keeps its state while it stays in the array (by identity: build a changing list with mapArray, which keeps a row's accessor while the row stays). Every other node prop is JSX.Element, which refuses an accessor item, since such a component creates its content when it is passed.

type NodeItems = JSX.Element | LazyNode | readonly (JSX.Element | LazyNode)[]

WithNodes

A core props type (@molecule/app-ui's, whose node props are untyped so every framework can read them) with the named node props typed JSX.Element, as a Solid component takes them. A Solid component names its node props once (Component<WithNodes<AlertProps, 'children' | 'icon'>>), so a consumer's accessor item there is a type error, and the component inserts them without a cast. Optional props stay optional.

type WithNodes<P, K extends keyof P> = { [N in keyof P]: N extends K ? JSX.Element : P[N] }

RouterPrimitives (deprecated)

Deprecated: Renamed to UseRouterResult, @molecule/app-react's name for it.

The former name of UseRouterResult.

type RouterPrimitives = UseRouterResult

Functions

BodyPortal(props)

Renders its children directly under a target node (no wrapper element) and removes them when the component unmounts. New children are added after the portal's last child, as React's portal adds them.

function BodyPortal(props: BodyPortalProps): undefined
  • props — The children to portal and the optional mount target.

Returns: Nothing — the children render into the target, not inline.

getStateProvider()

Get the state provider from context.

function getStateProvider(): StateProvider

Returns: The state provider instance.

getAuthClient()

Get the auth client from context.

Pass the same generics the client was created with — getAuthClient<MyUser, { username: string }>() — so register() accepts the app's own fields.

function getAuthClient<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(): AuthClient<T, TRegister>

Returns: The auth client instance.

getThemeProvider()

Get the theme provider from context.

function getThemeProvider(): ThemeProvider

Returns: The theme provider instance.

getRouter()

Get the router from context.

function getRouter(): Router

Returns: The router instance.

getI18nProvider()

Get the i18n provider from context.

function getI18nProvider(): I18nProvider

Returns: The i18n provider instance.

getHttpClient()

Get the HTTP client from context.

function getHttpClient(): HttpClient

Returns: The HTTP client instance.

getStorageProvider()

Get the storage provider from context.

function getStorageProvider(): StorageProvider

Returns: The storage provider instance.

getLoggerProvider()

Get the logger provider from context.

function getLoggerProvider(): LoggerProvider

Returns: The logger provider instance.

getWorkspaceProvider()

Get the IDE workspace provider from context.

function getWorkspaceProvider(): WorkspaceProvider

Returns: The workspace provider instance.

getEditorProvider()

Get the code editor provider from context.

function getEditorProvider(): EditorProvider

Returns: The editor provider instance.

getPreviewProvider()

Get the live preview provider from context.

function getPreviewProvider(): PreviewProvider

Returns: The preview provider instance.

Link(props)

An <a href={to}> that navigates in-app through the molecule router, with react-router <Link>'s rules (followRouterLink from @molecule/app-routing): a plain primary click navigates without a page load; a ctrl/cmd, shift or alt click, a target other than _self, a click an onClick already prevented, and a URL on another origin are left to the browser.

A link to a URL outside the app (another origin, mailto:, //host) needs no router: the browser, or on a device the URL handler, opens it. It renders with no router mounted, the URL as its href, and a click is left to the browser (onClick still runs). A link to an app path needs a router, and fails without one with the error useRouterInstance throws.

Use it for every internal link instead of an anchor with a click handler that calls navigate(). Render it inside a MoleculeProvider whose config has a router.

function Link(props: LinkProps): JSX.Element
  • props — The link's LinkProps; other attributes go on the anchor.

Returns: The anchor.

ResolveNode(props)

Resolves a node prop once, in the place where it is put, and always renders its callback. Use it when something besides the node's own wrapper reads whether the node renders anything: a default that replaces it (Alert's status icon, Table's empty text), a class on a sibling (Input's padding), an aria-describedby that points at it. For a wrapper that exists only while the node renders something, use PresentWhileNode.

Put it at the highest point inside the branch that shows the node and still contains every reader (inside a dialog's open branch, not at the top of the dialog component). The node's components are created when this is rendered and disposed with it, so a closed dialog creates none of them and each opening creates them again, as React mounts them. Resolving the prop with resolveNode() at the top of the component instead creates them while the branch is hidden (their effects and fetches run) and keeps one instance across close and reopen.

function ResolveNode(props: ResolveNodeProps): JSX.Element
  • props — The node prop and the render callback (see ResolveNodeProps).

Returns: What the callback renders.

PresentWhileNode(props)

Renders its callback only while the node prop renders something: React's slot(footer) && <div>{footer}</div>. A node that renders nothing (null, false, '', an empty list, a <For> over no rows) leaves no wrapper, like an omitted prop. Place it where the wrapper goes; the node's components are created and disposed with it (see ResolveNode).

function PresentWhileNode(props: PresentWhileNodeProps): JSX.Element
  • props — The node prop and the wrapper callback (see PresentWhileNodeProps).

Returns: The wrapper while the node renders something, else nothing.

createNodePresence()

Carries a node's presence out of the branch that renders it, for a reader outside that branch: a dialog's aria-labelledby is a prop of Modal, set before Modal's open branch renders the heading it names. The node stays resolved inside the branch (see ResolveNode), so it is still created only while shown, and present() is false whenever the scope is not rendered.

function createNodePresence(): NodePresence

Returns: The presence and the function the scope reports it with.

rendersNode(node)

Whether a node, resolved with Solid's children(), renders anything: not null, undefined, a boolean or '', and not a list holding only those. React's slot(node) from @molecule/app-react/render decides the same way, so a component that renders a wrapper only while a node prop has something to show (a dialog's heading id, a dropdown panel) reads the same in both: an empty list ([], a <For> over no rows) renders nothing, like an omitted prop.

function rendersNode(node: unknown): boolean
  • node — The resolved node.

Returns: True when it renders something.

createAsyncState(initialState)

Primitive like createSignal but accepts Promises and supports partial state extension.

function createAsyncState<T>(initialState: T): CreateAsyncStateReturn<T>
  • initialState — Initial state value

Returns: The created instance.

useAsyncState(initialState)

Like createSignal but accepting Promises and partial updates, under React's hook name: a [state, setState, extendState] tuple where setState replaces, extendState merges, and both accept a value, an updater or a promise of either. There is deliberately no latest-wins guard: whatever settles last wins, so a promise settling after a newer synchronous set overwrites it.

function useAsyncState<T>(initialState: T): [T, AsyncSetState<T>, AsyncExtendState<T>]
  • initialState — Initial state value.

Returns: The tuple: the live state, the replacing setter, the merging setter.

useAuthClient()

The auth client from the nearest MoleculeProvider (config.auth), under React's hook name.

Pass the same generics the client was created with — useAuthClient<MyUser, { username: string }>() — so register() accepts the app's own fields.

function useAuthClient<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(): AuthClient<T, TRegister>

Returns: The auth client instance.

useAuth(options)

Authentication state and actions, under React's hook name.

The session decision is three-way, never a boolean signed-out branch: status === 'loading' is undecided — wait for it and redirect only on status === 'unauthenticated'. 'unavailable' keeps the session candidate for retry, but isAuthenticated() can be false and user() null while a token-only restore has no cached profile. A restore failure other than 401/403 never signs out.

function useAuth<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(options?: MaybeAccessor<UseAuthOptions>): UseAuthResult<T, TRegister>
  • options — Hook options (autoRefresh probes once on mount while signed out). May be an accessor: autoRefresh turning on through it probes once more on the same mount, the way React re-renders useAuth.

Returns: Session fields as accessors and the auth actions.

useUser()

The authenticated user, under React's hook name.

function useUser<T = UserProfile>(): Accessor<T | null>

Returns: Accessor for the user or null.

useIsAuthenticated()

Whether a session exists, under React's hook name.

function useIsAuthenticated(): Accessor<boolean>

Returns: Accessor for whether the session is authenticated.

createAuth()

Create auth primitives for authentication state and actions.

function createAuth<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(): AuthPrimitives<T, TRegister>

Returns: Auth primitives object

createAuthGuard(redirectTo)

Create a guard primitive that redirects unauthenticated users.

function createAuthGuard(redirectTo: string): Accessor<boolean>
  • redirectTo — Path to redirect to

Returns: Accessor indicating if user is allowed

createAuthHelpers()

Creates a auth helpers.

function createAuthHelpers<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(): {
  login: (credentials: LoginCredentials) => Promise<AuthResult<T>>
  logout: () => Promise<void>
  register: (data: RegisterData<TRegister>) => Promise<AuthResult<T>>
  refresh: () => Promise<AuthResult<T>>
  getUser: () => T | null
  getToken: () => string | null
  isAuthenticated: () => boolean
}

Returns: The created result.

createAuthFromClient(client)

Create auth primitives from a specific client.

function createAuthFromClient<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(client: AuthClient<T, TRegister>): AuthPrimitives<T, TRegister>
  • client — Auth client

Returns: Auth primitives

createCapacitorApp(options)

Create Capacitor app primitives for native app initialization.

Wraps the core createCapacitorApp coordinator with Solid signals, automatically initializing and cleaning up on disposal.

function createCapacitorApp(options?: CapacitorAppOptions): CapacitorAppPrimitives
  • options — Capacitor app configuration options.

Returns: Capacitor app primitives object

useCapacitorApp(options)

Capacitor app initialization and state management, under React's hook name.

Creates a CapacitorApp coordinator on mount, subscribes to state changes, and auto-initializes. Cleans up listeners on unmount via destroy().

function useCapacitorApp(options?: CapacitorAppOptions): UseCapacitorAppResult
  • options — Capacitor app configuration options.

Returns: The state fields as accessors and an initialize function for manual re-initialization.

createChangePassword()

Creates a change password primitive with async state tracking.

function createChangePassword(): CreateChangePasswordReturn

Returns: Change password state and action

useChangePassword()

Changing password with async state tracking, under React's hook name.

function useChangePassword(): UseChangePasswordReturn

Returns: Change state (status, error as accessors) and the controls.

createDevice()

Create device primitives for accessing device information.

This is a static primitive (no reactive signals) since device info does not change during the lifecycle of the app.

function createDevice(): UseDeviceResult

Returns: Device primitives object

createForm(provider, options)

Create form primitives for form state management and validation.

function createForm<T extends FormValuesConstraint<T>>(
  provider: FormProvider,
  options: FormOptions<T>,
): CreateFormResult<T>
  • provider — Form provider that creates controllers
  • options — Form configuration options

Returns: Form primitives object

createFieldSignal(controller, name)

Create a reactive accessor for a single field's state.

function createFieldSignal<T extends FormValuesConstraint<T>>(
  controller: FormController<T>,
  name: keyof T,
): Accessor<FieldState<T[keyof T]>>
  • controller — Form controller
  • name — Field name to track

Returns: Accessor for the field state

createWatchSignal(controller, name)

Create a reactive accessor that tracks a single field's value.

function createWatchSignal<T extends FormValuesConstraint<T>, K extends keyof T>(
  controller: FormController<T>,
  name: K,
): Accessor<T[K]>
  • controller — Form controller
  • name — Field name to watch

Returns: Accessor for the field value

createFormHelpers(provider)

Creates a form helpers.

function createFormHelpers(provider: FormProvider): {
  createForm: <T extends FormValuesConstraint<T>>(options: FormOptions<T>) => CreateFormResult<T>
}
  • provider — The provider implementation.

Returns: The created result.

createFormFromController(controller)

Create form primitives from an existing controller.

Useful when you have a controller created externally and want to wrap it with Solid reactivity.

function createFormFromController<T extends FormValuesConstraint<T>>(
  controller: FormController<T>,
): CreateFormResult<T>
  • controller — An existing FormController

Returns: Form primitives object

useHttpClient()

The HTTP client from the nearest MoleculeProvider (config.http), under React's hook name.

function useHttpClient(): HttpClient

Returns: The HTTP client from context.

useHttp(method, url, options)

HTTP requests with state management, under React's hook name.

execute keeps one identity while method, url and the HTTP client stay the same. The current headers, body, signal and callbacks are read when execute is called. The newest request owns the state: an older request that answers after a newer one (or after reset) cannot overwrite it, and its callbacks still report to the caller.

function useHttp<T>(
  method: MaybeAccessor<'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'>,
  url: MaybeAccessor<string>,
  options?: MaybeAccessor<UseHttpOptions<T>>,
): UseHttpResult<T>
  • method — HTTP method. May be an accessor; read when execute runs.
  • url — Request URL. May be an accessor, read when execute runs: a changed url makes the next execute request it on the same mount.
  • options — Request options, read at call time. May be an accessor: a changed options object re-arms nothing on its own (the mount-time immediate fetch never repeats), but the next execute reads the new headers, body, signal and callbacks.

Returns: Request state (data, loading, error) as accessors and execute/reset.

useGet(url, options)

GET requests, under React's hook name.

function useGet<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>
  • url — Request URL to fetch from.
  • options — HTTP request options including callbacks and request config.

Returns: Request state (data, loading, error) and controls (execute, reset).

usePost(url, options)

POST requests, under React's hook name.

function usePost<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>
  • url — Request URL to post to.
  • options — HTTP request options including body data and callbacks.

Returns: Request state (data, loading, error) and controls (execute, reset).

usePut(url, options)

PUT requests, under React's hook name.

function usePut<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>
  • url — Request URL to send the PUT request to.
  • options — HTTP request options including body data and callbacks.

Returns: Request state (data, loading, error) and controls (execute, reset).

usePatch(url, options)

PATCH requests, under React's hook name.

function usePatch<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>
  • url — Request URL to send the PATCH request to.
  • options — HTTP request options including partial body data and callbacks.

Returns: Request state (data, loading, error) and controls (execute, reset).

useDelete(url, options)

DELETE requests, under React's hook name; a body travels in options.data.

function useDelete<T>(url: string, options?: UseHttpOptions<T>): UseHttpResult<T>
  • url — Request URL of the resource to delete.
  • options — HTTP request options including callbacks.

Returns: Request state (data, loading, error) and controls (execute, reset).

createHttp()

Creates a http.

function createHttp(): {
  get: <T>(url: string, config?: RequestConfig) => Promise<HttpResponse<T>>
  post: <T>(url: string, data?: unknown, config?: RequestConfig) => Promise<HttpResponse<T>>
  put: <T>(url: string, data?: unknown, config?: RequestConfig) => Promise<HttpResponse<T>>
  patch: <T>(url: string, data?: unknown, config?: RequestConfig) => Promise<HttpResponse<T>>
  delete: <T>(url: string, config?: RequestConfig) => Promise<HttpResponse<T>>
  request: <T>(config: FullRequestConfig) => Promise<HttpResponse<T>>
}

Returns: The created result.

useFetch(url, config)

Create a resource for fetching data.

function useFetch<T>(
  url: Accessor<string> | string,
  config?: RequestConfig,
): Resource<T | undefined>
  • url — URL string or accessor returning a URL string.
  • config — Optional request configuration.

Returns: Solid resource

useMutation()

Hook for mutation.

function useMutation<T>(): {
  mutate: (
    url: string,
    payload?: unknown,
    method?: 'POST' | 'PUT' | 'PATCH' | 'DELETE',
  ) => Promise<T>
  isLoading: Accessor<boolean>
  error: Accessor<Error | null>
  data: Accessor<T | null>
  reset: () => void
}

Returns: The result.

useLazyQuery()

Hook for lazy query.

function useLazyQuery<T>(): {
  execute: (url: string, config?: RequestConfig) => Promise<T>
  data: () => T | null
  isLoading: () => boolean
  error: () => Error | null
  reset: () => void
}

Returns: The result.

createHttpHelpers()

Creates a http helpers.

function createHttpHelpers(): {
  get: <T>(url: string, config?: RequestConfig) => Promise<HttpResponse<T>>
  post: <T>(url: string, data?: unknown, config?: RequestConfig) => Promise<HttpResponse<T>>
  put: <T>(url: string, data?: unknown, config?: RequestConfig) => Promise<HttpResponse<T>>
  patch: <T>(url: string, data?: unknown, config?: RequestConfig) => Promise<HttpResponse<T>>
  delete: <T>(url: string, config?: RequestConfig) => Promise<HttpResponse<T>>
  setAuthToken: (token: string | null) => void
  getAuthToken: () => string | null
}

Returns: The created result.

createHttpFromClient(client)

Creates a http from client.

function createHttpFromClient(client: HttpClient): {
  get: <T>(url: string, config?: RequestConfig) => Promise<HttpResponse<T>>
  post: <T>(url: string, data?: unknown, config?: RequestConfig) => Promise<HttpResponse<T>>
  put: <T>(url: string, data?: unknown, config?: RequestConfig) => Promise<HttpResponse<T>>
  patch: <T>(url: string, data?: unknown, config?: RequestConfig) => Promise<HttpResponse<T>>
  delete: <T>(url: string, config?: RequestConfig) => Promise<HttpResponse<T>>
  request: <T>(config: FullRequestConfig) => Promise<HttpResponse<T>>
}
  • client — The client instance.

Returns: The created result.

useRichTranslation()

Reads rich catalog messages from the active provider. Call the returned translation function in render so it follows locale and catalog changes.

function useRichTranslation(): RichTranslateFunction

Returns: The locale-reactive rich translation function.

useI18nProvider()

The i18n provider: the one the nearest MoleculeProvider supplies (config.i18n), otherwise the bonded @molecule/app-i18n provider, which is the one the static t reads. A component can therefore translate through the hooks wherever the static t works.

function useI18nProvider(): I18nProvider

Returns: The i18n provider from context, or the bonded provider.

useTranslation()

Internationalization state and actions, under React's hook name.

function useTranslation(): UseTranslationResult

Returns: The translation function, the locale, and the formatters.

useT()

The translation function alone, under React's hook name.

The returned function keeps ONE identity for as long as the provider instance is unchanged (locale changes included), and still re-reads the active translations on every call, so text read through it is current. Call it in either of two compatible forms:

  • t(key, values?, options?) — the provider signature.
  • t(key, fallback, options?) — a string second argument is the defaultValue, so t('cart.empty', 'Your cart is empty') equals t('cart.empty', undefined, { defaultValue: 'Your cart is empty' }).
function useT(): UseTFunction

Returns: The translation function (stable identity while the provider is unchanged).

useLocale()

The current locale, under React's hook name.

function useLocale(): Accessor<string>

Returns: Accessor for the current locale code.

useDirection()

The text direction, under React's hook name.

function useDirection(): Accessor<'ltr' | 'rtl'>

Returns: Accessor for the active locale's text direction ('ltr' or 'rtl').

useI18nError(error)

Translates an error at render time so the displayed message updates automatically when the locale changes, under React's hook name.

If error is an I18nError (thrown via throw new I18nError(key)), its key is translated using the current locale; for plain Error instances, error.message is returned unchanged.

function useI18nError(error: MaybeAccessor<Error | null | undefined>): Accessor<string | null>
  • error — The error to translate, or null/undefined. May be an accessor: a changed error replaces the message on the same mount, the way React re-renders useI18nError.

Returns: Accessor for the translated error string, or null without an error.

createI18n()

Creates a i18n.

function createI18n(): {
  t: TranslateFunction
  locale: Accessor<string>
  setLocale: (newLocale: string) => Promise<void>
  isReady: Accessor<boolean>
  getLocales: () => LocaleConfig[]
  hasKey: (key: string) => boolean
}

Returns: The created result.

useTranslate()

Get translate function.

function useTranslate(): TranslateFunction

Returns: Translate function

usePlural(key, count, values)

Create a reactive plural translation.

function usePlural(
  key: string,
  count: Accessor<number>,
  values?: InterpolationValues,
): Accessor<string>
  • key — Translation key
  • count — Count accessor for pluralization
  • values — Interpolation values for the translation.

Returns: Accessor for translated string

createI18nHelpers()

Creates a i18n helpers.

function createI18nHelpers(): {
  t: TranslateFunction
  getLocale: () => string
  setLocale: (locale: string) => Promise<void>
  getLocales: () => LocaleConfig[]
  hasKey: (key: string) => boolean
  isReady: () => boolean
}

Returns: The created result.

createI18nFromProvider(provider)

Creates a i18n from provider.

function createI18nFromProvider(provider: I18nProvider): {
  t: TranslateFunction
  locale: Accessor<string>
  setLocale: (newLocale: string) => Promise<void>
  isReady: Accessor<boolean>
  getLocales: () => LocaleConfig[]
  hasKey: (key: string) => boolean
}
  • provider — The provider implementation.

Returns: The created result.

useWorkspaceProvider()

The workspace provider from the nearest MoleculeProvider (config.workspace), under React's hook name.

function useWorkspaceProvider(): WorkspaceProvider

Returns: The workspace provider instance.

useWorkspace()

IDE workspace layout management, under React's hook name.

function useWorkspace(): UseWorkspaceResult

Returns: The workspace state as accessors and the layout actions.

useEditorProvider()

The code editor provider from the nearest MoleculeProvider (config.editor), under React's hook name.

function useEditorProvider(): EditorProvider

Returns: The editor provider instance.

useEditor()

Code editor management, under React's hook name.

tabs and activeFile always come from the provider's own tab list, read at mount, on every provider change event, and after each action that changes the tab list.

function useEditor(): UseEditorResult

Returns: Editor state (tabs, activeFile as accessors) and the controls.

usePreviewProvider()

The live preview provider from the nearest MoleculeProvider (config.preview), under React's hook name.

function usePreviewProvider(): PreviewProvider

Returns: The preview provider instance.

usePreview()

Live preview management, under React's hook name.

function usePreview(): UsePreviewResult

Returns: The preview state as an accessor and the controls.

useLoggerProvider()

Get the logger provider from the nearest MoleculeProvider (config.logger).

function useLoggerProvider(): LoggerProvider

Returns: The logger provider.

useLogger(name, config)

Get a logger for one component or module, exactly like React's useLogger: with config the provider creates a logger from { name, ...config }, without it the shared logger of that name is returned.

function useLogger(name: string, config?: Partial<LoggerConfig>): Logger
  • name — Logger name (usually component or module name)
  • config — Optional logger configuration

Returns: Logger instance

useRootLogger()

Get the root logger, under React's hook name.

function useRootLogger(): Logger

Returns: Root logger instance

useChildLogger(parentName, context)

Create a child logger with additional context.

function useChildLogger(parentName: string, context: Record<string, unknown>): Logger
  • parentName — Parent logger name
  • context — Additional context

Returns: Child logger instance

getLogger(name)

Get a logger instance.

function getLogger(name?: string): Logger
  • name — Logger name

Returns: Logger instance

createLogger(config)

Create a logger with custom configuration.

function createLogger(config: LoggerConfig): Logger
  • config — Logger configuration

Returns: Logger instance

getRootLogger()

Get the root logger.

function getRootLogger(): Logger

Returns: Root logger instance

getChildLogger(name, context)

Create a child logger with additional context.

function getChildLogger(name: string, context: Record<string, unknown>): Logger
  • name — Parent logger name
  • context — Additional context

Returns: Child logger instance

useComponentLogger(componentName)

Create a component logger that includes component name in context.

function useComponentLogger(componentName: string): Logger
  • componentName — Name of the component

Returns: Logger configured for the component

createLoggerHelpers()

Creates a logger helpers.

function createLoggerHelpers(): {
  getLogger: (name?: string) => Logger
  createLogger: (config: LoggerConfig) => Logger
  setLevel: (level: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'silent') => void
  getLevel: () => string
  enable: () => void
  disable: () => void
  isEnabled: () => boolean
}

Returns: The created result.

createLoggerHelpersFromProvider(provider)

Creates a logger helpers from provider.

function createLoggerHelpersFromProvider(provider: LoggerProvider): {
  getLogger: (name?: string) => Logger
  createLogger: (config: LoggerConfig) => Logger
  setLevel: (level: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'silent') => void
  getLevel: () => string
  enable: () => void
  disable: () => void
  isEnabled: () => boolean
}
  • provider — The provider implementation.

Returns: The created result.

createLoggerFromProvider(provider, name)

Create logger from a specific provider.

function createLoggerFromProvider(provider: LoggerProvider, name?: string): Logger
  • provider — Logger provider
  • name — Logger name

Returns: Logger instance

createLogin()

Creates a login primitive with async state tracking.

function createLogin<T = unknown>(): CreateLoginReturn<T>

Returns: Login state and action

useLogin()

Login with async state tracking, under React's hook name.

Registration is available through const { register } = useAuth(); use usePromise(register) when a form needs the same pending/error tracking.

function useLogin<T = unknown>(): UseLoginReturn<T>

Returns: Login state (status, value, error as accessors) and the controls.

access(value)

Reads the current value of a plain value or accessor argument.

function access<T>(value: MaybeAccessor<T>): T
  • value — The argument as the caller passed it: a plain value or an accessor of one.

Returns: The current value.

useOAuth(config)

OAuth authentication helpers, under React's hook name: builds the provider URLs, starts a login (full-page or popup), and automatically handles OAuth callbacks by detecting code and state URL parameters and exchanging them for a session — relaying to the opener when running inside a popup we opened.

function useOAuth(config?: MaybeAccessor<UseOAuthConfig>): UseOAuthReturn
  • config — Optional OAuth configuration override. May be an accessor: a changed oauthProviders list is what providers reads, and the rest of the config (URL parts, navigate, onSuccess, onError) is read at the moment an action or a settling flow uses it, on the same mount.

Returns: providers, getOAuthUrl, redirect, and loginViaPopup.

createOAuth(options)

Creates OAuth helpers.

Automatically handles OAuth callbacks by detecting code and state URL parameters and exchanging them for a session:

  • Inside a Solid owner (component setup / createRoot), the callback handling is deferred to onMount so it runs client-side after mount.
  • Outside an owner (a plain function call, e.g. bootstrap code), it runs immediately at creation, browser-guarded.
function createOAuth(options?: CreateOAuthOptions): CreateOAuthReturn
  • options — OAuth configuration

Returns: The created instance.

useOptimisticToggle(options)

Owns the state and save ordering of a follow, favorite, star or subscription control while all markup stays in the app. Pass toggle straight to the click handler: it takes no argument and flips the value shown now. commit(desired) receives the value to SAVE, never the old one, and returns the server's boolean answer. Only the newest failure rolls the shown value back.

Saves run one at a time; clicks during a save coalesce to the newest desired value. Use pending for feedback, not to disable the control or drop a click. Mount it only after the record loads, key it by record identity, and keep it mounted through refetches. For a flag with a related count, use useOptimisticValue with both fields in one value.

function useOptimisticToggle(
  options: MaybeAccessor<UseOptimisticToggleOptions>,
): UseOptimisticToggleResult
  • options — The server value, the save and an optional error callback (or an accessor of them: a new value syncs in while nothing is saving).

Returns: The value, pending and error state as accessors, and the stable toggle.

useOptimisticValue(options)

A server-backed value — a favorite, follow, like or bookmark button, a rating, a quantity, a setting switch — that changes immediately on a tap and is saved one change at a time, in order. See createOptimisticValue in @molecule/app-state, under React's hook name.

A new server value is taken only when it differs (by equals) from the one the hook last received, and only while nothing is being saved, so a refetch of older data never flips the button mid-save. The latest commit and onError are always used. Keep related fields in the SAME value and let commit reject on failure so the hook can roll back.

function useOptimisticValue<T>(
  options: MaybeAccessor<OptimisticValueOptions<T>>,
): UseOptimisticValueResult<T>
  • options — The server's current value and how to save a change. May be an accessor: the controller survives a change (a pending save keeps running), commit/onError are always read from the latest options, and a new value syncs in exactly as React's re-render delivers it.

Returns: The value, pending and error state as accessors, and set/update.

createPasswordReset()

Creates a password reset primitive with async state tracking.

function createPasswordReset(): CreatePasswordResetReturn

Returns: Password reset state and actions

usePasswordReset()

The password reset flow with async state tracking, under React's hook name. The request and confirm halves are tracked separately.

function usePasswordReset(): UsePasswordResetReturn

Returns: Password reset state (statuses and errors as accessors) and the actions.

createPlatform()

Create platform primitives for detecting the current platform.

This is a static primitive (no reactive signals) since the platform does not change during the lifecycle of the app.

function createPlatform(): PlatformPrimitives

Returns: Platform primitives object

usePlatform()

Platform detection, under React's hook name.

Platform info is static and doesn't change at runtime; this reads the module-singleton detection once per component.

function usePlatform(): UsePlatformResult

Returns: Platform information and utility methods.

createPromise(asyncFn)

Primitive that wraps an async function with reactive state tracking.

function createPromise<V, Args extends unknown[]>(
  asyncFn: (...args: Args) => Promise<V>,
): CreatePromiseReturn<V, Args>
  • asyncFn — The async function to wrap

Returns: Object with state accessor, call, cancel, and reset functions

usePromise(asyncFn)

Wraps an async function with state tracking, under React's hook name: a [state, wrapped] tuple. The wrapped function tracks its latest call — a stale resolution or rejection after a newer call started is not shown but still reaches its caller (a rejection rethrows). cancel marks the pending call rejected with its message; reset returns to idle.

function usePromise<V, A extends unknown[]>(
  asyncFn: (...args: A) => Promise<V>,
): [UsePromiseState<V>, (...args: A) => Promise<V>]
  • asyncFn — The async function to wrap.

Returns: The tuple: the live state and the wrapped function.

useForm(options)

Form state management over the bonded forms provider, under React's hook name.

The controller is created once per component (a resetKey change starts a fresh one). When values changes by content, it becomes the new baseline; resetOptions.keepDirtyValues retains edited fields while pristine fields take the loaded values.

function useForm<T extends FormValuesConstraint<T> = Record<string, unknown>>(
  options?: MaybeAccessor<UseFormOptions<T>>,
): UseFormResult<T>
  • options — Form options, forwarded to the provider. May be an accessor: the same mount follows it the way React follows a re-render — a changed resetKey starts a fresh form, a changed values becomes the new baseline (keeping dirty fields unless asked not to), and a fresh options object whose values content is unchanged resets nothing.

Returns: Form state fields as accessors and the methods.

useWatch(form, name)

One field's current value, under React's hook name.

function useWatch<T extends FormValuesConstraint<T>, K extends keyof T>(
  form: MaybeAccessor<FormController<T>>,
  name: MaybeAccessor<K>,
): Accessor<T[K]>
  • form — Form controller, or an accessor of one; a changed controller is followed on the same mount.
  • name — Field name to watch, or an accessor of it; a changed field is followed on the same mount.

Returns: An accessor of the field value.

useFieldState(form, name)

One field's state (value, error, touched, dirty, valid), under React's hook name.

function useFieldState<T extends FormValuesConstraint<T>>(
  form: MaybeAccessor<FormController<T>>,
  name: MaybeAccessor<keyof T>,
): Accessor<FieldState<T[keyof T]>>
  • form — Form controller, or an accessor of one; a changed controller is followed on the same mount.
  • name — Field name, or an accessor of it; a changed field is followed on the same mount.

Returns: An accessor of the field state.

useProfileForm(options)

Owns load → edit → submit → publish for the signed-in user's profile, under React's hook name.

Same-account background updates refresh untouched fields but preserve dirty controls. Session ownership comes from the auth client, independently of mutable profile fields; an explicit getIdentity adds the caller's identity check. Submission snapshots the registered values before asynchronous validation, sends only changed fields through toPatch, and uses the auth client's configured updateProfile transport. The saved server response becomes the clean baseline; edits made while saving remain dirty. No request is made for a patch with no fields. A failed request retains the edits and the shared user.

function useProfileForm<TUser, TValues extends FormValuesConstraint<TValues>>(
  options: UseProfileFormOptions<TUser, TValues>,
): UseProfileFormResult<TUser, TValues>
  • options — Controlled defaults, identity and wire adapters, optional cache/navigation callback.

Returns: Form state, typed control bindings, native submit binding and save error.

useRouterInstance()

The router from the nearest MoleculeProvider (config.router), under React's hook name.

function useRouterInstance(): Router

Returns: The router instance.

useLinkRouter(to)

The router a link navigates through, under React's hook name: the router from the nearest MoleculeProvider, or null for a URL outside the app when there is none. The browser, or on a device the URL handler, opens such a URL, so a link to it renders in an app with no router (a widget, a static page). A link to an app path still fails without one: that is how an app that forgot to mount its router finds out.

Link uses it. With a destination it answers for that one and follows it while the component lives. Without one it returns a function to call with the destination wherever it is known; call it in component setup, which reads the context once.

function useLinkRouter(to: MaybeAccessor<string>): Accessor<Router | null>
  • to — The link's destination: an app path or a URL, or an accessor of one.

Returns: An accessor of the router the link navigates through, or null for a URL outside the app with no router provided.

useRouter()

Routing state and actions, under React's hook name.

function useRouter(): UseRouterResult

Returns: Location, params and query as accessors; the navigation actions.

useLocation()

The current location, under React's hook name.

function useLocation(): Accessor<RouteLocation>

Returns: Accessor for the current route location.

useParams()

The current route's path parameters, under React's hook name.

function useParams<T extends Record<string, string> = RouteParams>(): Accessor<T>

Returns: Accessor for the route params.

useQuery()

The parsed query parameters, under React's hook name.

function useQuery<T extends QueryParams = QueryParams>(): Accessor<T>

Returns: Accessor for the query params.

useNavigate()

A function that navigates, under React's hook name. It does not subscribe to route changes: navigation needs the instance, not the location.

function useNavigate(): (path: string, options?: NavigateOptions) => void

Returns: The navigate function.

useIsActive(path, exact)

Whether a path matches the current route, under React's hook name.

function useIsActive(path: MaybeAccessor<string>, exact?: MaybeAccessor<boolean>): Accessor<boolean>
  • path — The path to check. May be an accessor: a changed path (or exact) recomputes the match on the same mount, the way React re-renders useIsActive.
  • exact — Whether to match exactly (default false). May be an accessor.

Returns: Accessor for whether the path is active.

useListRoute(options)

URL-backed pagination, filters and selected views, under React's hook name: the page, the filters and the view live in the URL only, so a reload, a shared link and Back all show the same list. Built on resolveListRoute from @molecule/app-routing, so every framework binding returns the same result.

A signed-out visit to a view with requiresAuth replaces the entry with options.auth.redirectTo, carrying state.returnTo; until auth is confirmed canLoad() is false.

The options may be an accessor: a new auth status re-resolves the list on the same component, the way React re-renders useListRoute.

function useListRoute<Filter extends string = string, Selection extends string = string>(
  options?: MaybeAccessor<ListRouteOptions<Filter, Selection>>,
): UseListRouteResult<Filter, Selection>
  • options — List options (or an accessor of them): filter sources, view paths, pagination and optional auth readiness.

Returns: Each list-state field as an accessor, and the link builder and navigation actions as plain functions.

useConsumedSearchParam(name)

Takes a one-time credential (a reset token, an OAuth code) out of the URL and keeps it in memory, under React's hook name, through whichever routing bond the app wired. The parameter is removed with a replace navigation that keeps the path, the hash, the other query values and the location state; the value survives later query-only navigation, Back to an entry restores the value consumed there, and a new value arriving on the same mounted route is consumed too.

function useConsumedSearchParam(name: string): [string, (value: string) => void]
  • name — The query key to consume, for example token or code.

Returns: The tuple the binding's tuples use: the consumed value at index 0 as a live getter ('' before the parameter was ever present) and the setter at index 1 (a form clears it after a successful submit).

createRouter()

Create router primitives for navigation state and actions.

function createRouter(): UseRouterResult

Returns: Router primitives object

useMatch(pattern)

Create a match accessor for a path pattern.

function useMatch(pattern: string): Accessor<boolean>
  • pattern — Path pattern to match

Returns: Accessor indicating if current path matches

createIsActive(path, exact)

Create a reactive boolean accessor that tracks whether a given path is active.

Unlike useMatch which only accepts a static pattern, this factory returns a signal that re-evaluates on every route change and supports the exact parameter from the router's isActive method.

function createIsActive(path: string, exact?: boolean): Accessor<boolean>
  • path — Path to check against the current location
  • exact — Whether to require an exact match (default: false)

Returns: Accessor<boolean> that is true when the path is active

createRouterHelpers()

Creates a router helpers.

function createRouterHelpers(): {
  navigate: (path: string, options?: NavigateOptions) => void
  navigateTo: (
    name: string,
    params?: RouteParams,
    query?: QueryParams,
    options?: NavigateOptions,
  ) => void
  back: () => void
  forward: () => void
  getLocation: () => RouteLocation
  getParams: () => RouteParams
  getQuery: () => QueryParams
  isActive: (path: string) => boolean
}

Returns: The created result.

createRouterFromInstance(router)

Create router primitives from a specific router.

function createRouterFromInstance(router: Router): UseRouterResult
  • router — Router instance

Returns: Router primitives

createSignup()

Creates a signup primitive with async state tracking.

function createSignup<T = unknown>(): CreateSignupReturn<T>

Returns: Signup state and action

useSignup()

User registration with async state tracking, under React's hook name.

function useSignup<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(): UseSignupReturn<T, TRegister>

Returns: Signup state (status, value, error as accessors) and the controls.

createStore(config)

Create a reactive store using Solid signals.

function createStore<T extends object>(config: StoreConfig<T>): Store<T>
  • config — Store configuration

Returns: Store instance

useStateProvider()

The state provider from the nearest MoleculeProvider (config.state), under React's hook name.

The context comes from config.state — which supplies the provider bonded under @molecule/app-state by default, so a scaffolded app needs no state entry.

function useStateProvider(): Accessor<StateProvider>

Returns: Accessor for the state provider from context.

useStore(store, options)

Subscribe to a store with an optional selector and equality function, under React's hook name.

The store is the argument, so this hook needs NO StateProvider: it reads store.getState() and subscribes with store.subscribe(), and never touches the state context. A store minted outside the state bond is as valid here as one @molecule/app-state's createStore() made.

function useStore<T>(
  store: MaybeAccessor<Store<T>>,
  options?: MaybeAccessor<UseStoreOptions<T, T>>,
): Accessor<T>
  • store — The store to subscribe to. May be an accessor: a changed store re-subscribes and reads the new store's state on the same mount, the way React re-renders useStore.
  • options — Selector and equality function. May be an accessor; both fields are read at use, and the previous selection survives an argument change (React's ref) so equalityFn keeps the equal result.

Returns: Accessor for the selected state.

useSetStore(store)

The store's setState function, under React's hook name.

function useSetStore<T>(store: Store<T>): Store<T>['setState']
  • store — The store to get setState from.

Returns: The setState function.

useStoreAction(store, action)

A function bound to a store's setState/getState, under React's hook name.

The action factory runs on every CALL, so it always reads fresh state.

function useStoreAction<T, Args extends unknown[], R>(
  store: Store<T>,
  action: (setState: Store<T>['setState'], getState: Store<T>['getState']) => (...args: Args) => R,
): (...args: Args) => R
  • store — The store to bind to.
  • action — Receives setState and getState, returns the callable.

Returns: The bound action function.

createSignalStore(initial)

Create a simple signal-based store without provider.

function createSignalStore<T>(initial: T): [Accessor<T>, (value: T | ((prev: T) => T)) => void]
  • initial — Initial state

Returns: The created instance.

createPersistedStore(key, initial, storage)

Create a persisted signal store.

function createPersistedStore<T>(
  key: string,
  initial: T,
  storage: StorageAdapter,
): [Accessor<T>, (value: T | ((prev: T) => T)) => void]
  • key — Storage key
  • initial — Initial value
  • storage — Storage adapter (required - use localStorage, sessionStorage, or @molecule/app-storage)

Returns: Tuple of accessor and setter

createStateHelpers()

Creates a state helpers.

function createStateHelpers(): {
  createStore: <T extends object>(config: StoreConfig<T>) => Store<T>
}

Returns: The created result.

createStateHelpersFromProvider(provider)

Creates a state helpers from provider.

function createStateHelpersFromProvider(provider: StateProvider): {
  createStore: <T extends object>(config: StoreConfig<T>) => Store<T>
}
  • provider — The provider implementation.

Returns: The created result.

useStorageProvider()

The storage provider from the nearest MoleculeProvider (config.storage), under React's hook name.

function useStorageProvider(): StorageProvider

Returns: The storage provider from context.

useStorageValue(key, options)

One storage key as reactive state, under React's hook name.

A read that started before a local write lands is discarded, so a slow backend never replaces a newer value. With sync, the provider's own subscription delivers another tab's writes.

function useStorageValue<T>(
  key: MaybeAccessor<string>,
  options?: MaybeAccessor<UseStorageValueOptions<T>>,
): UseStorageValueResult<T>
  • key — Storage key. May be an accessor: a changed key starts over (default value shown, loading, error cleared) and loads its own value on the same mount, the way React re-renders useStorageValue.
  • options — Default value and cross-tab sync. May be an accessor; both fields are read at use, and only a real change of key or sync re-subscribes.

Returns: The value, loading and error state as accessors, and the mutators.

useStoragePreference(key, options)

One persisted preference through the module-singleton preference store (getPreferenceStore() over the BONDED provider — not the context), under React's hook name.

A render-time value is available immediately when the bonded provider can answer synchronously, and an asynchronous provider's hydration CONVERGES onto the same accessor without a remount. Ordering is the store's: a read that started before a newer write, remove or external change is discarded.

Pass null for key while the real key is unknown: the hook then behaves as local state around defaultValue and persists nothing.

function useStoragePreference<T = unknown>(
  key: MaybeAccessor<string | null | undefined>,
  options?: MaybeAccessor<UseStoragePreferenceOptions<T>>,
): UseStoragePreferenceResult<T>
  • key — The storage key, or null when there is nothing to persist. May be an accessor: a changed key re-seeds, re-subscribes and re-hydrates on the same mount, the way React re-renders useStoragePreference.
  • options — defaultValue, reported until the provider supplies one. May be an accessor; the default is read at use.

Returns: The value, its mutators, and whether it is definite yet.

useStorage()

The provider's storage operations as stable functions, no reactive state — under React's hook name.

function useStorage(): {
  get: <T>(key: string) => Promise<T | null>
  set: <T>(key: string, value: T) => Promise<void>
  remove: (key: string) => Promise<void>
  clear: () => Promise<void>
  keys: () => Promise<string[]>
}

Returns: get, set, remove, clear and keys, straight through the provider.

createStorageValue(key, defaultValue)

Create a storage value primitive.

function createStorageValue<T>(
  key: string,
  defaultValue?: T,
): {
  value: () => T | undefined
  loading: () => boolean
  error: () => Error | null
  set: (value: T) => Promise<void>
  remove: () => Promise<void>
  refresh: () => Promise<T | undefined>
}
  • key — Storage key
  • defaultValue — Default value if not found

Returns: Storage value accessor and actions

createStorage()

Create storage primitives.

function createStorage(): {
  get: <T>(key: string) => Promise<T | null>
  set: <T>(key: string, value: T) => Promise<void>
  remove: (key: string) => Promise<void>
  clear: () => Promise<void>
  keys: () => Promise<string[]>
}

Returns: Storage methods

usePersistedSignal(key, defaultValue)

Create a persisted signal that syncs with storage.

function usePersistedSignal<T>(
  key: string,
  defaultValue: T,
): [Accessor<T | undefined>, (value: T | ((prev: T | undefined) => T)) => void]
  • key — Storage key
  • defaultValue — Default value

Returns: Tuple of accessor and setter

createStorageHelpers()

Create storage helpers from context.

function createStorageHelpers(): {
  get: <T>(key: string) => Promise<T | null>
  set: <T>(key: string, value: T) => Promise<void>
  remove: (key: string) => Promise<void>
  clear: () => Promise<void>
  keys: () => Promise<string[]>
}

Returns: Storage helper functions

createStorageFromProvider(storage)

Create storage primitives from a specific provider.

function createStorageFromProvider(storage: StorageProvider): {
  get: <T>(key: string) => Promise<T | null>
  set: <T>(key: string, value: T) => Promise<void>
  remove: (key: string) => Promise<void>
  clear: () => Promise<void>
  keys: () => Promise<string[]>
}
  • storage — Storage provider

Returns: Storage methods

createStorageValueFromProvider(storage, key, defaultValue)

Create storage value primitive from a specific provider.

function createStorageValueFromProvider<T>(
  storage: StorageProvider,
  key: string,
  defaultValue?: T,
): {
  value: () => T | undefined
  loading: () => boolean
  error: () => Error | null
  set: (value: T) => Promise<void>
  remove: () => Promise<void>
}
  • storage — Storage provider
  • key — Storage key
  • defaultValue — Default value

Returns: Storage value accessor and actions

useThemeProvider()

The theme provider from the nearest MoleculeProvider (config.theme), under React's hook name.

function useThemeProvider(): ThemeProvider

Returns: The theme provider instance.

useTheme()

Theme state and actions, under React's hook name.

function useTheme(): UseThemeResult

Returns: Theme fields as accessors and the actions.

useCurrentTheme()

The whole current theme object, under React's hook name.

function useCurrentTheme(): Accessor<Theme>

Returns: Accessor for the current theme.

useThemeMode()

The theme mode (light/dark), under React's hook name.

function useThemeMode(): Accessor<'light' | 'dark'>

Returns: Accessor for the current mode.

useThemeColors()

The current theme's color palette, under React's hook name.

function useThemeColors(): Accessor<ThemeColors>

Returns: Accessor for the current theme's colors.

createTheme()

Create theme primitives for theme state and actions.

function createTheme(): ThemePrimitives

Returns: The created instance.

useMode()

Create a mode accessor.

function useMode(): Accessor<'light' | 'dark'>

Returns: Accessor for current mode

useThemeName()

Create a theme name accessor.

function useThemeName(): Accessor<string>

Returns: Accessor for current theme name

createThemeHelpers()

Creates a theme helpers.

function createThemeHelpers(): {
  getTheme: () => Theme
  setTheme: (name: string) => void
  getMode: () => 'light' | 'dark'
  toggleMode: () => void
  getAvailableThemes: () => Theme[]
}

Returns: The created result.

createThemeFromProvider(provider)

Create theme primitives from a specific provider.

function createThemeFromProvider(provider: ThemeProvider): ThemePrimitives
  • provider — Theme provider

Returns: Theme primitives

createThemeColors(theme)

Create a colors accessor derived from a theme accessor.

function createThemeColors(theme: Accessor<Theme>): Accessor<ThemeColors>
  • theme — Theme accessor (e.g. from createTheme().theme)

Returns: Accessor for the current theme colors

applyThemeToDocument() (deprecated)

Deprecated: The theme bond (e.g. @molecule/app-theme-css-variables) owns document styling; this duplicates it. React's bindings never touch the document — drive the theme provider (useTheme) and let the bond style.

Apply theme CSS variables to document.

function applyThemeToDocument(): void

useVerifyPaymentReturn(options)

Reads the payment id a provider put in the return URL and confirms the purchase server-side with POST /users/:id/verify-payment/:provider, under React's hook name.

Session cookies are host-only on the app's origin, so the verification must run as a same-origin call from a loaded app page. It waits for auth to hydrate first, runs at most once per transaction id per page, and stays idle on pages reached normally (no id in the URL).

If the component unmounts while the request is in flight, a verified purchase still refreshes the cached profile (the plan is paid for), but the hook calls neither onVerified nor onError and leaves the URL alone. A failure after unmount is logged instead.

function useVerifyPaymentReturn(
  options?: UseVerifyPaymentReturnOptions,
): UseVerifyPaymentReturnResult
  • options — Provider fallback + lifecycle callbacks.

Returns: The verification state, as accessors, and retry.

createVersion()

Create version primitives for tracking app updates.

function createVersion(): UseVersionResult

Returns: Version primitives object

useVersion()

Version and update state, under React's hook name: the state fields as accessors over the bonded provider's snapshot (refreshed on the same six events React subscribes) and the actions as plain functions.

Uses module-level getProvider() — version is a singleton, not context-provided.

function useVersion(): UseVersionResult

Returns: Version state and action methods.

StateProvider(props)

Provider for state management, as @molecule/app-react's StateProvider.

function StateProvider(props: StateProviderProps): JSX.Element
  • props — Component props (see StateProviderProps).

Returns: The provided tree.

AuthProvider(props)

Provider for authentication, alone.

The counterpart of React's AuthProvider: it supplies the auth client under its context and, by default, holds rendering until the client has decided the session, so a returning visitor's first render reads the restored user rather than null. Pass awaitSession={false} for a deliberately ungated shell.

function AuthProvider<T = unknown>(props: AuthProviderProps<T>): JSX.Element
  • props — Component props (see AuthProviderProps).

Returns: The auth context provider wrapping the children.

ThemeProvider(props)

Provider for theming, as @molecule/app-react's ThemeProvider.

function ThemeProvider(props: ThemeProviderProps): JSX.Element
  • props — Component props (see ThemeProviderProps).

Returns: The provided tree.

RouterProvider(props)

Provider for routing, as @molecule/app-react's RouterProvider: the router and, from a routing bond that has one, the routed view RoutedView renders (null without one). A routing bond renders it for the app, so app code rarely mounts it by hand.

function RouterProvider(props: RouterProviderProps): JSX.Element
  • props — Component props (see RouterProviderProps).

Returns: The provided tree.

I18nProvider(props)

Provider for internationalization, as @molecule/app-react's I18nProvider.

function I18nProvider(props: I18nProviderProps): JSX.Element
  • props — Component props (see I18nProviderProps).

Returns: The provided tree.

HttpProvider(props)

Provider for the HTTP client, as @molecule/app-react's HttpProvider.

function HttpProvider(props: HttpProviderProps): JSX.Element
  • props — Component props (see HttpProviderProps).

Returns: The provided tree.

StorageProvider(props)

Provider for storage, as @molecule/app-react's StorageProvider.

function StorageProvider(props: StorageProviderProps): JSX.Element
  • props — Component props (see StorageProviderProps).

Returns: The provided tree.

LoggerProvider(props)

Provider for logging, as @molecule/app-react's LoggerProvider.

function LoggerProvider(props: LoggerProviderProps): JSX.Element
  • props — Component props (see LoggerProviderProps).

Returns: The provided tree.

WorkspaceProvider(props)

Provider for the IDE workspace, as @molecule/app-react's WorkspaceProvider.

function WorkspaceProvider(props: WorkspaceProviderProps): JSX.Element
  • props — Component props (see WorkspaceProviderProps).

Returns: The provided tree.

EditorProvider(props)

Provider for the code editor, as @molecule/app-react's EditorProvider.

function EditorProvider(props: EditorProviderProps): JSX.Element
  • props — Component props (see EditorProviderProps).

Returns: The provided tree.

PreviewProvider(props)

Provider for the live preview, as @molecule/app-react's PreviewProvider.

function PreviewProvider(props: PreviewProviderProps): JSX.Element
  • props — Component props (see PreviewProviderProps).

Returns: The provided tree.

MoleculeProvider(props)

Combined provider for every molecule service, as @molecule/app-react's MoleculeProvider.

Only the services passed are provided, except state, which falls back to the state provider bonded under @molecule/app-state (set by setupAllDefaultBonds() or a state bond) so useStore() works without a state prop. Given auth, it renders the app only once the session is decided (awaitSession, default true), with sessionFallback meanwhile.

The services may also come inside one config object, the deprecated form, with the same defaults; mixing the two is a type error.

function MoleculeProvider(props: MoleculeProviderProps | MoleculeConfigProviderProps): JSX.Element
  • props — Component props (see MoleculeProviderProps).

Returns: The nested provider tree wrapping children.

resolveNode(read)

Solid's children() helper, with every function in the node read in a scope of its own. children() reads a node and every function in it in one memo, so a change inside what an accessor item returned (the <Show> at the root of () => <Row />) calls the accessor again and replaces the row, losing its state. Here an item is created once and kept while it stays: a list is mapped by item identity, so adding a row to a <For> of accessor rows creates only that row. Components are created where this is called and disposed with that scope, as with children(). Use it wherever a component resolves a node prop (molecule's Solid packages do not import children from solid-js).

function resolveNode(read: () => unknown): ChildrenReturn
  • read — Reads the node prop (() => local.footer).

Returns: The resolved node, with toArray() as children() gives it.

RoutedView()

Renders the matched child route, through whichever routing bond the app wired. A layout or guard renders it where its page goes when it was given no children, so the component imports no router library.

function RoutedView(): JSX.Element

Returns: The routing bond's routed view.

SessionReady(props)

Renders its children once createAuth().state().status has left 'loading' — the session is decided (signed in, signed out, or 'unavailable') — and fallback until then. It never redirects. An unavailable session is unconfirmed and may still have a null user.

With the bundled JWT client, a stored token AND cached user restore synchronously, so this boundary renders immediately. Token-only and cookie-only sessions need an asynchronous current-user request. Until it answers, createAuth().user() is null, so a public page that renders a signed-in action at once lets that action run against "signed out": a Follow button whose handler starts with if (!user()) return ignores the click, one that redirects to /login signs the visitor out of the flow. MoleculeProvider given auth renders this around the app by default (awaitSession), so every page's first render reads the restored user when restoration succeeds.

A visitor with no session candidate settles synchronously without a request. Must render inside MoleculeProvider with auth configured. A client that nobody initialized starts its restore on this first read. The bundled JWT client bounds each auth request (default 10 seconds), then settles as 'unavailable' on timeout. Custom clients must also settle their initial session status.

Route-level redirects for signed-in-only pages stay with createAuthGuard (./primitives/auth.js).

function SessionReady(props: ParentProps<SessionReadyProps>): JSX.Element
  • props — SessionReadyProps.

Returns: The children once the session is decided, otherwise the fallback.

Constants

StateContext

Internal contexts for molecule providers.

const StateContext: Context<StateProvider | undefined>

AuthContext

const AuthContext: Context<AuthClient<unknown, Record<never, never>> | undefined>

ThemeContext

const ThemeContext: Context<ThemeProvider | undefined>

RouterContext

const RouterContext: Context<Router | undefined>

I18nContext

const I18nContext: Context<I18nProvider | undefined>

HttpContext

const HttpContext: Context<HttpClient | undefined>

StorageContext

const StorageContext: Context<StorageProvider | undefined>

LoggerContext

const LoggerContext: Context<LoggerProvider | undefined>

WorkspaceContext

const WorkspaceContext: Context<WorkspaceProvider | undefined>

EditorContext

const EditorContext: Context<EditorProvider | undefined>

PreviewContext

const PreviewContext: Context<PreviewProvider | undefined>

useDevice

Device information, React's useDevice under the same name: one static snapshot of the bonded device provider (supports, isOnline and isStandalone stay live functions reading the provider).

const useDevice: () => UseDeviceResult

Returns: Device information and utility methods

Injection Notes

Requirements

Peer dependencies:

  • @molecule/app-ai-chat ^1.8.0 (optional)
  • @molecule/app-ai-models ^1.0.1 (optional)
  • @molecule/app-auth ^3.0.0 (optional)
  • @molecule/app-code-editor ^1.0.1 (optional)
  • @molecule/app-device ^1.0.1
  • @molecule/app-forms ^2.4.0
  • @molecule/app-http ^1.0.1 (optional)
  • @molecule/app-i18n ^1.4.0
  • @molecule/app-ide ^1.1.0 (optional)
  • @molecule/app-live-preview ^1.0.1 (optional)
  • @molecule/app-logger ^1.0.1
  • @molecule/app-platform ^1.0.1
  • @molecule/app-push ^1.0.1 (optional)
  • @molecule/app-routing ^1.4.0
  • @molecule/app-routing-solid-router >=1.4.0 (optional)
  • @molecule/app-state ^1.2.0
  • @molecule/app-storage ^1.1.1
  • @molecule/app-theme ^1.0.1 (optional)
  • @molecule/app-ui ^1.0.1 (optional)
  • @molecule/app-utilities ^1.0.1 (optional)
  • @molecule/app-version ^1.0.1
  • solid-js ^1.8.0

Runtime Dependencies

  • @molecule/app-ai-chat (optional)

  • @molecule/app-ai-models (optional)

  • @molecule/app-auth (optional)

  • @molecule/app-code-editor (optional)

  • @molecule/app-device

  • @molecule/app-forms

  • @molecule/app-http (optional)

  • @molecule/app-i18n

  • @molecule/app-ide (optional)

  • @molecule/app-live-preview (optional)

  • @molecule/app-logger

  • @molecule/app-platform

  • @molecule/app-push (optional)

  • @molecule/app-routing

  • @molecule/app-routing-solid-router (optional)

  • @molecule/app-state

  • @molecule/app-storage

  • @molecule/app-theme (optional)

  • @molecule/app-ui (optional)

  • @molecule/app-utilities (optional)

  • @molecule/app-version

  • solid-js

  • Primitives throw outside MoleculeProvider — and per missing service. It provides ONLY the services you pass; calling createAuth() in a tree whose provider has no auth throws "getAuthClient must be used within a MoleculeProvider with auth configured". Pass the service, don't catch the error.

  • Primitive results are Solid accessors — call them (isAuthenticated(), theme(), user()), never read them bare; a bare theme.colors is a type error, and a bare isAuthenticated is always truthy.

  • Call primitives at component setup (top level of the component function), not inside JSX callbacks, so subscriptions are established once.

  • In-app links are Link (<Link to="/settings">): it navigates through the router with react-router <Link>'s click rules. A bare <a href> reloads the page; a hand-written click handler that calls navigate() breaks ctrl/cmd-click (new tab) unless it repeats those rules.

Use @molecule/app-solid/chat, @molecule/app-solid/ai-models, and @molecule/app-solid/push for those features.

Translations

Translation strings are provided by @molecule/app-locales-solid.