npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

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

About

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

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

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

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

Open Software & Tools

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

© 2026 – Pkg Stats / Ryan Hefner

@molecule/app-angular

v4.0.2

Published

Angular framework bindings for molecule.dev

Readme

@molecule/app-angular

Angular framework bindings for molecule.dev.

Provides Angular-specific services and providers for all molecule core interfaces. This package enables the use of molecule's framework-agnostic interfaces with Angular's idioms (services, DI, RxJS observables, etc.).

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

// main.ts — wire concrete providers into Angular DI:
import { Component, inject } from '@angular/core'
import { bootstrapApplication } from '@angular/platform-browser'
import {
  MoleculeAuthService,
  MoleculeThemeService,
  provideMolecule,
  t,
} from '@molecule/app-angular'
import { createJWTAuthClient } from '@molecule/app-auth'
import { provider as stateProvider } from '@molecule/app-state-zustand'
import { provider as themeProvider } from '@molecule/app-theme-css-variables'

const authClient = createJWTAuthClient({ baseURL: '/api' })

// dashboard.component.ts — inject the Molecule services:
@Component({
  selector: 'app-dashboard',
  template: `
    <div [style.background]="(theme$ | async)?.colors.background">
      <h1>{{ t('dashboard.welcome', {}, { defaultValue: 'Welcome!' }) }}</h1>
      <p>{{ (user$ | async)?.name }}</p>
      <button (click)="logout()">
        {{ t('auth.logout', {}, { defaultValue: 'Log out' }) }}
      </button>
    </div>
  `,
})
export class DashboardComponent {
  // Expose the reactive t() so template bindings re-evaluate on locale change.
  protected readonly t = t

  private authService = inject(MoleculeAuthService)
  private themeService = inject(MoleculeThemeService)

  user$ = this.authService.user$ // Observable<UserProfile | null>
  theme$ = this.themeService.theme$ // Observable<Theme>

  logout(): void {
    void this.authService.logout()
  }
}

// app.component.ts — the root that mounts the dashboard:
@Component({
  selector: 'app-root',
  imports: [DashboardComponent],
  template: '<app-dashboard />',
})
export class AppComponent {}

bootstrapApplication(AppComponent, {
  providers: [
    provideMolecule({
      state: stateProvider,
      auth: authClient,
      theme: themeProvider,
    }),
  ],
})

Session restore: useAuth().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 can be null. A restore failure other than 401/403 never signs out. provideMolecule({ auth }) starts the bundled client's restore when a consumer first reads the session, so the app entry can mount its root without calling initialize(). It holds bootstrap — and so every page's first render — while a token-only or cookie-only restore is undecided; a cached token and user, and a visitor without a session candidate, settle at once. Pass awaitSession: false to render before the restore settles.

Type

framework

Installation

npm install @molecule/app-angular @angular/core @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 rxjs

API

Interfaces

AuthState

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

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

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

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

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

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

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

AuthClient

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

EditorProvider

Code editor provider interface that all editor bond packages must implement. Provides mounting, file management, cursor control, and change subscription.

interface EditorProvider {
  readonly name: string
  mount(element: HTMLElement, config?: EditorConfig): void | Promise<void>
  dispose(): void
  openFile(file: EditorFile): void
  closeFile(path: string): void
  getContent(): string | null
  setContent(path: string, content: string): void
  /** Silently update file content without firing change events or marking dirty. Preserves cursor position. */
  setContentSilent?(path: string, content: string): void
  getCursorPosition(): EditorPosition | null
  setCursorPosition(position: EditorPosition): void
  focus(): void
  onChange(callback: (event: EditorChangeEvent) => void): () => void
  getTabs(): EditorTab[]
  setActiveTab(path: string): void
  updateConfig(config: Partial<EditorConfig>): void
  /** Read the current effective editor configuration. Optional — lets consumers capture a baseline before applying temporary overrides (e.g. mobile viewport tuning). */
  getConfig?(): EditorConfig
  /** Open a side-by-side diff view for a file. Optional — providers may not support this. */
  openDiff?(file: DiffFile): void
  /** Close the diff view and restore the normal editor. */
  closeDiff?(): void
  /** Clear the dirty flag on a tab after a successful save. */
  markSaved?(path: string): void
  /** Promote a preview tab to a permanent tab. */
  pinTab?(path: string): void
  /** Add a type definition or virtual file for module resolution. */
  addExtraLib?(content: string, filePath: string): void
  /** Remove all registered extra libs. */
  clearExtraLibs?(): void
  /** Connect to an LSP server for language intelligence. */
  connectLsp?(wsUrl: string): Promise<void>
  /** Disconnect from the LSP server. */
  disconnectLsp?(): void
  /** Register a callback for when the LSP connection drops unexpectedly. */
  onLspDisconnect?(cb: () => void): void
  /** Set a file resolver for Go to Definition / Peek Definition cross-file navigation. */
  setFileResolver?(
    resolver: (path: string) => Promise<{ content: string; language?: string } | null>,
  ): void
  /** Register a callback for "Fix with AI" requests from the editor (lightbulb quick fix or context menu). Returns an unsubscribe function. */
  onFixWithAI?(callback: (request: FixWithAIRequest) => void): () => void
  /** Get current diagnostics (errors/warnings) for a file from the language service. */
  getDiagnostics?(path: string): EditorDiagnostic[]
}

FormController

Form controller interface.

All form providers must implement this interface.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

FormResetOptions

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

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

FormOptions

Form creation options.

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

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

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

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

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

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

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

HttpClient

HTTP client interface.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

I18nProvider

i18n provider interface.

All i18n providers must implement this interface.

interface I18nProvider {
  /**
   * Gets the current locale.
   */
  getLocale(): string

  /**
   * Sets the current locale.
   *
   * **Fleet contract:** every conformant provider (the core simple provider,
   * `@molecule/api-i18n-simple`, `@molecule/app-i18n-i18next`, and
   * `@molecule/app-i18n-react-i18next`) MUST throw `Error('Locale "<code>"
   * not found')` when `locale` is not registered — via the constructor's
   * `initialLocales`/`locales` config, `addLocale()`, or `addTranslations()`
   * (all three register a locale). It must NOT silently degrade to
   * fallback-locale text while `getLocale()` reports the unregistered code —
   * that divergence makes a misconfigured locale switch indistinguishable
   * from a working one until a user notices the wrong language on screen.
   */
  setLocale(locale: string): Promise<void>

  /**
   * Gets all available locales.
   */
  getLocales(): LocaleConfig[]

  /**
   * Adds a locale.
   */
  addLocale(config: LocaleConfig): void

  /**
   * Removes a locale by code, notifying subscribers so language pickers
   * built on `onLocaleChange` re-render their list. If the removed locale
   * is currently active, the caller is responsible for switching to a
   * fallback (e.g. `'en'`) BEFORE calling this — the provider will not
   * auto-fall-back on its own.
   *
   * Returns `true` if the locale was registered and removed, `false`
   * otherwise.
   */
  removeLocale(code: string): boolean

  /**
   * Adds translations to a locale. Auto-creates the locale if it doesn't exist.
   *
   * **Fleet contract:** merges are DEEP, not a shallow spread — registering
   * two calls (e.g. two modules) that share a top-level namespace key merges
   * their subtrees instead of the second call clobbering the first's nested
   * translations wholesale. `@molecule/api-i18n-simple` implements the same
   * contract on the API side.
   */
  addTranslations(locale: string, translations: Translations, namespace?: string): void

  /**
   * Translates a key with optional interpolation values and pluralization.
   *
   * **Fleet plural contract (matches i18next's own key resolution order):**
   * when `options.count` is provided, the plural-suffixed key
   * (`` `${key}_${pluralForm}` ``, e.g. `item_one`/`item_few`/…, falling back
   * to `` `${key}_other` ``) is looked up FIRST and wins over the base `key`
   * if BOTH are registered. Only when no plural-suffixed key exists at all
   * does resolution fall back to the base key. A catalog that ships both
   * `item` and `item_one`/`item_other` therefore pluralizes identically
   * whichever provider is bonded.
   *
   * @returns The translated string, or the default value / key if not found.
   */
  t: TranslateFunction

  /**
   * Checks if a translation key exists.
   *
   * **Fleet contract:** follows the SAME locale-resolution chain as `t()` —
   * the active locale, then the English fallback — so `exists(key) === true`
   * whenever `t(key)` would render real translated text (not the raw key or
   * an inline `defaultValue`). Do not narrow this to "only the active
   * locale's own catalog"; that made `exists()` return `false` for keys `t()`
   * happily rendered via the English fallback, and the answer differed by
   * provider.
   *
   * @returns `true` if the key has a translation.
   */
  exists(key: string): boolean

  /**
   * Formats a number according to the current locale.
   *
   * @returns The locale-formatted number string.
   */
  formatNumber(value: number, options?: NumberFormatOptions): string

  /**
   * Formats a date according to the current locale.
   *
   * @returns The locale-formatted date string.
   */
  formatDate(value: Date | number | string, options?: DateFormatOptions): string

  /**
   * Formats a relative time (e.g. "2 hours ago").
   *
   * @returns The locale-formatted relative time string.
   */
  formatRelativeTime(value: Date | number, options?: { unit?: Intl.RelativeTimeFormatUnit }): string

  /**
   * Formats a list (e.g. "A, B, and C").
   *
   * @returns The locale-formatted list string.
   */
  formatList(values: string[], options?: { type?: 'conjunction' | 'disjunction' | 'unit' }): string

  /**
   * Subscribes to locale changes.
   *
   * @returns An unsubscribe function.
   */
  onLocaleChange(listener: (locale: string) => void): () => void

  /**
   * Gets a counter that advances for every change `onLocaleChange` announces:
   * a locale switch, a locale-list change, or translations added for a locale
   * `t()` reads (the active locale and the locales it falls back to — English
   * for `createSimpleI18nProvider`). It does NOT advance for a re-registration
   * that leaves every rendered string identical.
   *
   * **Optional — read it only when present.** A consumer that observes the
   * provider through `useSyncExternalStore` (the React hooks do) compares this
   * value across renders, so it also sees a change that happened before its
   * listener existed: a notification fired from a child's or an earlier
   * sibling's layout effect, or while React kept the tree hidden with its
   * effects unmounted. Providers written before this method existed keep the
   * listener-only behaviour; consumers must fall back to counting
   * notifications.
   *
   * Reads must be side-effect free, and the value must never decrease.
   *
   * @returns The provider's current revision.
   */
  getRevision?(): number

  /**
   * Gets the text direction for the current locale.
   *
   * @returns `'ltr'` or `'rtl'`.
   */
  getDirection(): 'ltr' | 'rtl'

  /**
   * Checks if a translation key exists (alias for exists).
   */
  hasKey?(key: string): boolean

  /**
   * Checks if the provider is ready.
   */
  isReady?(): boolean

  /**
   * Registers a callback for when the provider is ready.
   */
  onReady?(callback: () => void): () => void

  /**
   * Registers a lazily-loaded content module for automatic reload on locale changes.
   * All registered content is reloaded during `setLocale()` before listeners fire,
   * ensuring content is available on the first re-render with no flash.
   *
   * Idempotent: registering the same module name twice is a no-op.
   */
  registerContent?(module: string, loader: (locale: string) => Promise<void>): void
}

WorkspaceProvider

Workspace provider interface that all IDE workspace bond packages must implement. Manages panel layout, sizing, and visibility.

interface WorkspaceProvider {
  /** Provider name identifier. */
  readonly name: string

  /** Returns the current workspace layout. */
  getLayout(): WorkspaceLayout

  /**
   * Returns the full current workspace state (layout, active panel, collapsed
   * panels, fullscreen), so a framework binding that mounts after earlier
   * changes reads them without waiting for the next `subscribe` callback.
   * Return the same object until the state changes.
   */
  getState?(): WorkspaceState

  /** Sets the entire workspace layout. */
  setLayout(layout: WorkspaceLayout): void

  /** Toggles visibility of a panel by ID. */
  togglePanel(panelId: PanelId): void

  /** Resizes a panel to the given size. */
  resizePanel(panelId: PanelId, size: number): void

  /** Sets the active (focused) panel. */
  setActivePanel(panelId: PanelId): void

  /**
   * Subscribes to workspace state changes.
   *
   * @returns An unsubscribe function.
   */
  subscribe(callback: (state: WorkspaceState) => void): () => void

  /** Resets layout to the default configuration. */
  resetLayout(): void
}

PreviewProvider

Provider interface for preview.

interface PreviewProvider {
  readonly name: string
  /**
   * Sets the preview's load target and bumps {@link PreviewState.loadNonce} so
   * the renderer (re)loads it. No-ops when `url` repeats the previous `setUrl`
   * call — to force a reload of the SAME url, call {@link PreviewProvider.refresh}
   * instead.
   * @param url - The new URL to load in the preview.
   */
  setUrl(url: string): void
  getUrl(): string
  refresh(): void
  setDevice(device: DeviceFrame): void
  getState(): PreviewState
  navigateTo(path: string): void
  /**
   * Records a navigation the running preview reported (via the
   * `molecule:navigate` message — see the interface `@remarks`). Updates the
   * current location for the URL bar; invalid or non-`http(s)` URLs are ignored,
   * and the host's internal cache-buster ({@link PREVIEW_CACHE_BUSTER_PARAM}) is
   * stripped so it never leaks into the URL bar or the Back/Forward history.
   * @param url - The preview's new location (absolute `http`/`https` URL).
   * @param isReplace - Whether the preview REPLACED its current history entry (a
   * `replaceState` redirect/canonicalization) rather than ADDING one (a
   * `pushState`). A replace swaps the current entry in place and PRESERVES the
   * forward stack (so Forward stays enabled); a push (the default) opens a new
   * branch and truncates forward. Defaults to `false`.
   */
  recordNavigation(url: string, isReplace?: boolean): void
  /**
   * Navigates the preview to the previous entry in its navigation history (the
   * history is built from {@link PreviewProvider.recordNavigation} and
   * {@link PreviewProvider.setUrl} calls). This is a CLIENT-SIDE history move,
   * NOT a reload: it updates {@link PreviewState.currentUrl} + the nav flags and
   * leaves {@link PreviewState.url}/`loadNonce` untouched. The renderer posts a
   * `molecule:nav-command` so the preview runs its own `history.back()`,
   * preserving scroll position + SPA state. No-op when
   * {@link PreviewState.canGoBack} is `false`.
   */
  back(): void
  /**
   * Navigates the preview to the next entry in its navigation history — a
   * client-side history move (see {@link PreviewProvider.back}), not a reload.
   * No-op when {@link PreviewState.canGoForward} is `false`.
   */
  forward(): void
  /**
   * Reports whether the preview can navigate back in its history.
   * @returns Whether a Back navigation is currently possible.
   */
  canGoBack(): boolean
  /**
   * Reports whether the preview can navigate forward in its history.
   * @returns Whether a Forward navigation is currently possible.
   */
  canGoForward(): boolean
  subscribe(callback: (state: PreviewState) => void): () => void
  openExternal(): void
}

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
}

LoggerProvider

Logger provider interface that all logger bond packages must implement. Creates and manages logger instances and global log configuration.

interface LoggerProvider {
  /**
   * Gets a logger by name, or the root logger if no name given.
   */
  getLogger(name?: string): Logger

  /**
   * Creates a named logger.
   */
  createLogger(nameOrConfig: string | LoggerConfig, config?: LoggerConfig): Logger

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

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

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

  /**
   * Enables logging.
   */
  enable(): void

  /**
   * Disables logging.
   */
  disable(): void

  /**
   * Checks if logging is enabled.
   *
   * @returns `true` if logging is currently enabled.
   */
  isEnabled(): boolean
}

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

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
}

StateProvider

State provider interface that all state management bond packages must implement. Provides the store creation factory.

interface StateProvider {
  /**
   * Creates a new store.
   */
  createStore<T>(config: StoreConfig<T>): Store<T>
}

StorageProvider

Storage provider interface.

All storage providers must implement this interface.

interface StorageProvider {
  /**
   * Gets a value from storage.
   */
  get<T = unknown>(key: string): Promise<T | null>

  /**
   * Sets a value in storage.
   */
  set<T = unknown>(key: string, value: T): Promise<void>

  /**
   * Removes a value from storage.
   */
  remove(key: string): Promise<void>

  /**
   * Clears all values from storage.
   */
  clear(): Promise<void>

  /**
   * Gets all keys in storage.
   */
  keys(): Promise<string[]>

  /**
   * Gets multiple values from storage.
   */
  getMany?<T = unknown>(keys: string[]): Promise<Map<string, T | null>>

  /**
   * Sets multiple values in storage.
   */
  setMany?<T = unknown>(entries: Array<[string, T]>): Promise<void>

  /**
   * Removes multiple values from storage.
   */
  removeMany?(keys: string[]): Promise<void>

  /**
   * Reads a value synchronously.
   *
   * Optional: only a provider backed by a SYNCHRONOUS store (browser
   * `localStorage`, an in-memory map) can answer without I/O. A render-time
   * caller reads through `getPreferenceStore()`, which uses this method to see
   * the persisted value on the first paint; a provider without it is read
   * through {@link StorageProvider.get} and subscribers update when the value
   * lands.
   * @param key - The storage key.
   * @returns The stored value, or `null` when it is absent, unreadable or corrupt.
   */
  getSync?<T = unknown>(key: string): T | null

  /**
   * Subscribes to changes made to a key OUTSIDE this provider instance — for
   * example another browser tab's `localStorage` write.
   *
   * Writes made through the same provider instance do not re-emit here; a
   * synchronous caller observes them through `getPreferenceStore()`'s own
   * subscribers.
   * @param key - The storage key.
   * @param listener - Called with the new value, or `null` when it was removed.
   * @returns A function that stops the subscription.
   */
  subscribe?(key: string, listener: (value: unknown) => void): () => void
}

ThemeProvider

Manages theme state including the active theme, mode toggling, and change subscriptions.

interface ThemeProvider {
  /**
   * Returns the currently active theme.
   */
  getTheme(): Theme

  /**
   * Sets the active theme by reference or by name.
   *
   * @param theme - A `Theme` object or a theme name string to activate.
   */
  setTheme(theme: Theme | string): void

  /**
   * Toggles between light and dark mode for the active theme.
   */
  toggleMode(): void

  /**
   * Subscribes to theme changes. The callback fires whenever
   * `setTheme()` or `toggleMode()` is called.
   *
   * @param callback - Invoked with the new theme after each change.
   * @returns An unsubscribe function.
   */
  subscribe(callback: (theme: Theme) => void): () => void

  /**
   * Returns all registered themes. Optional — not all providers
   * support multiple themes.
   */
  getThemes?(): Theme[]

  /**
   * Returns the theme a render WITHOUT a browser produces — a server or
   * build-time render, which has no storage and no `prefers-color-scheme`
   * to read. A hydrating client renders this theme first, so its markup
   * matches what the server sent, and switches to `getTheme()` right
   * after. Optional — a provider whose theme cannot differ between the two
   * need not implement it.
   */
  getServerTheme?(): Theme
}

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
}

SlotReader

Reads whether a slot renders anything; see {@link usePlacement}. A capture that also holds the port's own text before the slot (<span #c>{{ label }}<ng-content /></span>) passes how many leading child nodes are the port's: one per interpolation or static text before the <ng-content>.

interface SlotReader {
  (capture: Node | null | undefined, ownLeadingNodes?: number): boolean
  /**
   * The slot's React children (`React.Children.toArray(slot)`): its elements
   * and its text that is not template indentation, in order, wherever
   * {@link placeContent} rendered them. A `*molLazy` slot is one child, its
   * anchor comment, whether or not its content is stamped: hide that node to
   * hide the child, and its content is destroyed until it shows again.
   *
   * The same array comes back while the children are the same nodes, so it can be kept in a
   * signal (`children.set(hasContent.nodes(capture))`) and passed to a binding: the placement
   * function runs after every render, and a new array each time would render again forever.
   *
   * @param capture - The element Angular projected the content into.
   * @returns The children.
   */
  nodes(capture: Node | null | undefined): readonly Node[]
}
  • capture — The element Angular projected the content into.
  • ownLeadingNodes — How many of the capture's first child nodes the port renders itself (default 0).

Returns: Whether the slot has content.

UsePromiseState

The state of the latest {@link usePromise} call.

interface UsePromiseState<T> {
  /** `'idle'`, `'pending'`, `'resolved'` or `'rejected'`. */
  status: PromiseStatus
  /** The resolved value, `null` before the first resolution and after a reset. */
  value: T | null
  /** The rejection of the latest call, or the cancel message as an Error. */
  error: Error | null
  /** Marks a pending call rejected; its late result is not shown. */
  cancel: (message?: string) => void
  /** Returns the state to idle and clears value and error. */
  reset: () => void
}

UseOptimisticValueResult

What {@link useOptimisticValue} returns: the state to render (as signals — the same fields React's result carries as plain values) and the two ways to change it.

interface UseOptimisticValueResult<T> {
  /** The newest chosen value, or the server's value when nothing is saving. */
  readonly value: Signal<T>

  /** Whether a save is running or waiting to run. */
  readonly pending: Signal<boolean>

  /** The failure of the newest change, after the value went back; `null` otherwise. */
  readonly error: Signal<unknown>
  /**
   * Shows `next` at once and saves it, after any save already running.
   *
   * @param next - The value the person chose.
   */
  set: OptimisticValue<T>['set']

  /**
   * Like `set`, computed from the value shown now (`update((on) => !on)`).
   *
   * @param change - Computes the next value from the value shown now.
   */
  update: OptimisticValue<T>['update']
}

UseLoginReturn

Return type for {@link useLogin}.

interface UseLoginReturn<T = unknown> {
  /** The login state: `'idle'`, `'pending'`, `'resolved'` or `'rejected'`. */
  readonly status: UsePromiseState<AuthResult<T>>['status']
  /** The resolved session, `null` before the first resolution. */
  readonly value: UsePromiseState<AuthResult<T>>['value']
  /** The failure of the latest login. */
  readonly error: UsePromiseState<AuthResult<T>>['error']
  /**
   * Runs one tracked login.
   *
   * @param credentials - The credentials to sign in with.
   * @returns The session.
   */
  login: (credentials: LoginCredentials) => Promise<AuthResult<T>>
  /** Returns the state to idle. */
  reset: () => void
}

UseSignupReturn

Return type for {@link useSignup}.

interface UseSignupReturn<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  /** The signup state. */
  readonly status: UsePromiseState<AuthResult<T>>['status']
  /** The resolved session, `null` before the first resolution. */
  readonly value: UsePromiseState<AuthResult<T>>['value']
  /** The failure of the latest signup. */
  readonly error: UsePromiseState<AuthResult<T>>['error']
  /**
   * Runs one tracked registration (and signs the account in).
   *
   * @param data - The registration data.
   * @returns The session.
   */
  signup: (data: RegisterData<TRegister>) => Promise<AuthResult<T>>
  /** Returns the state to idle. */
  reset: () => void
}

UseChangePasswordReturn

Return type for {@link useChangePassword}.

interface UseChangePasswordReturn {
  /** The change state. */
  readonly status: UsePromiseState<void>['status']
  /** The failure of the latest change. */
  readonly error: UsePromiseState<void>['error']
  /**
   * Runs one tracked password change.
   *
   * @param oldPassword - The current password.
   * @param newPassword - The new password.
   * @returns Resolves once changed.
   */
  changePassword: (oldPassword: string, newPassword: string) => Promise<void>
  /** Returns the state to idle. */
  reset: () => void
}

UsePasswordResetReturn

Return type for {@link usePasswordReset}.

interface UsePasswordResetReturn {
  /** The request half's state. */
  readonly requestStatus: UsePromiseState<void>['status']
  /** The request half's failure. */
  readonly requestError: UsePromiseState<void>['error']
  /** The confirm half's state. */
  readonly confirmStatus: UsePromiseState<void>['status']
  /** The confirm half's failure. */
  readonly confirmError: UsePromiseState<void>['error']
  /**
   * Sends the reset email.
   *
   * @param data - The request data.
   * @returns Resolves once sent.
   */
  requestReset: (data: PasswordResetRequest) => Promise<void>
  /**
   * Submits the token and the new password.
   *
   * @param data - The confirm data.
   * @returns Resolves once confirmed.
   */
  confirmReset: (data: PasswordResetConfirm) => Promise<void>
  /** Returns both halves to idle. */
  reset: () => void
}

UseOAuthReturn

Return type for {@link useOAuth}.

interface UseOAuthReturn {
  /**
   * The supported provider names. A live getter: it reads the config the hook
   * currently holds, so it follows a config passed as a signal the way React's
   * re-rendered `providers` list does.
   */
  providers: string[]
  /**
   * Builds the initiation URL for one provider.
   *
   * @param provider - The provider name.
   * @returns The URL.
   */
  getOAuthUrl: (provider: string) => string
  /**
   * Full-page redirect to the provider (default). The opener page navigates
   * away.
   *
   * @param provider - The provider name.
   */
  redirect: (provider: string) => void
  /**
   * Open the provider in a popup so the opener page does NOT navigate. On
   * success the session is established in the opener in place and
   * `config.onSuccess` fires; on failure `config.onError` fires. Falls back to
   * a full-page {@link redirect} when the popup is blocked.
   *
   * @param provider - The provider name.
   */
  loginViaPopup: (provider: string) => void
}

UseOAuthConfig

OAuth configuration for {@link useOAuth}: the app's oauthConfig (from its config.ts), the same type under the same name in every framework binding.

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

UseAuthOptions

Options for {@link useAuth}.

interface UseAuthOptions {
  /**
   * Refresh the session once on mount when the visitor is signed out and the
   * state is decided (a silent probe for a token the storage may hold).
   * Default `false`.
   */
  autoRefresh?: boolean
}

UseAuthResult

What {@link useAuth} returns: every state field as a signal and every auth action as a plain function.

interface UseAuthResult<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> {
  /** `'loading'` until the client decides the session, then its status. */
  readonly status: Signal<AuthState<T>['status']>
  /** The full auth state. */
  readonly state: Signal<AuthState<T>>
  /** The signed-in user, or `null`. */
  readonly user: Signal<T | null>
  /** Whether a session exists. */
  readonly isAuthenticated: Signal<boolean>
  /** Whether the session is still being decided. */
  readonly isLoading: Signal<boolean>
  /** Signs in with credentials. */
  login: (credentials: LoginCredentials) => Promise<AuthResult<T>>
  /** Signs out. */
  logout: () => Promise<void>
  /** Creates an account (also signs it in). */
  register: (data: RegisterData<TRegister>) => Promise<AuthResult<T>>
  /** Refreshes the session from its token. */
  refresh: () => Promise<AuthResult<T>>
  /** Saves profile edits through the client and publishes the saved user. */
  updateProfile: (data: Partial<T>) => Promise<T>
  /** Caches a user without signing in. */
  setUser: (user: T | null) => void
  /** Adopts a caller-issued session atomically. */
  setSession: (session: AuthSessionSeed<T>) => void
}

UseFormOptions

Options for {@link useForm}.

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

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

UseFormResult

Result of {@link useForm}: the state fields as signals and every method as a plain function.

interface UseFormResult<T extends FormValuesConstraint<T>> {
  // State
  /** The whole-form state. */
  readonly formState: Signal<FormState<T>>
  /** Whether the form has no errors. */
  readonly isValid: Signal<boolean>
  /** Whether any field differs from its baseline. */
  readonly isDirty: Signal<boolean>
  /** Whether a submit is running. */
  readonly isSubmitting: Signal<boolean>

  // Field methods
  /**
   * Registers a field and returns its bindings.
   *
   * @param name - The field's name.
   * @param options - Registration options.
   * @returns The field registration.
   */
  register: (
    name: keyof T,
    options?: Omit<RegisterOptions, 'name'> & { name?: string },
  ) => FieldRegistration
  /**
   * Reads one field's value.
   *
   * @param name - The field's name.
   * @returns The value.
   */
  getValue: <K extends keyof T>(name: K) => T[K]
  /**
   * Writes one field's value (marks it touched).
   *
   * @param name - The field's name.
   * @param value - The new value.
   */
  setValue: <K extends keyof T>(name: K, value: T[K]) => void
  /**
   * Reads one field's error.
   *
   * @param name - The field's name.
   * @returns The error message, or `undefined`.
   */
  getError: (name: keyof T) => string | undefined
  /**
   * Sets or clears one field's error.
   *
   * @param name - The field's name.
   * @param error - The message, or `undefined` to clear.
   */
  setError: (name: keyof T, error: string | undefined) => void
  /** Clears every field error. */
  clearErrors: () => void

  // Form methods
  /**
   * Builds the submit runner over the controller's validation.
   *
   * @param onSubmit - Called with the values once validation passes.
   * @returns The runner to call on submit.
   */
  handleSubmit: (
    onSubmit: (values: T) => void | Promise<void>,
  ) => (event?: { preventDefault?: () => void }) => Promise<void>
  /**
   * Resets to the baseline (or new values, which become the baseline).
   *
   * @param values - Optional new baseline.
   */
  reset: (values?: Partial<T>) => void
  /**
   * Applies outside values.
   *
   * @param values - The values to apply.
   * @param resetOptions - Whether edits survive.
   */
  updateValues: (values: Partial<T>, resetOptions?: FormUpdateOptions) => void
  /**
   * Whole-form state tuple: edits mark only changed fields dirty; fills
   * preserve them.
   *
   * @returns `[values, edit, fill]`.
   */
  asState(): readonly [T, FormSetState<T>, FormSetState<Partial<T>>]
  /**
   * One field as [value, edit, fill]. Fill preserves edits made before data
   * arrives.
   *
   * @param name - The field's name.
   * @returns `[value, edit, fill]`.
   */
  asState<K extends keyof T>(name: K): readonly [T[K], FormSetState<T[K]>, FormSetState<T[K]>]
  /**
   * Runs the whole validation.
   *
   * @returns Whether the form is valid.
   */
  validate: () => Promise<boolean>
}

UseHttpState

State for async HTTP operations.

interface UseHttpState<T> {
  /** The latest successful response's data, `null` before one and after a reset. */
  data: T | null
  /** Whether a request is in flight. */
  loading: boolean
  /** The failure of the newest owned request. */
  error: Error | null
}

UseHttpResult

Result of {@link useHttp}: every state field as a signal (the same fields React's result carries as plain values) and the two controls as plain functions.

interface UseHttpResult<T> {
  /** The latest successful response's data, `null` before one and after a reset. */
  readonly data: Signal<T | null>
  /** Whether a request is in flight. */
  readonly loading: Signal<boolean>
  /** The failure of the newest owned request. */
  readonly error: Signal<Error | null>
  /**
   * Runs the request and resolves with its ow