@molecule/app-angular

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

Angular framework bindings for molecule.dev

npm install @molecule/app-angular

npm · Source on GitHub

How it works

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

// 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,
    }),
  ],
})

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

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

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 `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 `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 `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 (`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 `PreviewProvider.recordNavigation` and
   * `PreviewProvider.setUrl` calls). This is a CLIENT-SIDE history move,
   * NOT a reload: it updates `PreviewState.currentUrl` + the nav flags and
   * leaves `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
   * `PreviewState.canGoBack` is `false`.
   */
  back(): void
  /**
   * Navigates the preview to the next entry in its navigation history — a
   * client-side history move (see `PreviewProvider.back`), not a reload.
   * No-op when `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 `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 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
   * `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 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 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 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 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 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 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 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 `redirect` when the popup is blocked.
   *
   * @param provider - The provider name.
   */
  loginViaPopup: (provider: string) => void
}

UseOAuthConfig

OAuth configuration for 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: `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 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 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 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 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 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 own data, or `null` on failure,
   * even when a newer request or `reset` has superseded its displayed state.
   *
   * This function is IDENTITY-STABLE for the component's lifetime — the
   * request it performs is the one the `method`, `url` and `options` sources
   * hold when it is CALLED, as React reads the latest committed render's
   * arguments when its `execute` runs. Its request options are read when it
   * is CALLED.
   *
   * @returns The response data, or `null` on failure.
   */
  execute: () => Promise<T | null>
  /** Supersedes every pending request and clears the state. */
  reset: () => void
}

UseHttpOptions

Options for useHttp and the verb hooks.

Every request option — headers, params, body data, signal, onSuccess, onError — is read at the moment execute runs, not when the hook mounted, 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.
   *
   * @param data - The response data.
   */
  onSuccess?: (data: T) => void
  /**
   * Callback for each request that fails while mounted, including a request
   * superseded by another `execute` or `reset`.
   *
   * @param error - The failure.
   */
  onError?: (error: Error) => void
}

UseWorkspaceResult

What useWorkspace returns: the workspace state as signals and the layout actions.

interface UseWorkspaceResult {
  /** The current panel layout. */
  readonly layout: Signal<WorkspaceState['layout']>
  /** The active panel id, or `null`. */
  readonly activePanel: Signal<WorkspaceState['activePanel']>
  /** The collapsed panel ids. */
  readonly collapsedPanels: Signal<WorkspaceState['collapsedPanels']>
  /**
   * Shows or hides one panel.
   *
   * @param panelId - The panel to toggle.
   */
  togglePanel: (panelId: PanelId) => void
  /**
   * Rewrites one panel's size.
   *
   * @param panelId - The panel to resize.
   * @param size - The new size.
   */
  resizePanel: (panelId: PanelId, size: number) => void
  /**
   * Sets the active panel.
   *
   * @param panelId - The panel to activate.
   */
  setActivePanel: (panelId: PanelId) => void
  /** Restores the default layout. */
  resetLayout: () => void
}

UseEditorResult

What useEditor returns: the tab list and active file as signals and every editor action as a plain function.

interface UseEditorResult {
  /** The provider's tab list. */
  readonly tabs: Signal<EditorTab[]>
  /** The path of the active tab, or `null` when no tab is active. */
  readonly activeFile: Signal<string | null>
  /**
   * Opens a file (and makes it active).
   *
   * @param file - The file to open.
   */
  openFile: (file: EditorFile) => void
  /**
   * Closes a file's tab.
   *
   * @param path - The path to close.
   */
  closeFile: (path: string) => void
  /**
   * Reads the active tab's content.
   *
   * @returns The content, or `null` with no active tab.
   */
  getContent: () => string | null
  /**
   * Writes one tab's content.
   *
   * @param path - The tab's path.
   * @param content - The new content.
   */
  setContent: (path: string, content: string) => void
  /**
   * Activates one tab.
   *
   * @param path - The tab to activate.
   */
  setActiveTab: (path: string) => void
  /**
   * Mounts the editor into an element.
   *
   * @param element - The host element.
   * @param config - The editor config.
   * @returns Whatever the provider's mount returns.
   */
  mount: (...args: Parameters<EditorProvider['mount']>) => ReturnType<EditorProvider['mount']>
  /** Disposes the editor. */
  dispose: () => void
  /** Focuses the editor. */
  focus: () => void
  /**
   * Opens a diff tab.
   *
   * @param file - The diff to show.
   */
  openDiff: (file: DiffFile) => void
  /** Closes the diff tab. */
  closeDiff: () => void
  /**
   * Converts a preview tab into a normal one.
   *
   * @param path - The tab to pin.
   */
  pinTab: (path: string) => void
  /**
   * Adds a type definition file to the editor's language service.
   *
   * @param content - The declaration content.
   * @param filePath - The virtual file path.
   */
  addExtraLib: (content: string, filePath: string) => void
  /**
   * Subscribes to fix-with-AI requests.
   *
   * @param callback - Called for every request.
   * @returns A function that removes the subscription.
   */
  onFixWithAI: (callback: (request: FixWithAIRequest) => void) => () => void
}

UsePreviewResult

What usePreview returns: the preview state as a signal and every preview action as a plain function.

interface UsePreviewResult {
  /** The preview state (url, device, connection, history flags). */
  readonly state: Signal<PreviewState>
  /**
   * Loads a new document.
   *
   * @param url - The url to load.
   */
  setUrl: (url: string) => void
  /** Reloads the current document. */
  refresh: () => void
  /**
   * Switches the device frame.
   *
   * @param device - The device frame to show.
   */
  setDevice: (device: DeviceFrame) => void
  /** Opens the current url outside the preview. */
  openExternal: () => void
  /**
   * Records an in-app navigation without reloading.
   *
   * @param url - The displayed url.
   * @param isReplace - Whether the current history entry is replaced.
   */
  recordNavigation: (url: string, isReplace?: boolean) => void
  /** Goes back one navigation entry. */
  back: () => void
  /** Goes forward one navigation entry. */
  forward: () => void
}

UseDeviceResult

What useDevice returns: the provider's info objects and its two helpers.

interface UseDeviceResult {
  /** The device info. */
  deviceInfo: DeviceInfo
  /** The screen info. */
  screenInfo: ScreenInfo
  /** The hardware info. */
  hardwareInfo: HardwareInfo
  /** Which features this device supports. */
  featureSupport: FeatureSupport
  /**
   * Whether a feature is supported.
   *
   * @param feature - The feature to check.
   * @returns Whether the feature is supported.
   */
  supports: (feature: keyof FeatureSupport) => boolean
  /**
   * Whether the device is online.
   *
   * @returns Whether the device is online.
   */
  isOnline: () => boolean
  /**
   * Whether the app runs standalone (installed).
   *
   * @returns Whether the app is standalone.
   */
  isStandalone: () => boolean
  /** The primary language tag. */
  language: string
  /** The preferred language tags. */
  languages: string[]
}

UsePlatformResult

What usePlatform returns: the detected platform's info and the isPlatform helper.

interface UsePlatformResult {
  /** The detected platform. */
  platform: Platform
  /** Whether the app runs in a native container. */
  isNative: boolean
  /** Whether the platform is mobile. */
  isMobile: boolean
  /** Whether the platform is desktop. */
  isDesktop: boolean
  /** Whether the platform is the web. */
  isWeb: boolean
  /** Whether the app runs in development. */
  isDevelopment: boolean
  /** Whether the app runs in production. */
  isProduction: boolean
  /**
   * Whether the current platform is one of the candidates.
   *
   * @param platforms - The candidate platforms.
   * @returns Whether any candidate matches.
   */
  isPlatform: (...platforms: Platform[]) => boolean
}

UseCapacitorAppResult

What useCapacitorApp returns: every state field as a signal and initialize as a plain function.

interface UseCapacitorAppResult {
  /** Whether the app is fully initialized. */
  readonly ready: Signal<boolean>
  /** Whether device ready has fired. */
  readonly deviceReady: Signal<boolean>
  /** Whether push notifications are initialized. */
  readonly pushReady: Signal<boolean>
  /** The initialization error, if any. */
  readonly error: Signal<Error | null>
  /**
   * Runs initialization again (manual re-initialization).
   *
   * @returns Resolves once initialization finished.
   */
  initialize: () => 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 signals, the same fields React's result carries as plain values) and an argument-free action.

interface UseOptimisticToggleResult {
  /** The newest chosen value, or the server's value when nothing is saving. */
  readonly value: Signal<boolean>
  /** 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>
  /** Flips the value shown now and saves it; the same function for the component's life. */
  toggle: () => void
}

UseProfileFormOptions

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

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

interface UseProfileFormOptions<TUser, TValues extends FormValuesConstraint<TValues>> extends Omit<
  UseFormOptions<TValues>,
  'defaultValues'
> {
  /** Complete controlled-field defaults, including blank write-only fields. */
  defaultValues: TValues
  /**
   * Optional additional account identity check; changing it discards prior edits.
   * By default ownership follows the auth client's session revision, so editable
   * fields can change during a save. Providers without getSessionRevision must
   * supply this callback with an identity that remains stable across profile edits.
   *
   * @param user - The current user.
   * @returns The account identity.
   */
  getIdentity?: (user: TUser) => string
  /**
   * Maps the current/saved user into controlled values, e.g. nullable text to ''.
   *
   * @param user - The current user.
   * @returns The controlled values.
   */
  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.
   *
   * @param changes - The changed fields.
   * @param values - The complete submit-time snapshot.
   * @returns The API patch.
   */
  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.
   *
   * @param user - The saved user.
   * @returns Resolves when propagation finished.
   */
  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. */
  readonly user: Signal<TUser | null>
  /** A user has been loaded; disable submission until this is true. */
  readonly ready: Signal<boolean>
  /**
   * The latest save/propagation failure. Rejected saves retain edits; a failed
   * onSaved callback can be retried by submit without repeating the mutation.
   */
  readonly error: Signal<unknown>
  /**
   * Native input/textarea bindings with the field's concrete value type.
   *
   * @param name - The field's name.
   * @param options - Registration options.
   * @returns The registration, with edits tracked for the dirty rebase.
   */
  register: <K extends keyof TValues>(
    name: K,
    options?: Parameters<UseFormResult<TValues>['register']>[1],
  ) => Omit<FieldRegistration, 'value'> & { value: TValues[K] }
  /** Bind to the native form, with a type="submit" button inside it. */
  formProps: { onSubmit: (event: { preventDefault: () => void }) => void }
  /**
   * Validates and saves one submit-time snapshot. Concurrent submits share the
   * same promise. Resolves undefined on validation, save or propagation failure.
   *
   * @returns The saved user, or `undefined` on failure.
   */
  submit: () => Promise<TUser | undefined>
  /** Discards edits and restores the newest loaded/saved profile baseline. */
  reset: () => void
}

UseRouterResult

What useRouter returns.

interface UseRouterResult {
  /** The current route location. */
  readonly location: Signal<RouteLocation>
  /** The current route's path parameters. */
  readonly params: Signal<RouteParams>
  /** The current query parameters. */
  readonly query: Signal<QueryParams>
  /** Navigates to a path. */
  navigate: (path: string, options?: NavigateOptions) => void
  /** Navigates to a named route. */
  navigateTo: (
    name: string,
    params?: RouteParams,
    query?: QueryParams,
    options?: NavigateOptions,
  ) => void
  /** Goes back one history entry. */
  back: () => void
  /** Goes forward one history entry. */
  forward: () => void
  /** Whether a path matches the current route. */
  isActive: (path: string, exact?: boolean) => boolean
}

UseListRouteResult

What useListRoute returns: each list state field as a signal (the same fields React's result carries as plain values) and the list's link builder and navigation actions.

interface UseListRouteResult<Filter extends string = string, Selection extends string = string> {
  /** The current 1-indexed page (malformed and non-positive URL values read as page one). */
  readonly page: Signal<number>
  /** The configured items per page. */
  readonly pageSize: Signal<number>
  /** The zero-indexed item offset for an API request. */
  readonly offset: Signal<number>
  /** The current URL filter values, including values supplied by path parameters. */
  readonly filters: Signal<Record<Filter, string | undefined>>
  /** The matching view, or the configured fallback. */
  readonly selection: Signal<Selection | undefined>
  /** The decoded current path parameters, also usable as API-only filters. */
  readonly params: Signal<RouteParams>
  /** Whether the current view may load; a protected view waits for auth. */
  readonly canLoad: Signal<boolean>
  /** Readiness for the current view; a public view always stays ready. */
  readonly status: Signal<ListRouteResult<Filter, Selection>['status']>
  /** The sign-in destination while a signed-out protected view is being redirected. */
  readonly redirectTo: Signal<string | undefined>
  /**
   * Builds a real link target, preserving the current pathname, unrelated query
   * values and hash.
   *
   * @param change - The page, filter, selection and path-parameter changes.
   * @returns The link target for the change.
   */
  readonly href: (change?: ListRouteChange<Filter, Selection>) => string
  /**
   * Navigates atomically; location state is preserved unless options replace it.
   *
   * @param change - The page, filter, selection and path-parameter changes.
   * @param options - Navigation options.
   */
  readonly navigate: (change: ListRouteChange<Filter, Selection>, options?: NavigateOptions) => void
  /**
   * Changes only the page, retaining the current filters and view.
   *
   * @param page - The target page, starting at one.
   * @param options - Navigation options.
   */
  readonly setPage: (page: number, options?: NavigateOptions) => void
  /**
   * Patches URL filters and returns to page one.
   *
   * @param filters - The filter values to write (`undefined` removes one).
   * @param options - Navigation options.
   */
  readonly setFilters: (
    filters: Partial<Record<Filter, string | undefined>>,
    options?: NavigateOptions,
  ) => void
  /**
   * Selects a configured view at page one, preserving current route parameters.
   *
   * @param selection - The view to select.
   * @param options - Navigation options.
   */
  readonly select: (selection: Selection, options?: NavigateOptions) => void
}

UseStorageValueOptions

Options for useStorageValue.

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

UseStorageValueResult

Result of useStorageValue: every state field as a signal and the mutators as plain functions.

interface UseStorageValueResult<T> {
  /** The stored value, the default while absent, `undefined` while unknown. */
  readonly value: Signal<T | undefined>
  /** Writes the value through the provider and publishes it. */
  setValue: (value: T) => Promise<void>
  /** Removes the key; the value falls back to the default. */
  removeValue: () => Promise<void>
  /** Whether the first read for the key is still in flight. */
  readonly loading: Signal<boolean>
  /** The read or write failure, cleared by the next successful operation. */
  readonly error: Signal<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

Result of useStoragePreference.

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

UseStoreOptions

Options for useStore.

interface UseStoreOptions<T, S = T> {
  /**
   * Derives the hook's value from the whole state. Receives the full state on
   * every read.
   */
  selector?: (state: T) => S
  /**
   * Compares the previous selected value with the next one; an equal pair keeps
   * the previous result. Without it, identity decides.
   */
  equalityFn?: (previous: S, next: S) => boolean
}

SelectingStoreOptions

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

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

UseThemeResult

What useTheme returns: the current theme, its name and mode as signals, and the actions as plain functions.

interface UseThemeResult {
  /** The current theme object. */
  readonly theme: Signal<Theme>
  /** The current theme's name. */
  readonly themeName: Signal<string>
  /** The current theme's mode (`'light'` or `'dark'`). */
  readonly mode: Signal<'light' | 'dark'>
  /** Sets the theme by name. */
  setTheme: (name: string) => void
  /** Toggles the theme mode, preferring the provider's `toggleMode()`. */
  toggleTheme: () => void
}

UseTranslationResult

What useTranslation returns.

interface UseTranslationResult {
  /**
   * The translation function. A plain function (a signal would be read as the
   * method itself) that reads the provider on every call AND the locale
   * notifications signal, so a template, `computed` or `effect` that calls it
   * re-runs on a locale switch the way React re-renders on one.
   *
   * Its identity follows the active locale, like React's `useTranslation().t`:
   * a value memoized on it (a `computed`, a child bound `t` as an input)
   * refreshes after a switch, while an `addTranslations` for the same locale
   * keeps it. `useT()` is the one-identity form.
   */
  readonly t: I18nProvider['t']
  /** The active locale code. */
  readonly locale: Signal<string>
  /** Switches the active locale; resolves when the provider has switched it. */
  setLocale: I18nProvider['setLocale']
  /** The available locales; a fresh list once per notification. */
  readonly locales: Signal<I18nProvider['getLocales'] extends () => infer L ? L : never>
  /** Formats a number for the active locale. */
  formatNumber: (value: number, options?: NumberFormatOptions) => string
  /** Formats a date for the active locale. */
  formatDate: (value: Date | number | string, options?: DateFormatOptions) => string
  /** The active locale's text direction. */
  readonly direction: Signal<'ltr' | 'rtl'>
}

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.
   *
   * @param error - The failure.
   */
  onError?: (error: Error) => void
}

UseVerifyPaymentReturnResult

Result of useVerifyPaymentReturn: the state fields as signals.

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`.
   */
  readonly status: Signal<VerifyPaymentReturnStatus>

  /**
   * `true` when the URL identifies a purchase to verify. A `cleanUrl` rewrite
   * after a verified purchase clears it, as React's per-render URL read does.
   */
  readonly isReturn: Signal<boolean>

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

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

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

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

UseVersionResult

What useVersion returns: every state field as a signal and every update action as a plain function.

interface UseVersionResult {
  /** The full version state. */
  readonly state: Signal<VersionState>
  /** Whether an update is available. */
  readonly isUpdateAvailable: Signal<boolean>
  /** Whether an update check is running. */
  readonly isChecking: Signal<boolean>
  /** Whether a service worker waits to activate. */
  readonly isServiceWorkerWaiting: Signal<boolean>
  /** The version an available update reports. */
  readonly newVersion: Signal<string | undefined>
  /** Runs one update check; resolves with whether one was found. */
  checkForUpdates: () => Promise<boolean>
  /** Applies the update (the provider reloads the page). */
  applyUpdate: (options?: { force?: boolean }) => void
  /** Hides the update notice until the next check finds one. */
  dismissUpdate: () => void
  /** Starts periodic update checks. */
  startPeriodicChecks: (options?: UpdateCheckOptions) => void
  /** Stops periodic update checks. */
  stopPeriodicChecks: () => void
}

LinkProps

The inputs Link takes: @molecule/app-react's LinkProps for an Angular directive. React's to is the directive's own attribute, molLink; every other anchor attribute (class, target, rel) is written on the <a> as usual.

interface LinkProps {
  /** The destination: an app path or a URL (React's `to`). */
  molLink: string
  /** Replace the current history entry instead of pushing one. */
  replace?: boolean
  /** State stored with the new history entry. */
  state?: unknown
}

AsyncStateManager

Async state manager.

interface AsyncStateManager<T> {
  state$: Observable<T>
  getState: () => 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
  destroy: () => void
}

CapacitorAppManager

Capacitor app manager interface.

interface CapacitorAppManager {
  state$: Observable<CapacitorAppState>
  ready$: Observable<boolean>
  initialize: () => Promise<void>
  destroy: () => void
}

ChangePasswordStateManager

Change password state manager.

interface ChangePasswordStateManager {
  state$: Observable<PromiseState<void>>
  getState: () => PromiseState<void>
  changePassword: (oldPassword: string, newPassword: string) => Promise<void>
  reset: () => void
  destroy: () => void
}

DeviceService

Device service interface.

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

HttpState

State for HTTP requests.

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

LoginStateManager

Login state manager.

interface LoginStateManager<T = unknown> {
  state$: Observable<PromiseState<AuthResult<T>>>
  getState: () => PromiseState<AuthResult<T>>
  login: (credentials: LoginCredentials) => Promise<AuthResult<T>>
  reset: () => void
  destroy: () => void
}

OAuthOptions

OAuth configuration options.

interface OAuthOptions {
  /** 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. Failures are
   * also emitted on `OAuthStateManager.error$`.
   */
  onError?: (error: string) => void
  /**
   * Auth client used to establish the session after the code exchange. This
   * is THE way to wire session establishment in Angular: inject the
   * `AUTH_CLIENT` token and pass the client here. When omitted, the helper
   * falls back to the server-established httpOnly-cookie session (see
   * `OAuthStateManager.handleCallback`).
   */
  authClient?: AuthClient<unknown>
}

OAuthStateManager

OAuth state manager.

interface OAuthStateManager {
  /** Observable of the configured OAuth provider names. */
  providers$: Observable<string[]>
  /**
   * Observable of OAuth failure messages (from the callback code exchange).
   * Completed by `OAuthStateManager.destroy`.
   */
  error$: Observable<string>
  /** Returns the configured OAuth provider names. */
  getProviders: () => 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 `createOAuthState`);
   * 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 was provided, 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>
  /** Completes the `providers$` and `error$` observables. */
  destroy: () => void
}

PasswordResetStateManager

Password reset state manager.

interface PasswordResetStateManager {
  requestState$: Observable<PromiseState<void>>
  confirmState$: Observable<PromiseState<void>>
  getRequestState: () => PromiseState<void>
  getConfirmState: () => PromiseState<void>
  requestReset: (data: PasswordResetRequest) => Promise<void>
  confirmReset: (data: PasswordResetConfirm) => Promise<void>
  reset: () => void
  destroy: () => void
}

PlatformService

Platform service interface.

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

PromiseStateManager

Promise state manager.

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

SignupStateManager

Signup state manager.

interface SignupStateManager<T = unknown> {
  state$: Observable<PromiseState<AuthResult<T>>>
  getState: () => PromiseState<AuthResult<T>>
  signup: (data: RegisterData) => Promise<AuthResult<T>>
  reset: () => void
  destroy: () => void
}

StorageValueState

State for a storage value.

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

VersionService

Version service interface.

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

SessionReadyProps

The content SessionReady takes. React passes these nodes as the children and fallback props; an Angular component takes nodes as projected content, so children is the content and fallback is the element marked slot="fallback".

interface SessionReadyProps {
  /** What renders once the initial restore settles (projected content). */
  children?: unknown
  /** What renders while the session restore is still undecided (the `[slot=fallback]` element). */
  fallback?: unknown
}

MoleculeModuleConfig

Configuration for molecule Angular module.

interface MoleculeModuleConfig {
  state?: StateProvider
  auth?: AuthClient<unknown>
  /**
   * Hold bootstrap (and so every page's first render) until `auth` has decided the
   * session. Defaults to true, as React's `MoleculeProvider` does. A token-only or
   * cookie-only restore makes a current-user request. Until it answers, a public page's
   * signed-in action (`if (!user) return`, a redirect to `/login`) treats a signed-in
   * visitor as signed out. Angular's app initializer waits only while status is
   * `'loading'`, so a cached session renders while its verification continues in the
   * background. `'unavailable'` also renders and may have a null user. A visitor with no
   * session candidate settles synchronously without a request. While the initializer
   * waits, the page shows whatever the app root holds in `index.html` (Angular has no
   * `sessionFallback`). Set false to render at once. Ignored without `auth`.
   */
  awaitSession?: boolean
  theme?: ThemeProvider
  router?: Router
  i18n?: I18nProvider
  http?: HttpClient
  storage?: StorageProvider
  logger?: LoggerProvider
  /** The IDE workspace provider useWorkspace and useWorkspaceProvider use. */
  workspace?: WorkspaceProvider
  /** The code editor provider useEditor and useEditorProvider use. */
  editor?: EditorProvider
  /** The live preview provider usePreview and usePreviewProvider use. */
  preview?: PreviewProvider
}

MoleculeTokens

Injection tokens for molecule services.

interface MoleculeTokens {
  STATE_PROVIDER: symbol
  AUTH_CLIENT: symbol
  THEME_PROVIDER: symbol
  ROUTER: symbol
  I18N_PROVIDER: symbol
  HTTP_CLIENT: symbol
  STORAGE_PROVIDER: symbol
  LOGGER_PROVIDER: symbol
  WORKSPACE_PROVIDER: symbol
  EDITOR_PROVIDER: symbol
  PREVIEW_PROVIDER: symbol
}

Types

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

An async-capable setState function: a value, an updater receiving the previous state, or a promise resolving to either. Errors from a resolved promise are swallowed so they never surface as unhandled rejections.

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

AsyncExtendState

An async-capable extendState function for partial updates.

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

FormSetState

A set-state function over a form value: a value or an updater receiving the previous value.

type FormSetState<T> = (value: T | ((previous: T) => T)) => void

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

The translation function useT returns.

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.
type UseTFunction = TranslateFunctionWithFallback

VerifyPaymentReturnStatus

How far the return-page verification has got.

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

MaybeSignal

A hook argument: the plain value, or a signal holding the value the hook should currently use. A signal holding undefined means the argument was omitted, exactly like a missing plain argument: the default applies.

type MaybeSignal<T> = T | Signal<T>

Classes

MolPlacement

Gives usePlacement the component's own moments. A component that calls usePlacement lists it in hostDirectives; usePlacement throws without it. Its hooks fire exactly when the component's own would: after the component's view was first rendered (its view queries are set), and each time the parent checks the component (its inputs are set).

@Directive({ standalone: true })
export class MolPlacement implements AfterViewInit, DoCheck {
  private readonly runs: (() => void)[] = []

  /**
   * Adds a placement function to run at the component's moments.
   *
   * @param run - Runs it.
   * @internal
   */
  add(run: () => void): void {
    this.runs.push(run)
  }

  /** The component's view exists and its view queries are set. */
  ngAfterViewInit(): void {
    for (const run of this.runs) run()
  }

  /** The parent set the component's inputs. */
  ngDoCheck(): void {
    for (const run of this.runs) run()
  }
}

WrappedChildren

The wrappers around a component's projected children: React's children.map((child) => <div>{child}</div>).

The component lists it in providers, injects it, and puts molWrapEachChild on the template element that holds <ng-content>. Angular then places every projected child — at creation and whenever the consumer's @for or @if adds one later, anywhere in the list — inside its own wrapper, and a wrapper goes with its child. No node is moved after Angular placed it. The component styles the wrappers from wrappers (an effect), and reads React's children.length as wrappers().length.

@Injectable()
export class WrappedChildren {
  private readonly state = signal<readonly HTMLElement[]>([])
  private parent: HTMLElement | null = null
  private create: (document: Document) => HTMLElement = (document) => document.createElement('div')

  /** The wrappers, in render order. */
  readonly wrappers: Signal<readonly HTMLElement[]> = this.state.asReadonly()

  constructor() {
    assertDomPlacement('WrappedChildren')
  }

  /**
   * Sets how a wrapper element is created (default: an empty `<div>`). Call it
   * in the constructor; attributes that depend on the child's index belong in
   * an effect over `wrappers`.
   *
   * @param create - Builds one wrapper element.
   */
  wrapWith(create: (document: Document) => HTMLElement): void {
    this.create = create
  }

  /**
   * Starts wrapping the children Angular places in `parent`.
   *
   * @param parent - The element that holds the projected content.
   * @internal
   */
  attach(parent: HTMLElement): void {
    if (this.parent !== null) {
      throw new Error('WrappedChildren: one component wraps the children of one element.')
    }
    this.parent = parent
    wrappingParents.set(parent, this)
  }

  /**
   * Creates one wrapper.
   *
   * @returns The wrapper element.
   * @internal
   */
  createWrapper(): HTMLElement {
    const wrapper = this.create((this.parent as HTMLElement).ownerDocument)
    wrapperOwners.set(wrapper, this)
    return wrapper
  }

  /**
   * Re-reads the wrappers after Angular added or removed a child.
   *
   * @internal
   */
  refresh(): void {
    if (this.parent === null) return
    const next: HTMLElement[] = []
    for (const child of Array.from(this.parent.children)) {
      if (wrapperOwners.get(child) !== this) continue
      // Angular's `animate.leave` removes a cancelled leaving element without the renderer.
      if (child.hasChildNodes()) next.push(child as HTMLElement)
      else child.remove()
    }
    const current = this.state()
    if (next.length === current.length && next.every((wrapper, i) => wrapper === current[i])) return
    this.state.set(next)
  }
}

MolWrapEachChild

Marks the template element whose projected children are each wrapped: <div molWrapEachChild><ng-content /></div>. See WrappedChildren. The marker attribute is taken off the element, so the markup stays React's.

@Directive({ selector: '[molWrapEachChild]', standalone: true })
export class MolWrapEachChild {
  constructor() {
    const parent = inject(ElementRef<HTMLElement>).nativeElement as HTMLElement
    parent.removeAttribute('molWrapEachChild')
    inject(WrappedChildren).attach(parent)
  }
}

MolLazy

Stamps projected content in its own place, and keeps it exactly while that place is in the page: created when the component that received it shows it, destroyed when the component hides it, created again when it shows it again, as React mounts a slot. A place that moves to another parent (a sidebar rendered on the other side) is a new place: React never moves a mounted node to another parent, so the content is created again there. Write it as *molLazy on the slot's element, or as molLazy on an <ng-template> (with ngProjectAs for a named slot):

<mol-modal [open]="open" (close)="open = false">
  <form *molLazy>…</form>
  <div slot="footer" *molLazy><button molButton>Save</button></div>
  <ng-template molLazy ngProjectAs="[slot=footer]">…</ng-template>
</mol-modal>

Plain projected content is created with the consumer's view and kept for its whole life, which is right for static content (a closed dialog's footer buttons). Use *molLazy for content with state, effects or a fetch, which must not run while hidden and must start fresh each time it shows. It works on every component that hides a slot by taking its place out of the page, through @if or the @molecule/app-angular DOM placement, and on content that a wrapper component projects on.

The decision runs after every render, once every component has placed its slots: a component that attaches or detaches a region does it in a render's write phase or earlier, and this directive reads the result in the mixedReadWrite phase of the same render. It does not run on the server, where a lazy slot renders nothing.

@Directive({ selector: '[molLazy]', standalone: true })
export class MolLazy {
  constructor() {
    const template = inject(TemplateRef, { optional: true })
    if (template === null) {
      throw new Error('molLazy goes on an <ng-template>, or as *molLazy on an element.')
    }
    const views = inject(ViewContainerRef)
    const anchor = inject(ElementRef).nativeElement as Comment
    lazyAnchors.set(anchor, template)
    /** The parent the content was stamped in. */
    let stampedIn: Node | null = null
    afterEveryRender({
      // After every component's placement (`write`), so a closed dialog's footer is already out
      // of the page; outside change detection, so no view is edited while Angular walks it.
      mixedReadWrite: () => {
        const shown = anchor.isConnected
        if (views.length > 0 && (!shown || anchor.parentNode !== stampedIn)) {
          stampedRoots.delete(anchor)
          views.clear()
        }
        if (shown && views.length === 0) {
          stampedIn = anchor.parentNode
          const view = views.createEmbeddedView(template)
          for (const node of view.rootNodes as Node[]) lazyContent.add(node)
          stampedRoots.set(anchor, view.rootNodes as Node[])
          view.detectChanges()
        }
      },
    })
  }
}

<a molLink="/settings">: sets the anchor's href and 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 the template's own (click) handler 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 registered, the URL as its href, and a click is left to the browser (the template's own (click) handler still runs). A link to an app path needs a router, and fails without one with the error useRouterInstance throws.

Inputs: molLink (the destination: an app path or a URL), replace (replace the current history entry; when unset, a link to the location already shown replaces it and any other link pushes, as with react-router's <Link>), and state (stored with the new entry). Every other attribute (class, target, rel) is written on the anchor as usual.

Use it for every internal link instead of an anchor with a (click) handler that calls navigate(). Needs the router from provideMolecule({ router }).

@Directive({
  selector: 'a[molLink]',
  standalone: true,
  inputs: ['molLink', 'replace', 'state'],
  host: { '[attr.href]': 'href' },
})
export class Link implements OnInit, LinkProps {
  /**
   * The 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.
   */
  molLink = ''
  /** Replace the current history entry instead of pushing one. */
  replace?: boolean
  /** State stored with the new history entry. */
  state?: unknown

  /**
   * Reads the registered router once, here in the field initializer's injection context, and
   * answers for each destination this link shows: an app path fails with the no-router error
   * when none is registered. It takes the hook's function form because `molLink` is not set
   * when a field initializer runs.
   */
  private readonly linkRouter = useLinkRouter()

  /**
   * The anchor's `href`: the URL as written for a URL outside the app with no router registered,
   * else the one the router writes for an app path, base path included. An app path with no
   * router fails here with the no-router error.
   */
  get href(): string {
    const router = this.linkRouter(this.molLink)
    return router === null ? this.molLink : routerLinkHref(this.molLink, router)
  }
  private readonly element = inject<ElementRef<HTMLAnchorElement>>(ElementRef)
  private readonly renderer = inject(Renderer2)
  private readonly destroyRef = inject(DestroyRef)

  /**
   * Starts handling clicks. The listener is added here, after the template
   * created this anchor's own `(click)` listeners, so those run first and can
   * prevent the navigation (react-router calls `onClick` first too). With no
   * router (a URL outside the app) the browser follows the anchor instead.
   */
  ngOnInit(): void {
    const stop = this.renderer.listen(this.element.nativeElement, 'click', (event: MouseEvent) => {
      const router = this.linkRouter(this.molLink)
      if (router !== null) {
        followRouterLink(event, this.molLink, router, {
          replace: this.replace,
          state: this.state,
        })
      }
    })
    this.destroyRef.onDestroy(stop)
  }
}

RoutedView

Renders the matched child route, through whichever routing bond the app wired (an outlet component under the angular-router bond). A layout or guard renders it where its page goes when it was given no projected content, so the component imports no router library. The page renders where this element stands, and the element itself is not in the page: React's RoutedView renders only the page.

Throws an I18nError (angular.error.noRoutedView) when it is created and the routing bond has no routed view: project the page instead. Rendering nothing there would show a blank page with no error.

@Component({
  selector: 'mol-routed-view',
  standalone: true,
  hostDirectives: [MolPlacement],
  template: '<ng-container #outlet />',
})
export class RoutedView implements OnInit {
  private readonly view = routedViewOrThrow()
  private readonly host = inject(ElementRef).nativeElement as HTMLElement
  /**
   * An anchor of its own template: a RoutedView created outside any template (a test mounting it
   * alone) has no parent element for its host's container, so a page placed there never shows. A
   * decorator query, not `viewChild()`: this package is compiled by `tsc`, and Angular's JIT
   * compiler sees no signal query in a field initializer (NG0951). Static, so set before ngOnInit.
   */
  @ViewChild('outlet', { read: ViewContainerRef, static: true }) outlet?: ViewContainerRef

  constructor() {
    // Alone (no parent element), the host keeps the page: placeContentBefore needs a place.
    usePlacement(() => {
      placeContentBefore(this.host, this.host)
      setElementPresent(this.host, false)
    })
  }

  /** Creates the routed view's component at this element's anchor. */
  ngOnInit(): void {
    this.outlet?.createComponent(this.view)
  }
}

MoleculeAuthService

Angular service for authentication.

Wraps molecule auth client and exposes state as RxJS observables.

@Injectable({
  providedIn: 'root',
})
export class MoleculeAuthService<
  T = unknown,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
> implements OnDestroy {
  private stateSubject: BehaviorSubject<AuthState<T>>
  private unsubscribe: (() => void) | null = null

  /**
   * Observable of the full auth state.
   */
  state$: Observable<AuthState<T>>

  /**
   * Observable of the authenticated user.
   */
  user$: Observable<T | null>

  /**
   * Observable of authentication status.
   */
  isAuthenticated$: Observable<boolean>

  /**
   * Observable of loading status.
   */
  isLoading$: Observable<boolean>

  constructor(@Inject(AUTH_CLIENT) private client: AuthClient<T, TRegister>) {
    this.stateSubject = new BehaviorSubject<AuthState<T>>(client.getState())

    this.unsubscribe = client.onAuthChange(() => {
      this.stateSubject.next(client.getState())
    })

    this.state$ = this.stateSubject.asObservable()

    this.user$ = this.state$.pipe(
      map((state) => state.user),
      distinctUntilChanged(),
    )

    this.isAuthenticated$ = this.state$.pipe(
      map((state) => state.authenticated),
      distinctUntilChanged(),
    )

    this.isLoading$ = this.state$.pipe(
      map((state) => state.loading),
      distinctUntilChanged(),
    )
  }

  /**
   * Get the current auth state snapshot.
   * @returns The current authentication state including user, loading, and authenticated flags.
   */
  get state(): AuthState<T> {
    return this.client.getState()
  }

  /**
   * Get the current user snapshot.
   * @returns The authenticated user object, or `null` if not authenticated.
   */
  get user(): T | null {
    return this.state.user
  }

  /**
   * Check if user is currently authenticated.
   * @returns `true` if the user is authenticated, `false` otherwise.
   */
  get isAuthenticated(): boolean {
    return this.state.authenticated
  }

  /**
   * Login with credentials.
   *
   * @param credentials - The email/password or provider-specific login credentials.
   * @returns A promise that resolves to the authentication result with user data and tokens.
   */
  login(credentials: LoginCredentials): Promise<AuthResult<T>> {
    return this.client.login(credentials)
  }

  /**
   * Logout the current user.
   * @returns A promise that resolves when the user has been logged out.
   */
  logout(): Promise<void> {
    return this.client.logout()
  }

  /**
   * Register a new user.
   *
   * @param data - The registration payload including email, password, and profile fields.
   * @returns A promise that resolves to the authentication result for the newly registered user.
   */
  register(data: RegisterData<TRegister>): Promise<AuthResult<T>> {
    return this.client.register(data)
  }

  /**
   * Refresh the authentication token.
   * @returns A promise that resolves to the authentication result with refreshed tokens.
   */
  refresh(): Promise<AuthResult<T>> {
    return this.client.refresh()
  }

  /**
   * Clean up auth state subscription on service destruction.
   */
  ngOnDestroy(): void {
    this.unsubscribe?.()
    this.stateSubject.complete()
  }
}

MoleculeFormInstance

Wrapper around a FormController that provides RxJS observables and synchronous accessors for use in Angular components.

class MoleculeFormInstance<T extends FormValuesConstraint<T>> {
  private stateSubject: BehaviorSubject<FormState<T>>
  private unsubscribe: (() => void) | null = null

  /**
   * Observable of the full form state.
   */
  state$: Observable<FormState<T>>

  /**
   * Observable of form validity.
   */
  isValid$: Observable<boolean>

  /**
   * Observable of form dirty state.
   */
  isDirty$: Observable<boolean>

  /**
   * Observable of form submitting state.
   */
  isSubmitting$: Observable<boolean>

  /**
   * Observable of field errors.
   */
  errors$: Observable<Partial<Record<keyof T, string>>>

  constructor(private controller: FormController<T>) {
    this.stateSubject = new BehaviorSubject<FormState<T>>(controller.getState())

    const refresh = (): void => this.stateSubject.next(controller.getState())
    this.unsubscribe = controller.subscribe(refresh)
    refresh()

    this.state$ = this.stateSubject.asObservable()

    this.isValid$ = this.state$.pipe(
      map((state) => state.isValid),
      distinctUntilChanged(),
    )

    this.isDirty$ = this.state$.pipe(
      map((state) => state.isDirty),
      distinctUntilChanged(),
    )

    this.isSubmitting$ = this.state$.pipe(
      map((state) => state.isSubmitting),
      distinctUntilChanged(),
    )

    this.errors$ = this.state$.pipe(
      map((state) => state.errors),
      distinctUntilChanged(),
    )
  }

  /**
   * Get the current form state snapshot.
   * @returns The current form state including values, errors, validity, and submission status.
   */
  get state(): FormState<T> {
    return this.controller.getState()
  }

  /**
   * Get the current form validity snapshot.
   * @returns `true` if all fields pass validation, `false` otherwise.
   */
  get isValid(): boolean {
    return this.controller.getState().isValid
  }

  /**
   * Get the current form dirty state snapshot.
   * @returns `true` if any field has been modified from its default value, `false` otherwise.
   */
  get isDirty(): boolean {
    return this.controller.getState().isDirty
  }

  /**
   * Get the current form submitting state snapshot.
   * @returns `true` if the form is currently being submitted, `false` otherwise.
   */
  get isSubmitting(): boolean {
    return this.controller.getState().isSubmitting
  }

  /**
   * Register a field for form management.
   *
   * @param name - The field name corresponding to a key in the form values type.
   * @param options - Registration options including validation rules and default value.
   * @returns The field registration with value, onChange, onBlur, and ref bindings.
   */
  register(name: keyof T, options?: Omit<RegisterOptions, 'name'>): FieldRegistration {
    return this.controller.register({ ...options, name: name as string } as RegisterOptions)
  }

  /**
   * Get the value of a specific field.
   *
   * @param name - The field name corresponding to a key in the form values type.
   * @returns The current value of the specified field.
   */
  getValue<K extends keyof T>(name: K): T[K] {
    return this.controller.getValue(name)
  }

  /**
   * Set the value of a specific field.
   *
   * @param name - The field name corresponding to a key in the form values type.
   * @param value - The new value to set for the field.
   */
  setValue<K extends keyof T>(name: K, value: T[K]): void {
    this.controller.setValue(name as string, value)
  }

  /**
   * Get the error for a specific field.
   *
   * @param name - The field name to retrieve the error for.
   * @returns The error message for the field, or `undefined` if the field has no error.
   */
  getError(name: keyof T): string | undefined {
    return this.controller.getError(name as string)
  }

  /**
   * Set the error for a specific field.
   *
   * @param name - The field name to set or clear the error for.
   * @param error - The error message to set, or `undefined` to clear the error.
   */
  setError(name: keyof T, error: string | undefined): void {
    if (error !== undefined) {
      this.controller.setError(name as string, error)
    } else {
      this.controller.clearError(name)
    }
  }

  /**
   * Clear all field errors.
   */
  clearErrors(): void {
    this.controller.clearErrors()
  }

  /**
   * Create a submit handler function.
   *
   * @param onSubmit - Callback invoked with validated form values on successful submission.
   * @param onError - Optional callback invoked with field errors when validation fails.
   * @returns A submit handler function that can be called from form submit events.
   */
  handleSubmit(
    onSubmit: (values: T) => void | Promise<void>,
    onError?: (errors: Partial<Record<keyof T, string>>) => void,
  ): (event?: { preventDefault?: () => void }) => Promise<void> {
    return this.controller.handleSubmit(onSubmit, onError)
  }

  /**
   * Apply a newly loaded record without clearing submission state.
   *
   * @param values - The newly loaded record.
   * @param resetOptions - Set `keepDirtyValues` to retain edits and fill pristine fields.
   */
  updateValues(values: Partial<T>, resetOptions: FormResetOptions = {}): void {
    this.controller.updateValues(values, resetOptions)
  }

  /**
   * Reset the form to initial values.
   *
   * @param values - Optional partial values to use as the new initial state.
   */
  reset(values?: Partial<T>): void {
    this.controller.reset(values)
  }

  /**
   * Validate all fields.
   *
   * @returns A promise that resolves to `true` if all fields are valid, `false` otherwise.
   */
  validate(): Promise<boolean> {
    return this.controller.validate()
  }

  /**
   * Destroy the form instance and clean up subscriptions.
   */
  destroy(): void {
    this.unsubscribe?.()
    this.unsubscribe = null
    this.stateSubject.complete()
    this.controller.destroy()
  }
}

MoleculeFormsService

Angular service for form handling.

Wraps molecule form providers and creates form instances that expose state as RxJS observables.

@Injectable({
  providedIn: 'root',
})
export class MoleculeFormsService implements OnDestroy {
  private instances: MoleculeFormInstance<Record<string, unknown>>[] = []

  /**
   * Create a form instance from a provider.
   *
   * @param provider - The form provider that creates form controllers.
   * @param options - Narrowed `FormOptions` without `values` or `resetOptions`;
   * includes default values and validation mode.
   * @returns A new form instance with RxJS observables and explicit
   * `updateValues(values, { keepDirtyValues })` delivery. The option defaults to
   * false; pass true to retain edited fields while pristine fields take the record.
   */
  createForm<T extends FormValuesConstraint<T>>(
    provider: FormProvider,
    options: AngularFormOptions<T>,
  ): MoleculeFormInstance<T> {
    const controller = provider.createForm(options)
    const instance = new MoleculeFormInstance<T>(controller)
    this.instances.push(instance as MoleculeFormInstance<Record<string, unknown>>)
    return instance
  }

  /**
   * Destroy all managed form instances on service destruction.
   */
  ngOnDestroy(): void {
    for (const instance of this.instances) {
      instance.destroy()
    }
    this.instances = []
  }
}

MoleculeHttpService

Angular service for HTTP requests.

Wraps molecule HTTP client and returns RxJS observables.

@Injectable({
  providedIn: 'root',
})
/**
 * Molecule Http Service class.
 */
export class MoleculeHttpService {
  constructor(@Inject(HTTP_CLIENT) private client: HttpClient) {}

  /**
   * Make a GET request.
   *
   * @param url - Request URL
   * @param config - Request configuration
   * @returns Observable of response data
   */
  get<T>(url: string, config?: RequestConfig): Observable<T> {
    return from(this.client.get<T>(url, config)).pipe(map((res) => res.data))
  }

  /**
   * Make a POST request.
   *
   * @param url - Request URL
   * @param data - Request body
   * @param config - Request configuration
   * @returns Observable of response data
   */
  post<T>(url: string, data?: unknown, config?: RequestConfig): Observable<T> {
    return from(this.client.post<T>(url, data, config)).pipe(map((res) => res.data))
  }

  /**
   * Make a PUT request.
   *
   * @param url - Request URL
   * @param data - Request body
   * @param config - Request configuration
   * @returns Observable of response data
   */
  put<T>(url: string, data?: unknown, config?: RequestConfig): Observable<T> {
    return from(this.client.put<T>(url, data, config)).pipe(map((res) => res.data))
  }

  /**
   * Make a PATCH request.
   *
   * @param url - Request URL
   * @param data - Request body
   * @param config - Request configuration
   * @returns Observable of response data
   */
  patch<T>(url: string, data?: unknown, config?: RequestConfig): Observable<T> {
    return from(this.client.patch<T>(url, data, config)).pipe(map((res) => res.data))
  }

  /**
   * Make a DELETE request.
   *
   * @param url - Request URL
   * @param config - Request configuration
   * @returns Observable of response data
   */
  delete<T>(url: string, config?: RequestConfig): Observable<T> {
    return from(this.client.delete<T>(url, config)).pipe(map((res) => res.data))
  }

  /**
   * Get the full response (including headers, status, etc.).
   *
   * @param method - HTTP method
   * @param url - Request URL
   * @param config - Request configuration
   * @returns Observable of full response
   */
  request<T>(
    method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
    url: string,
    config?: RequestConfig,
  ): Observable<HttpResponse<T>> {
    const promise = (async () => {
      switch (method) {
        case 'GET':
          return this.client.get<T>(url, config)
        case 'POST':
          return this.client.post<T>(
            url,
            (config as RequestConfig & { data?: unknown })?.data,
            config,
          )
        case 'PUT':
          return this.client.put<T>(
            url,
            (config as RequestConfig & { data?: unknown })?.data,
            config,
          )
        case 'PATCH':
          return this.client.patch<T>(
            url,
            (config as RequestConfig & { data?: unknown })?.data,
            config,
          )
        case 'DELETE':
          return this.client.delete<T>(url, config)
      }
    })()

    return from(promise)
  }

  /**
   * Create a state subject for managing request state.
   *
   * @returns The created instance.
   */
  createState<T>(): BehaviorSubject<HttpState<T>> {
    return new BehaviorSubject<HttpState<T>>({
      data: null,
      loading: false,
      error: null,
    })
  }

  /**
   * Make a GET request with state management.
   *
   * @param url - Request URL
   * @param state - State subject to update
   * @param config - Request configuration
   */
  getWithState<T>(url: string, state: BehaviorSubject<HttpState<T>>, config?: RequestConfig): void {
    state.next({ ...state.value, loading: true, error: null })

    this.get<T>(url, config)
      .pipe(
        tap((data) => state.next({ data, loading: false, error: null })),
        catchError((error) => {
          state.next({ data: null, loading: false, error })
          throw error
        }),
      )
      .subscribe()
  }
}

MoleculeI18nService

Angular service for internationalization.

Wraps molecule i18n provider and exposes state as RxJS observables.

@Injectable({
  providedIn: 'root',
})
export class MoleculeI18nService implements OnDestroy {
  private localeSubject: BehaviorSubject<string>
  private directionSubject: BehaviorSubject<'ltr' | 'rtl'>
  private localesSubject: BehaviorSubject<LocaleConfig[]>
  private unsubscribe: (() => void) | null = null

  /**
   * Observable of the current locale code.
   */
  locale$: Observable<string>

  /**
   * Observable of the text direction.
   */
  direction$: Observable<'ltr' | 'rtl'>

  /**
   * Observable of available locales.
   */
  locales$: Observable<LocaleConfig[]>

  constructor(@Inject(I18N_PROVIDER) private provider: I18nProvider) {
    this.localeSubject = new BehaviorSubject<string>(provider.getLocale())
    this.directionSubject = new BehaviorSubject<'ltr' | 'rtl'>(provider.getDirection())
    this.localesSubject = new BehaviorSubject<LocaleConfig[]>(provider.getLocales())

    this.unsubscribe = provider.onLocaleChange(() => {
      this.localeSubject.next(provider.getLocale())
      this.directionSubject.next(provider.getDirection())
      this.localesSubject.next(provider.getLocales())
    })

    this.locale$ = this.localeSubject.asObservable()
    this.direction$ = this.directionSubject.asObservable()
    this.locales$ = this.localesSubject.asObservable()
  }

  /**
   * Get the current locale code snapshot.
   * @returns The active locale code (e.g. `'en'`, `'fr'`).
   */
  get locale(): string {
    return this.provider.getLocale()
  }

  /**
   * Get the current text direction snapshot.
   * @returns The text direction for the active locale, either `'ltr'` or `'rtl'`.
   */
  get direction(): 'ltr' | 'rtl' {
    return this.provider.getDirection()
  }

  /**
   * Translate a key.
   *
   * @param key - The dot-notation translation key to look up.
   * @param values - Optional interpolation values to substitute into the translated string.
   * @returns The translated and interpolated string for the current locale.
   */
  t(key: string, values?: InterpolationValues): string {
    return this.provider.t(key, values)
  }

  /**
   * Set the current locale.
   *
   * @param code - The locale code to switch to (e.g. `'en'`, `'fr'`).
   */
  setLocale(code: string): void {
    this.provider.setLocale(code)
  }

  /**
   * Format a number.
   *
   * @param value - The number to format.
   * @param options - Locale-aware formatting options such as style, currency, and precision.
   * @returns The locale-formatted number string.
   */
  formatNumber(value: number, options?: NumberFormatOptions): string {
    return this.provider.formatNumber(value, options)
  }

  /**
   * Format a date.
   *
   * @param value - The date to format, as a Date object, timestamp, or ISO string.
   * @param options - Locale-aware formatting options such as date style and time zone.
   * @returns The locale-formatted date string.
   */
  formatDate(value: Date | number | string, options?: DateFormatOptions): string {
    return this.provider.formatDate(value, options)
  }

  /**
   * Clean up locale change subscription and complete all subjects on service destruction.
   */
  ngOnDestroy(): void {
    this.unsubscribe?.()
    this.localeSubject.complete()
    this.directionSubject.complete()
    this.localesSubject.complete()
  }
}

MoleculeLoggerService

Angular service for logging.

Wraps molecule logger provider.

@Injectable({
  providedIn: 'root',
})
export class MoleculeLoggerService {
  constructor(@Inject(LOGGER_PROVIDER) private provider: LoggerProvider) {}

  /**
   * Get a logger instance.
   *
   * @param name - Logger name (usually component/service name)
   * @returns The result.
   */
  getLogger(name?: string): Logger {
    return this.provider.getLogger(name)
  }

  /**
   * Create a logger with custom configuration.
   *
   * @param config - Logger configuration
   * @returns The created instance.
   */
  createLogger(config: LoggerConfig): Logger {
    return this.provider.createLogger(config)
  }

  /**
   * Set the global log level.
   *
   * @param level - Log level
   */
  setLevel(level: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'silent'): void {
    this.provider.setLevel(level)
  }

  /**
   * Get the current global log level.
   *
   * @returns The result.
   */
  getLevel(): string {
    return this.provider.getLevel()
  }

  /**
   * Enable logging.
   */
  enable(): void {
    this.provider.enable()
  }

  /**
   * Disable logging.
   */
  disable(): void {
    this.provider.disable()
  }

  /**
   * Check if logging is enabled.
   *
   * @returns Whether logging is enabled
   */
  isEnabled(): boolean {
    return this.provider.isEnabled()
  }
}

MoleculeRouterService

Angular service for routing.

Wraps molecule router and exposes state as RxJS observables.

@Injectable({
  providedIn: 'root',
})
/**
 * Molecule Router Service class.
 */
export class MoleculeRouterService implements OnDestroy {
  private locationSubject: BehaviorSubject<RouteLocation>
  private paramsSubject: BehaviorSubject<RouteParams>
  private querySubject: BehaviorSubject<QueryParams>
  private unsubscribe: (() => void) | null = null

  /**
   * Observable of the current location.
   */
  location$: Observable<RouteLocation>

  /**
   * Observable of route parameters.
   */
  params$: Observable<RouteParams>

  /**
   * Observable of query parameters.
   */
  query$: Observable<QueryParams>

  /**
   * Observable of the current pathname.
   */
  pathname$: Observable<string>

  constructor(@Inject(ROUTER) private router: Router) {
    this.locationSubject = new BehaviorSubject<RouteLocation>(router.getLocation())
    this.paramsSubject = new BehaviorSubject<RouteParams>(router.getParams())
    this.querySubject = new BehaviorSubject<QueryParams>(router.getQuery())

    this.unsubscribe = router.subscribe(() => {
      this.locationSubject.next(router.getLocation())
      this.paramsSubject.next(router.getParams())
      this.querySubject.next(router.getQuery())
    })

    this.location$ = this.locationSubject.asObservable()
    this.params$ = this.paramsSubject.asObservable()
    this.query$ = this.querySubject.asObservable()

    this.pathname$ = this.location$.pipe(
      map((loc) => loc.pathname),
      distinctUntilChanged(),
    )
  }

  /**
   * Get the current location snapshot.
   * @returns The result.
   */
  get location(): RouteLocation {
    return this.router.getLocation()
  }

  /**
   * Get the current params snapshot.
   * @returns The result.
   */
  get params(): RouteParams {
    return this.router.getParams()
  }

  /**
   * Get the current query snapshot.
   * @returns The result.
   */
  get query(): QueryParams {
    return this.router.getQuery()
  }

  /**
   * Navigate to a path.
   *
   * @param path - Target path
   * @param options - Navigation options
   */
  navigate(path: string, options?: NavigateOptions): void {
    this.router.navigate(path, options)
  }

  /**
   * Navigate to a named route.
   *
   * @param name - Route name
   * @param params - Route parameters
   * @param query - Query parameters
   * @param options - Navigation options
   */
  navigateTo(
    name: string,
    params?: RouteParams,
    query?: QueryParams,
    options?: NavigateOptions,
  ): void {
    this.router.navigateTo(name, params, query, options)
  }

  /**
   * Go back in history.
   */
  back(): void {
    this.router.back()
  }

  /**
   * Go forward in history.
   */
  forward(): void {
    this.router.forward()
  }

  /**
   * Check if a path is currently active.
   *
   * @param path - Path to check
   * @param exact - Whether to match exactly
   * @returns The result.
   */
  isActive(path: string, exact = false): boolean {
    return this.router.isActive(path, exact)
  }

  /**
   * Cleans up subscriptions and completes subjects on service destruction.
   */
  ngOnDestroy(): void {
    this.unsubscribe?.()
    this.locationSubject.complete()
    this.paramsSubject.complete()
    this.querySubject.complete()
  }
}

MoleculeStateService

Angular service for state management.

Wraps molecule state stores and exposes them as RxJS observables.

@Injectable({
  providedIn: 'root',
})
/**
 * Molecule State Service class.
 */
export class MoleculeStateService implements OnDestroy {
  private subscriptions = new Map<Store<unknown>, () => void>()
  private subjects = new Map<Store<unknown>, BehaviorSubject<unknown>>()

  constructor(@Inject(STATE_PROVIDER) private provider: StateProvider) {}

  /**
   * Get an observable of the full store state.
   *
   * @param store - The store to observe
   * @returns Observable of the store state
   */
  observe<T>(store: Store<T>): Observable<T> {
    return this.getOrCreateSubject(store).asObservable() as Observable<T>
  }

  /**
   * Select a piece of state from a store.
   *
   * @param store - The store to select from
   * @param selector - Selector function
   * @returns Observable of the selected state
   */
  select<T, S>(store: Store<T>, selector: (state: T) => S): Observable<S> {
    return this.observe(store).pipe(map(selector), distinctUntilChanged())
  }

  /**
   * Get the current snapshot of a store's state.
   *
   * @param store - The store
   * @returns The result.
   */
  snapshot<T>(store: Store<T>): T {
    return store.getState()
  }

  /**
   * Update a store's state.
   *
   * @param store - The store to update
   * @param partial - Partial state or updater function
   */
  update<T>(store: Store<T>, partial: Partial<T> | ((state: T) => Partial<T>)): void {
    store.setState(partial)
  }

  /**
   * Gets or creates a BehaviorSubject for the given store.
   * @param store - The data store to observe.
   * @returns The BehaviorSubject tracking the store state.
   */
  private getOrCreateSubject<T>(store: Store<T>): BehaviorSubject<T> {
    let subject = this.subjects.get(store as Store<unknown>) as BehaviorSubject<T> | undefined

    if (!subject) {
      subject = new BehaviorSubject<T>(store.getState())
      this.subjects.set(store as Store<unknown>, subject as BehaviorSubject<unknown>)

      const unsubscribe = store.subscribe(() => {
        subject!.next(store.getState())
      })
      this.subscriptions.set(store as Store<unknown>, unsubscribe)
    }

    return subject
  }

  /**
   * Cleans up all store subscriptions and completes subjects on service destruction.
   */
  ngOnDestroy(): void {
    // Clean up all subscriptions
    this.subscriptions.forEach((unsubscribe) => unsubscribe())
    this.subscriptions.clear()

    // Complete all subjects
    this.subjects.forEach((subject) => subject.complete())
    this.subjects.clear()
  }
}

MoleculeStorageService

Angular service for storage.

Wraps molecule storage provider and returns RxJS observables.

@Injectable({
  providedIn: 'root',
})
/**
 * Molecule Storage Service class.
 */
export class MoleculeStorageService {
  constructor(@Inject(STORAGE_PROVIDER) private provider: StorageProvider) {}

  /**
   * Get a value from storage.
   *
   * @param key - Storage key
   * @returns Observable of the value
   */
  get<T>(key: string): Observable<T | null> {
    return from(this.provider.get<T>(key))
  }

  /**
   * Set a value in storage.
   *
   * @param key - Storage key
   * @param value - Value to store
   * @returns Observable that completes when done
   */
  set<T>(key: string, value: T): Observable<void> {
    return from(this.provider.set(key, value))
  }

  /**
   * Remove a value from storage.
   *
   * @param key - Storage key
   * @returns Observable that completes when done
   */
  remove(key: string): Observable<void> {
    return from(this.provider.remove(key))
  }

  /**
   * Clear all values from storage.
   *
   * @returns Observable that completes when done
   */
  clear(): Observable<void> {
    return from(this.provider.clear())
  }

  /**
   * Get all keys in storage.
   *
   * @returns Observable of key array
   */
  keys(): Observable<string[]> {
    return from(this.provider.keys())
  }

  /**
   * Create a reactive storage value with auto-loading.
   *
   * @param key - Storage key
   * @param defaultValue - Default value if not found
   * @returns BehaviorSubject that syncs with storage
   */
  createValue<T>(key: string, defaultValue: T): BehaviorSubject<StorageValueState<T>> {
    const state = new BehaviorSubject<StorageValueState<T>>({
      value: defaultValue,
      loading: true,
      error: null,
    })

    // Load initial value
    this.get<T>(key).subscribe({
      next: (value) => {
        state.next({
          value: value ?? defaultValue,
          loading: false,
          error: null,
        })
      },
      error: (error) => {
        state.next({
          value: defaultValue,
          loading: false,
          error,
        })
      },
    })

    return state
  }

  /**
   * Update a reactive storage value.
   *
   * @param key - Storage key
   * @param value - New value
   * @param state - State subject to update
   */
  updateValue<T>(key: string, value: T, state: BehaviorSubject<StorageValueState<T>>): void {
    state.next({ ...state.value, loading: true })

    this.set(key, value).subscribe({
      next: () => {
        state.next({ value, loading: false, error: null })
      },
      error: (error) => {
        state.next({ ...state.value, loading: false, error })
      },
    })
  }
}

MoleculeThemeService

Angular service for theming.

Wraps molecule theme provider and exposes state as RxJS observables.

@Injectable({
  providedIn: 'root',
})
/**
 * Molecule Theme Service class.
 */
export class MoleculeThemeService implements OnDestroy {
  private themeSubject: BehaviorSubject<Theme>
  private themeNameSubject: BehaviorSubject<string>
  private unsubscribe: (() => void) | null = null

  /**
   * Observable of the current theme.
   */
  theme$: Observable<Theme>

  /**
   * Observable of the current theme name.
   */
  themeName$: Observable<string>

  /**
   * Observable of the theme mode (light/dark).
   */
  mode$: Observable<'light' | 'dark'>

  constructor(@Inject(THEME_PROVIDER) private provider: ThemeProvider) {
    this.themeSubject = new BehaviorSubject<Theme>(provider.getTheme())
    this.themeNameSubject = new BehaviorSubject<string>(provider.getTheme().name)

    this.unsubscribe = provider.subscribe(() => {
      this.themeSubject.next(provider.getTheme())
      this.themeNameSubject.next(provider.getTheme().name)
    })

    this.theme$ = this.themeSubject.asObservable()
    this.themeName$ = this.themeNameSubject.asObservable()

    this.mode$ = this.theme$.pipe(
      map((theme: Theme) => theme.mode),
      distinctUntilChanged(),
    )
  }

  /**
   * Get the current theme snapshot.
   * @returns The result.
   */
  get theme(): Theme {
    return this.provider.getTheme()
  }

  /**
   * Get the current theme name snapshot.
   * @returns The result.
   */
  get themeName(): string {
    return this.provider.getTheme().name
  }

  /**
   * Get available themes.
   * @returns The result.
   */
  get themes(): Theme[] {
    return this.provider.getThemes?.() ?? []
  }

  /**
   * Set the current theme.
   *
   * @param name - Theme name
   */
  setTheme(name: string): void {
    this.provider.setTheme(name)
  }

  /**
   * Toggle to the next theme.
   */
  toggleTheme(): void {
    const themes = this.themes
    const currentName = this.themeName
    const currentIndex = themes.findIndex((t: Theme) => t.name === currentName)
    const nextIndex = (currentIndex + 1) % themes.length
    this.provider.setTheme(themes[nextIndex])
  }

  /**
   * Cleans up subscriptions and completes subjects on service destruction.
   */
  ngOnDestroy(): void {
    this.unsubscribe?.()
    this.themeSubject.complete()
    this.themeNameSubject.complete()
  }
}

SessionReady

Renders its content once useAuth().status has left 'loading' (signed in, signed out, or 'unavailable'), and the [slot=fallback] content until then. It never redirects. An unavailable session is unconfirmed and may still have user === null; handle that status separately from sign-out.

With the bundled JWT client, a stored token and cached user restore synchronously. Token-only and cookie-only sessions need an asynchronous current-user request. Until it answers, useAuth().user is null everywhere, 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. provideMolecule({ auth }) holds bootstrap for that by default; wrap the routes in this component where an app passes awaitSession: false, 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 the auth registration (provideMolecule with auth). A client that nobody initialized starts its restore on this first read. The bundled JWT client bounds each auth request (default 10 seconds) and settles a timeout as 'unavailable'. Custom clients must also settle their initial session status.

Route-level redirects for signed-in-only pages stay with the app's own guards.

@Component({
  selector: 'mol-session-ready',
  standalone: true,
  template: `
    @if (status() === 'loading') {
      <ng-content select="[slot=fallback]" />
    } @else {
      <ng-content />
    }
  `,
})
export class SessionReady {
  /** The auth status this component holds on (`'loading'` shows the fallback). */
  readonly status = useAuth().status
}

MolSlotCopy

Renders a slot's children here, as React renders {children} inside each row, node or gap: every place shows its own copy. Give it the slot's children (SlotReader.nodes of usePlacement) and keep the slot itself out of the page (setElementPresent(capture, false)), so the slot shows no copy of its own.

A *molLazy child is stamped here from its template: a live instance per place, created with this copy and destroyed with it or when the child leaves the slot, as each of React's is. Any other child is copied as DOM (cloneNode), which has no listeners and no components, so content with either is written with *molLazy (MolLazy). A child that stays in the slot keeps its copy here when other children come and go.

```typescript @Directive({ selector: '[molSlotCopy]', standalone: true }) export class MolSlotCopy
implements OnDestroy { /** The slot's children to render here, in order. */ @Input({ required: true
}) molSlotCopy: readonly Node[] = [] /** Where the stamped instances go. */ private readonly views =
inject(ViewContainerRef) /** The directive's own place: the copies sit right before it. */ private
readonly anchor = inject(ElementRef).nativeElement as Comment /** The copies, in render order. */
private copies: Copy[] = [] /** The children the copies were last rendered from. */ private
rendered: readonly Node[] = [] constructor() { // In the same phase as `MolLazy`, after it: a slot's
own lazy children are stamped first, // in the order React mounts them (the original before its
copies). afterEveryRender({ mixedReadWrite: () => this.render() }) } /** Destroys every instance it
stamped. */ ngOnDestroy(): void { for (const copy of this.copies) this.destroy(copy) this.copies =
[] } /** Renders the children it is given, keeping the copy of each child it already shows. */
private render(): void { // `SlotReader.nodes` returns the same array while the children are the
same. if (this.molSlotCopy === this.rendered) return this.rendered = this.molSlotCopy const kept =
new Map(this.copies.map((copy) => [copy.source, copy])) const next = this.molSlotCopy.map((source)
=> { const copy = kept.get(source) if (copy === undefined) return this.create(source)
kept.delete(source) return copy }) for (const gone of kept.values()) this.destroy(gone) // The
stamped instances in their order, so Angular inserts each next to the right neighbour. let index = 0
for (const copy of next) if (copy.view !== null) this.views.move(copy.view, index++) // Then every
copy, back to front, right before the one that follows it. let ref: ChildNode = this.anchor for
(const copy of [...next].reverse()) { const nodes = nodesOf(copy) as ChildNode[] const first =
nodes[0] if (first === undefined) continue if (nodes[nodes.length - 1]?.nextSibling !== ref)
ref.before(...nodes) ref = first } this.copies = next } /** * Renders one child here. * * @param
source - The slot's child. * @returns Its copy. */ private create(source: Node): Copy { const
template = lazySlotTemplate(source) if (template === undefined) return { source, view: null, node:
source.cloneNode(true) } const view = this.views.createEmbeddedView(template) view.detectChanges()
return { source, view, node: null } } /** * Takes one copy out of the page, destroying its instance.
* * @param copy - The copy. */ private destroy(copy: Copy): void { if (copy.view !== null)
copy.view.destroy() else (copy.node as ChildNode).remove() } }

Functions

setHostRoot(host, root, options)

Names the element that stands for the calling component's host: React's {...rest} target. Call it in the component's usePlacement function, for a component whose host is out of the page.

An Angular consumer binds on the component's tag: <mol-switch (keydown)="…" class="…" data-testid="…" [attr.aria-label]="…">. With the host out of the page those would do nothing. Instead, while the host is absent:

  • native listeners are attached to the root ($event.currentTarget is the root, as it is in React);
  • attributes, class names and styles the consumer writes on the tag are written on the root, in the same instruction, and the ones already on the host are moved there.

A component that calls nothing gets the common case for free: with one element in its place (placeElementBefore(root, host)) that element is the root; with several elements or projected content in its place, listeners go to each of them (the events that used to bubble to the host) and attributes stay on the host. A component with nothing in its place (a portal) names its root, or a listener on its tag throws in dev mode: it could never fire.

function setHostRoot(
  host: Element,
  root: Element | null | undefined,
  options?: { except?: readonly string[] },
): void
  • host — The component's host element.
  • root — The element that stands for it, or null while React renders none.
  • options — except: attribute names the component reads off its host itself (it merges them with its own), which stay on the host.
  • options.except — Those attribute names.

provideDomPlacement()

Installs the placement rules in the application's renderer. provideMolecule includes it; a test that mounts a port without provideMolecule adds it to the application's providers. It wraps whatever renderer factory the application configured, so it also applies under an animation renderer.

function provideDomPlacement(): EnvironmentProviders

Returns: The environment providers.

setElementPresent(element, present)

Takes an element out of its parent while present is false and puts it back in the same place once it is true: Angular's equivalent of React's {cond && <span>…</span>} for an element the template must keep (one that holds an <ng-content>). "Attached" means the element has a parent, not that it is in the document, so it also works inside a host that is itself absent. An element that was never taken out is left where Angular put it. An element rendered elsewhere (placeElement, placeElementBefore) leaves that parent too, and true puts it back in its own place. Angular may remove or move the element while it is absent; its placeholder goes then.

function setElementPresent(element: Node | null | undefined, present: boolean): void
  • element — The element (nothing happens without one).
  • present — Whether React would render it now.

heldElement(node)

The element a placeholder stands in for while the element is out of its own place (setElementPresent, placeElement, placeElementBefore). A slot's children (SlotReader.nodes) list such an element as its placeholder; a component that took one of its slot's children out of the page finds that child again with this.

function heldElement(node: Node | null | undefined): Node | undefined
  • node — A node of the rendered tree.

Returns: The element whose place the node holds, or undefined when the node is not a current placeholder.

placeElement(element, target)

Renders an element in another parent while it keeps its place in Angular's view: Angular's equivalent of React's createPortal(child, document.body). An empty comment holds the element's place, so Angular can still insert before it and remove it. null puts it back where Angular put it. Calling it again with the same target moves nothing. If Angular moves the element while it is elsewhere, the element follows Angular and the next call moves it again. When Angular removes the view that holds its place, the element is removed from the other parent too, as React unmounts a portal.

function placeElement(element: Node | null | undefined, target: Node | null): void

placeElementBefore(element, sibling)

Renders an element of the component's template immediately in front of another node, as its sibling: Angular's equivalent of a React component whose root is a fragment, <><div>{children}</div>{portal}</>, where the node is the component's host (kept in the DOM with display: contents).

The element then belongs to the node's place. Angular inserts a new sibling before the element, not between the two; when Angular moves the node (a consumer @for reorders), the element moves with it; when Angular removes the node, the element goes back to its own place inside it and leaves the page with it. Several elements placed before the same node stand in the order they were placed. Calling it again moves nothing while the element already stands there.

"In front of the node" means in front of the node's place. A host that is absent (setElementPresent(host, false)) holds its place with a comment, and the element stands in front of that: this is how a fragment root renders React's exact DOM, with no host element among the siblings at all. A node another component rendered elsewhere (placeElement) is likewise led at its place, not where it was rendered.

Nothing happens while the node has no parent; call it from the component's usePlacement function, which runs again. placeElement(element, null) puts the element back in its own place.

function placeElementBefore(
  element: Node | null | undefined,
  sibling: Node | null | undefined,
): void
  • element — The element (nothing happens without one).
  • sibling — The node it stands in front of, usually the host.

renderedParent(node)

A node's parent in the rendered tree: the parent React context follows. It is the DOM parent, except where this module placed the node:

  • an element that is absent, or rendered in another parent (setElementPresent, placeElement, placeElementBefore), belongs where its placeholder is, the place the template gave it. A portal's content therefore has the component that declared it as an ancestor, not document.body, as in React.
  • a top-level node of a capture's content that renders outside the capture (placeContent, placeContentBefore) belongs to the capture. With placeContentBefore(host, host) that is the host: what a provider renders in its own place is the provider's child, and a sibling that merely shares the DOM parent is not.

So a component looks its context up from its own host and registers one on its own host, whether or not the host is in the page.

function renderedParent(node: Node | null | undefined): Element | null
  • node — The node.

Returns: Its parent in the rendered tree, or null at the top (or for a node that has no place: never inserted, or removed).

placeContent(capture, target, before)

Renders a capture element's content somewhere else: Angular's equivalent of React placing the same {slot} in a different parent depending on props (loading ? <span>{label}</span> : label). The capture element is the template element that holds the <ng-content>.

The whole content moves as one run, Angular's block anchors included, so the consumer's @for and @if keep working at the new place: Angular inserts a view under the parent of its anchor, before a node of the same run. Never move a filtered or remembered list of nodes instead; the anchors or the nodes Angular adds later stay behind (NG05106). Calling it again with the same target moves nothing. When Angular removes the capture (its view went), the content goes back inside it and leaves the page with it.

function placeContent(
  capture: Element | null | undefined,
  target: Node | null,
  before?: Node | null,
): void
  • capture — The element Angular projected the content into.
  • target — The parent to render the content in, or null to put it back inside capture.
  • before — The child of target to place the content before (default: at the end).

placeContentBefore(capture, sibling)

Renders a capture's content immediately in front of another node, as its siblings, with no element around it: Angular's equivalent of a React component whose root is a fragment of what it was given, <>{children}</> (a provider or a gate that renders no DOM of its own). The node is usually the component's host, and the capture may be the host itself: placeContentBefore(host, host) renders everything the host holds in front of it and leaves the host empty.

The content then belongs to the node's place, as an element does with placeElementBefore: Angular inserts a new sibling before the content, the content moves with the node, and it goes back inside the capture when Angular removes the node. Angular's block anchors move with the content, so an @if in the component's own template around <ng-content> and the consumer's blocks render at the new place from the first node on. Nothing happens while the node has no parent; call it from the component's usePlacement function. placeContent(capture, null) puts the content back.

function placeContentBefore(
  capture: Element | null | undefined,
  sibling: Node | null | undefined,
): void
  • capture — The element that holds the content (nothing happens without one).
  • sibling — The node the content stands in front of, usually the host.

hasContent(capture) (deprecated)

Deprecated: Use the reader usePlacement passes.

Reads a slot from a lifecycle hook, which can lag the content: a hook runs before the consumer's @if adds its node, and no hook runs at all when the content comes through an OnPush component in between. Read slots in the function passed to usePlacement instead; this export goes in the next major version.

function hasContent(capture: Node | null | undefined): boolean
  • capture — The capture.

Returns: Whether the slot has content.

usePlacement(place)

Registers the calling component's placement function: the one place where it decides, from its inputs and its projected content, which of its template elements are present (setElementPresent) and where its slots render (placeContent, placeElement). Call it in the constructor.

The component writes no lifecycle hook for this. The function runs:

  • right after Angular adds, removes or changes a node of a slot the function read, in the same instruction — in whatever pass and from whatever template the node came, so the decision never lags the content and the new content is in the page before its own ngAfterViewInit;
  • when a signal it read changed (an effect);
  • when the component's view was first rendered and each time its parent checks it (MolPlacement, which the component lists in hostDirectives), so a plain input is followed in any kind of change detection, a bare detectChanges() included;
  • after every render.

hasContent is the only way to ask whether a slot has content, and it works only while the function runs: a lifecycle hook cannot read a slot, because no hook runs at a moment when the slot is known to be current (ngDoCheck runs before the consumer's @if adds its node; no hook at all runs when the content comes through an OnPush component in between).

function usePlacement(place: (hasContent: SlotReader) => void): void
  • place — The placement function. It gets hasContent.

useHostPresence(isPresent)

Keeps the calling component's host element out of the DOM while isPresent() is false: Angular's equivalent of a React component that returns null. Call it in the component's injection context.

The host is put back before the component's own view refreshes whenever that is knowable: when a signal isPresent reads changed (an effect, which Angular runs before the view), and when Angular renders the first node into the absent host (so an @if branch that turns on with a plain input is built inside the document). Every render ends with the same check, which covers a predicate that reads what the render produced; a host restored there gets one more check with its content in the page.

function useHostPresence(isPresent: () => boolean): void
  • isPresent — Whether the component renders anything now. It may read inputs, plain fields or signals.

useExternalStore(read, subscribe)

Subscribes to an external store and mirrors its value into a signal, with React's read discipline. Call it in an injection context.

function useExternalStore<T>(
  read: () => T,
  subscribe: (notify: () => void) => () => void,
): Signal<T>
  • read — Reads the store's current snapshot (records on the provider); must return a stable object between notifications.
  • subscribe — Subscribes to the store; receives the hook's own snapshot-invalidating callback and returns the unsubscribe function.

Returns: A signal of the store's current snapshot.

usePromise(asyncFn)

Wraps an async function with the state of its latest call. Call it in an injection context (a component field initializer or constructor).

For one UI action, pass state.status === 'pending' to a button's loading input. The control then refuses input while the request is pending and re-enables when the tracked call settles. Handle the returned promise's rejection; the hook also records the failure in state.error.

This hook tracks the latest call: it does not serialize invocations or cancel their network requests. An explicit reset/cancel changes the tracked state, so it is not proof that an outstanding request has stopped. Use an app-owned queue when every click must be accepted in order.

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

Returns: A tuple of [state, wrappedFunction]; the state object is updated in place for this instance's lifetime.

useAsyncState(initialState)

Like useState but accepts Promises and supports partial state extension. Call it in an injection context.

There is NO latest-wins guard (pinned like React's): whatever settles last wins, even over a newer synchronous set.

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

Returns: A tuple of [state, setState, extendState]; the state member is replaced in place for this instance's lifetime.

useOptimisticValue(options)

A server-backed value — a favorite, follow, like or bookmark button, a rating, a quantity, a setting switch — that changes on the first read after a tap and is saved one change at a time, in order. Call it in an injection context.

Only a failure of the newest change puts the server value back. A new server value is taken only while nothing is being saved, so a parent re-render or a refetch of older data never flips the control mid-save.

The options may be a signal, and the controller follows them the way React's re-render does: commit, equals and onError are read from the options the signal holds at the moment they run, and a server value that differs (by equals) from the last one received is synced in — kept as the fallback while a save runs — with the controller and any pending save kept on the same component.

function useOptimisticValue<T>(
  options: MaybeSignal<OptimisticValueOptions<T>>,
): UseOptimisticValueResult<T>
  • options — The server's current value and how to save a change (or a signal of them).

Returns: The value to render, whether a save is pending, the newest failure, and set/update.

useLogin()

Login with async state tracking. Call it in an injection context.

Registration is available through const { register } = useAuth(); call register({ email, password, name }) to create an account. There is no separate useRegister hook. Use usePromise(register) when the form needs the same pending/error tracking as this login hook.

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

Returns: Login state and action.

useSignup()

Registration with async state tracking. Call it in an injection context.

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

Returns: Signup state and action.

useChangePassword()

Changing a password with async state tracking. Call it in an injection context.

function useChangePassword(): UseChangePasswordReturn

Returns: Change-password state and action.

usePasswordReset()

The password reset flow with async state tracking, one tracker per step. Call it in an injection context.

function usePasswordReset(): UsePasswordResetReturn

Returns: Password reset state and actions.

useOAuth(config)

OAuth authentication. Call it in an injection context.

Reads OAuth configuration from the provided config and provides helpers to build OAuth URLs and start a login (full-page or popup). Automatically handles OAuth callbacks by detecting code and state URL parameters and exchanging them for a session — and, when the callback is running inside a popup we opened, relaying the result to the opener instead.

The config may be a signal, and the result follows it the way React's re-render does: providers reads the config at the moment it is read, getOAuthUrl builds from the config at call time, and a flow (redirect, loginViaPopup, a callback exchange) uses the config it was started with, like the render closure React started it from.

Unmounting does not cancel a flow that has started. A popup result or a callback exchange that settles afterwards still establishes the session on the shared auth client, because the user did sign in. onSuccess and onError are not called after unmount: they belong to the unmounted view.

function useOAuth(config?: MaybeSignal<UseOAuthConfig>): UseOAuthReturn
  • config — Optional OAuth configuration override (see UseOAuthConfig), or a signal of it.

Returns: OAuth helpers: providers, getOAuthUrl, redirect, and loginViaPopup.

useAuthClient()

The auth client registered by provideMolecule({ auth }) or provideAuth. Call it in an injection context.

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

Returns: The auth client.

useAuth(options)

Authentication state and actions. Call it in an injection context (a component field initializer or constructor).

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 while a token/cookie-only restore has no cached profile. A restore failure other than 401/403 never signs out.

The options may be a signal: autoRefresh turning on through it probes once (when the visitor is signed out and decided), the way React re-renders useAuth with the new option.

function useAuth<
  T = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(options?: MaybeSignal<UseAuthOptions>): UseAuthResult<T, TRegister>
  • options — Hook options (autoRefresh), or a signal of them.

Returns: Auth state as signals and the auth actions.

useUser()

The signed-in user alone. Call it in an injection context.

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

Returns: A signal of the authenticated user or null.

useIsAuthenticated()

Whether a session exists. Call it in an injection context.

function useIsAuthenticated(): Signal<boolean>

Returns: A signal of the authentication flag.

useForm(options)

Form state management. Call it in an injection context (a component field initializer or constructor).

Creates its controller through the bonded forms provider, so an app wires a form library once (setProvider from @molecule/app-forms) and every form picks it up. Passing createForm overrides that for one form.

The options may be a signal, and the hook follows them the way React's re-render does: when values changes by content, it becomes the new baseline; resetOptions.keepDirtyValues retains edited fields while pristine fields take the loaded values. A changed resetKey starts a fresh form; new defaultValues without one leave the form (and its drafts) alone.

function useForm<T extends FormValuesConstraint<T> = Record<string, unknown>>(
  options?: MaybeSignal<UseFormOptions<T>>,
): UseFormResult<T>
  • options — Form options (or a signal of them).

Returns: Form state as signals and the form methods.

useWatch(form, name)

Watches one field's value. Call it in an injection context.

The controller and name may be signals, so a new controller or field is followed the way React re-renders useWatch with new arguments.

function useWatch<T extends FormValuesConstraint<T>, K extends keyof T>(
  form: MaybeSignal<FormController<T>>,
  name: MaybeSignal<K>,
): Signal<T[K]>
  • form — Form controller (or a signal of it).
  • name — Field name to watch (or a signal of it).

Returns: The current field value as a signal.

useFieldState(form, name)

Reads one field's state. Call it in an injection context.

The controller and name may be signals, so a new controller or field is followed the way React re-renders useFieldState with new arguments.

function useFieldState<T extends FormValuesConstraint<T>>(
  form: MaybeSignal<FormController<T>>,
  name: MaybeSignal<keyof T>,
): Signal<FieldState<T[keyof T]>>
  • form — Form controller (or a signal of it).
  • name — Field name (or a signal of it).

Returns: The field state as a signal.

useHttpClient()

The HTTP client registered by provideMolecule({ http }) or provideHttp. Call it in an injection context.

function useHttpClient(): HttpClient

Returns: The HTTP client.

useHttp(method, url, options)

HTTP requests with state management. Call it in an injection context (a component field initializer or constructor).

execute keeps one identity for the component's lifetime; the request it performs is the one the method, url and options sources hold when it is called. The current headers, body, signal and callbacks are read when execute is called, so an inline options object or callback needs no memoizing.

The arguments may be signals: execute then sends to the url the signal holds at the moment it is called, the way React's re-rendered useHttp sends to the latest url. The hook's state (an in-flight request, loaded data) survives an argument change, as React's survives a re-render.

The newest request owns the state: an older request that answers after a newer one (or after reset) cannot repopulate the displayed state, though its own callbacks still report its outcome.

function useHttp<T>(
  method: MaybeSignal<'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'>,
  url: MaybeSignal<string>,
  options?: MaybeSignal<UseHttpOptions<T>>,
): UseHttpResult<T>
  • method — HTTP method (or a signal of it).
  • url — Request URL (or a signal of it).
  • options — Request options, read at call time (or a signal of them).

Returns: The request state as signals and the execute/reset functions.

useGet(url, options)

GET requests.

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

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

usePost(url, options)

POST requests, with the body in options.data.

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

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

usePut(url, options)

PUT requests, with the replacement body.

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

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

usePatch(url, options)

PATCH requests, with the partial body.

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

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

useDelete(url, options)

DELETE requests; a body travels in options.data.

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

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

useWorkspaceProvider()

The workspace provider registered by provideMolecule({ workspace }) or provideWorkspace. Call it in an injection context.

function useWorkspaceProvider(): WorkspaceProvider

Returns: The workspace provider.

useWorkspace()

IDE workspace layout management. Call it in an injection context (a component field initializer or constructor).

function useWorkspace(): UseWorkspaceResult

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

useEditorProvider()

The editor provider registered by provideMolecule({ editor }) or provideEditor. Call it in an injection context.

function useEditorProvider(): EditorProvider

Returns: The editor provider.

useEditor()

Code editor management. Call it in an injection context (a component field initializer or constructor).

tabs and activeFile always come from the provider's own tab list: activeFile is the path of the tab marked isActive, or null when no tab is. They are read at mount (tabs opened before the component mounted show at once), on every provider change event, and after each action that changes the tab list (openFile, closeFile, setActiveTab, openDiff, closeDiff, pinTab).

function useEditor(): UseEditorResult

Returns: Editor state as signals and the editor actions.

usePreviewProvider()

The preview provider registered by provideMolecule({ preview }) or providePreview. Call it in an injection context.

function usePreviewProvider(): PreviewProvider

Returns: The preview provider.

usePreview()

Live preview management. Call it in an injection context (a component field initializer or constructor).

function usePreview(): UsePreviewResult

Returns: The preview state as a signal and the preview actions.

useLoggerProvider()

The logger provider registered by provideMolecule({ logger }) or provideLogger. Call it in an injection context.

function useLoggerProvider(): LoggerProvider

Returns: The logger provider.

useLogger(name, config)

A named logger from the registered provider. Call it in an injection context.

function useLogger(name: string, config?: Partial<LoggerConfig>): Logger
  • name — Logger name (usually the component or module name).
  • config — Optional configuration; a name in it wins over name.

Returns: The logger instance.

useRootLogger()

The provider's unnamed root logger. Call it in an injection context.

function useRootLogger(): Logger

Returns: The root logger instance.

useChildLogger(parentName, context)

A child logger whose context rides every call. Call it in an injection context.

function useChildLogger(parentName: string, context: Record<string, unknown>): Logger
  • parentName — The parent logger's name.
  • context — Additional context included in every log call.

Returns: The child logger instance.

useDevice()

Device information and utility methods. Call it in an injection context.

Uses module-level getProvider() — device info is a singleton, not registration-provided. Device info is static and doesn't change at runtime, so it is read once, like React's memoized hook.

function useDevice(): UseDeviceResult

Returns: Device information and utility methods.

usePlatform()

Platform detection. Call it in an injection context.

Uses module-level functions — platform is a singleton, not registration-provided. Platform info is static and doesn't change at runtime, so it is read once, like React's memoized hook.

function usePlatform(): UsePlatformResult

Returns: Platform information and utility methods.

useCapacitorApp(options)

Capacitor app initialization and state management. Call it in an injection context (a component field initializer or constructor).

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

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

Returns: The current app state as signals and an initialize function.

useOptimisticToggle(options)

Owns the state and save ordering of a follow, favorite, star or subscription control while all markup stays in the component's template. Bind 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. Call it in an injection context.

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. Create it only after the record loads, one per record, and keep it through refetches. For a flag with a related count, use useOptimisticValue with both fields in one value.

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

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

useProfileForm(options)

Owns load → edit → submit → publish for the signed-in user's profile. Call it in an injection context (a component field initializer or constructor).

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 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 registered by provideMolecule({ router }) or provideRouter. Call it in an injection context.

function useRouterInstance(): Router

Returns: The router instance.

useLinkRouter(to)

The router a link navigates through, React's useLinkRouter in Angular's idiom: the registered router, or null for a URL outside the app when none is. 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 register its router finds out.

The Link directive uses it. With a destination it answers for that one and follows it while the injector's host lives. Without one (a directive's input is not set when its field initializers run) it returns a function to call with the destination wherever it is known. Call it in an injection context (a constructor or a field initializer), which reads the injector once.

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

Returns: A signal of the router the link navigates through, or null for a URL outside the app with no router registered.

useRouter()

Routing state and actions. Call it in an injection context (a component field initializer or constructor).

function useRouter(): UseRouterResult

Returns: The location, params and query as signals, and the navigation actions.

useLocation()

The current location alone. Call it in an injection context.

function useLocation(): Signal<RouteLocation>

Returns: A signal of the current route location.

useParams()

The current path parameters alone. Call it in an injection context.

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

Returns: A signal of the current path parameters.

useQuery()

The current query parameters alone. Call it in an injection context.

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

Returns: A signal of the current query parameters.

useNavigate()

A navigate function alone. Call it in an injection context.

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

Returns: The navigate function.

useIsActive(path, exact)

Whether a path is active, re-evaluated on every route change. Call it in an injection context.

The arguments may be signals: the active flag then follows a changed path or exact on the same component, the way React re-renders useIsActive with new arguments. A signal holding undefined for exact matches an omitted argument (false).

function useIsActive(
  path: MaybeSignal<string>,
  exact?: MaybeSignal<boolean | undefined>,
): Signal<boolean>
  • path — The path to check (or a signal of it).
  • exact — Whether to match exactly (default: false, or a signal of it).

Returns: A signal of whether the path is active.

useListRoute(options)

URL-backed pagination, filters and selected views, through whichever routing bond the app wired: 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. Call it in an injection context (a component field initializer or constructor).

The options may be a signal: an auth status going from loading to unauthenticated reaches the list on the same component, the way React re-renders useListRoute with new options.

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.

function useListRoute<Filter extends string = string, Selection extends string = string>(
  options?: MaybeSignal<ListRouteOptions<Filter, Selection>>,
): UseListRouteResult<Filter, Selection>
  • options — Filter sources, view paths, pagination and optional auth readiness (or a signal of them).

Returns: The list state (page, offset, filters, selection, canLoad) as signals, and the list's link builder and navigation actions.

useConsumedSearchParam(name)

Takes a one-time credential (a reset token, an OAuth code) out of the URL and keeps it in memory, 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 the component's lifetime, and Back to an entry restores the value consumed there. Call it in an injection context (a component field initializer or constructor).

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

Returns: The consumed value ('' before the parameter was ever present) and a setter (a form clears it after a successful submit).

useStorageProvider()

The storage provider registered by provideMolecule({ storage }) or provideStorage. Call it in an injection context.

function useStorageProvider(): StorageProvider

Returns: The storage provider.

useStorageValue(key, options)

Manages one storage value. Call it in an injection context (a component field initializer or constructor).

A write bumps a version counter, so a read that started before it never replaces the newer value; a read that started before a write still ends loading. sync subscribes through the PROVIDER's own change subscription, so a non-browser backend propagates the same way instead of being limited to the browser storage event.

The arguments may be signals: a new key then starts over on the same component (the value falls back to the default, loading turns true and the new key is read and subscribed), the way React re-renders useStorageValue with a new key. The value, its pending write and any error survive the change, as React's state does.

function useStorageValue<T>(
  key: MaybeSignal<string>,
  options?: MaybeSignal<UseStorageValueOptions<T>>,
): UseStorageValueResult<T>
  • key — Storage key (or a signal of it).
  • options — Hook options (defaultValue, sync), or a signal of them.

Returns: The value, its mutators, and the loading/error state as signals.

useStoragePreference(key, options)

Subscribes to ONE persisted preference through getPreferenceStore(). Call it in an injection context (a component field initializer or constructor).

This is the component-side half of getPreferenceStore(): a value read at injection time is available immediately when the bonded provider can answer synchronously, and an asynchronous provider's hydration CONVERGES onto the same component without a remount. Ordering is the store's: a read that started before a newer write, remove or external change is discarded, so a slow hydration never overwrites an edit the user already made.

Pass null for key while the real key is unknown (no project selected yet): the hook then behaves as local state around defaultValue and persists nothing.

The arguments may be signals: a new key then re-reads and re-subscribes that key on the same component (its old subscription is dropped, hydration converges it), the way React re-renders useStoragePreference with a new key. The shown value survives the change, as React's state does.

function useStoragePreference<T = unknown>(
  key: MaybeSignal<string | null | undefined>,
  options?: MaybeSignal<UseStoragePreferenceOptions<T>>,
): UseStoragePreferenceResult<T>
  • key — The storage key, or null when there is nothing to persist (or a signal of it).
  • options — defaultValue, reported until the provider supplies one (or a signal of them).

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

useStorage()

The registered provider's operations as stable functions, no reactive state. Call it in an injection context.

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: The get/set/remove/clear/keys functions.

useStateProvider()

The state provider registered by provideMolecule({ state }) (by default the provider bonded under @molecule/app-state). Call it in an injection context.

Only hooks that read the registration call this; useStore(store) takes its store as an argument and works with no provider at all.

function useStateProvider(): StateProvider

Returns: The state provider.

useStore(store, options)

Subscribes to a store with an optional selector and equality function. Call it in an injection context.

The store is the argument, so this function needs NO registration: it reads store.getState() and subscribes with store.subscribe(), and never touches the state registration. A store minted outside the state bond — the direct createStoreWithActions() / createStore() a provider package exports — is therefore as valid here as one @molecule/app-state's createStore() made.

The arguments may be signals: a new store is subscribed in place of the old one (the old subscription is dropped first) and new options are applied on the next read, the way React re-renders useStore with new arguments. The previous selected value the equality function compares survives the change, as React's ref does.

function useStore<T>(
  store: MaybeSignal<Store<T>>,
  options?: MaybeSignal<UseStoreOptions<T, T>>,
): Signal<T>
  • store — The store to subscribe to (or a signal of it).
  • options — Hook options (selector, equalityFn), or a signal of them.

Returns: A signal of the selected state.

useSetStore(store)

The store's setState function. Call it in an injection context.

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 and getState. Call it in an injection context.

The action receives the store's setState and getState on every call, so it reads fresh state each time (like React's, which re-runs action(setState, getState) per call).

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 — The action function that receives setState and getState.

Returns: A bound action function.

useThemeProvider()

The theme provider registered by provideMolecule({ theme }) or provideTheme. Call it in an injection context.

function useThemeProvider(): ThemeProvider

Returns: The theme provider.

useTheme()

Theme state and actions. Call it in an injection context (a component field initializer or constructor).

function useTheme(): UseThemeResult

Returns: The theme, its name and mode as signals, and the actions.

useCurrentTheme()

The current theme object alone. Call it in an injection context.

function useCurrentTheme(): Signal<Theme>

Returns: A signal of the current theme.

useThemeMode()

The current theme mode alone. Call it in an injection context.

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

Returns: A signal of 'light' or 'dark'.

useThemeColors()

The current theme's color palette. Call it in an injection context.

function useThemeColors(): Signal<Theme['colors']>

Returns: A signal of the current theme's colors.

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 registered by provideMolecule({ i18n }) or provideI18n, otherwise the bonded @molecule/app-i18n provider — the one the static t reads. Call it in an injection context.

function useI18nProvider(): I18nProvider

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

useTranslation()

Translation, locale state and the formatters. Call it in an injection context (a component field initializer or constructor).

function useTranslation(): UseTranslationResult

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

useT()

The translation function alone. Call it in an injection context.

The returned function keeps ONE identity for as long as the provider is unchanged; it reads the active locale and the locale notifications on every CALL, so its text is current and its caller re-runs on a switch.

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.
function useT(): UseTFunction

Returns: The translation function.

useLocale()

The active locale code alone. Call it in an injection context.

function useLocale(): Signal<string>

Returns: A signal of the locale code.

useDirection()

The active locale's text direction alone. Call it in an injection context.

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

Returns: A signal of 'ltr' or 'rtl'.

useI18nError(error)

Translates an error at read time, so the displayed message follows locale changes. An I18nError is translated through its key (its own message as the default value); a plain Error returns its message unchanged; no error returns null. Call it in an injection context.

The error may be a signal: the message then follows a changed error on the same component, the way React re-renders useI18nError with a new argument.

function useI18nError(error: MaybeSignal<Error | null | undefined>): Signal<string | null>
  • error — The error to translate, or null/undefined (or a signal of it).

Returns: A signal of the error's display text, or null.

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. Call it in an injection context (a component field initializer or constructor).

This is why a hosted checkout returns the buyer to the APP and not the API. Session cookies are host-only on the app's origin, so a top-level redirect from the provider straight to an authenticated API callback on a different host arrives with NO credentials — it answers 401 and the paid plan is never granted. The request this hook makes is a same-origin call from a loaded app page, so the credentials apply. It waits for auth to hydrate first: after the redirect the page is a cold load, and the session is restored from the httpOnly cookie via GET /users/me.

Verification is idempotent server-side (first-claim-wins on the transaction), and this hook additionally runs at most once per transaction id per page. Safe on pages that are also reached normally: with no id in the URL it stays idle and issues no request.

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: by then the address may belong to another page. A failure after unmount is logged instead.

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

Returns: The verification state as signals.

useVersion()

Version state and update actions. Call it in an injection context (a component field initializer or constructor).

Uses module-level getProvider() — version is a singleton, not registration-provided. The state snapshot is cached field-wise (like React's hook), so a provider that builds a fresh object per read keeps the snapshot stable between notifications.

function useVersion(): UseVersionResult

Returns: Version state as signals and the update actions.

bumpLocaleVersion()

Bump the locale version signal, causing all template bindings that use the reactive t() to re-evaluate on the next change detection cycle.

Called automatically by the environment initializer provideMolecule registers.

function bumpLocaleVersion(): void

t(key, values, options)

Translate a key using the current locale.

This is a signal-aware wrapper around @molecule/app-i18n's t(). Reading the internal locale signal establishes an Angular reactivity dependency, so template bindings that call this function will be re-evaluated when the locale changes.

function t(
  key: string,
  values: InterpolationValues | undefined,
  options: TranslateOptions | undefined,
): string
  • key — Translation key
  • values — Interpolation values
  • options — Options (defaultValue, count).
  • options.defaultValue — Fallback string when no translation is found.
  • options.count — Pluralization count.

Returns: Translated string

isLazySlotAnchor(node)

Whether a node is the anchor of a MolLazy slot. A lazy slot is one child of the component it is passed to, stamped or not (React's children holds the element either way): a slot reader counts its anchor as content and as the child, so the wrapper that holds it is in the page, and a component that hides a child takes the anchor out of the page, which destroys the content.

function isLazySlotAnchor(node: Node): boolean
  • node — A node of a slot.

Returns: Whether it is a lazy slot's anchor.

isElementChild(node)

Whether a slot's child is an element, as React's isValidElement(child) tells an element from text: an element, or a MolLazy slot, which stands for the element it stamps whether or not it is stamped yet. Use it to pick a slot's elements out of SlotReader.nodes; a component that then moves the child (placeElement) moves the lazy slot, which stamps its content in the new place.

function isElementChild(node: Node): boolean
  • node — A child of a slot (SlotReader.nodes).

Returns: Whether it is an element child.

slotElement(node)

The element a slot's child is, for a component that works the child itself (React's cloneElement(child, …): a trigger that gets the listeners and aria-*, an anchor a popup is positioned against): the child when it is an element, the element a MolLazy child stamped once it is stamped, else null. A lazy child is stamped after the placement that put it in the page, and stamping it runs that placement again, which then finds the element; decide the layout from isElementChild meanwhile, so the child is not given a wrapper it then leaves.

function slotElement(node: Node): Element | null
  • node — A child of a slot (SlotReader.nodes).

Returns: The element, or null.

lazySlotTemplate(node)

The template of a MolLazy slot, which a component that renders a slot's children in more than one place stamps in each of them (MolSlotCopy does this): each copy is then a live instance, as each of React's is. Plain projected content exists once in Angular; a copy of it (cloneNode) has no listeners or components.

function lazySlotTemplate(node: Node): TemplateRef<unknown> | undefined
  • node — A child of a slot (SlotReader.nodes).

Returns: The lazy slot's template, or undefined when the node is not a lazy slot's anchor.

isLazySlotContent(node)

Whether a node is a root node of a MolLazy slot's stamped content: part of the child its anchor stands for (isLazySlotAnchor), not a child of its own.

function isLazySlotContent(node: Node): boolean
  • node — A node of a slot.

Returns: Whether it is stamped lazy content.

readMaybeSignal(value)

Reads a hook argument's current value. Inside a computed or effect this TRACKS a signal argument, so the reader re-runs when the argument changes; outside one it is a plain read.

function readMaybeSignal<T>(value: MaybeSignal<T>): T
  • value — The argument as the hook received it.

Returns: The argument's current value.

rendersNode(node)

Whether a node input 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, a default or an aria-* reference only while a node prop has something to show reads the same in both: title="" renders no heading, like an omitted title. Projected content is read with the SlotReader of usePlacement instead, which already counts only what renders.

function rendersNode(node: unknown): boolean
  • node — The input's value.

Returns: True when it renders something.

provideState(provider)

Provide state management.

function provideState(provider: StateProvider): EnvironmentProviders
  • provider — State provider

Returns: Environment providers

provideAuth(client)

Registers an AuthClient as an Angular environment provider for dependency injection.

function provideAuth<T>(client: AuthClient<T>): EnvironmentProviders
  • client — Auth client

Returns: Environment providers

provideTheme(provider)

Registers a ThemeProvider as an Angular environment provider for dependency injection.

function provideTheme(provider: ThemeProvider): EnvironmentProviders
  • provider — Theme provider

Returns: Environment providers

provideRouter(router, options)

Registers a Router as an Angular environment provider for dependency injection.

function provideRouter(
  router: Router | (() => Router),
  options?: { routedView?: Type<unknown> },
): EnvironmentProviders
  • router — The router, or a function that returns it. The function runs once, in the environment injector's injection context, the first time the router is injected: a routing bond builds its router from the framework router it injects there.
  • options — From a routing bond: its routed view (see RoutedView).
  • options.routedView — The component that renders the matched child route where a layout or guard puts it. Left out when the bond has none, and RoutedView then throws an error saying so.

Returns: Environment providers, provideDomPlacement included: RoutedView and a bond's routed view render the page with no element of their own.

provideI18n(provider)

Registers an I18nProvider as an Angular environment provider for dependency injection.

function provideI18n(provider: I18nProvider): EnvironmentProviders
  • provider — I18n provider

Returns: Environment providers

provideHttp(client)

Provide HTTP client.

function provideHttp(client: HttpClient): EnvironmentProviders
  • client — HTTP client

Returns: Environment providers

provideStorage(provider)

Registers a StorageProvider as an Angular environment provider for dependency injection.

function provideStorage(provider: StorageProvider): EnvironmentProviders
  • provider — Storage provider

Returns: Environment providers

provideLogger(provider)

Registers a LoggerProvider as an Angular environment provider for dependency injection.

function provideLogger(provider: LoggerProvider): EnvironmentProviders
  • provider — Logger provider

Returns: Environment providers

provideWorkspace(provider)

Registers the IDE workspace provider useWorkspace and useWorkspaceProvider use.

function provideWorkspace(provider: WorkspaceProvider): EnvironmentProviders
  • provider — Workspace provider

Returns: Environment providers

provideEditor(provider)

Registers the code editor provider useEditor and useEditorProvider use.

function provideEditor(provider: EditorProvider): EnvironmentProviders
  • provider — Editor provider

Returns: Environment providers

providePreview(provider)

Registers the live preview provider usePreview and usePreviewProvider use.

function providePreview(provider: PreviewProvider): EnvironmentProviders
  • provider — Preview provider

Returns: Environment providers

provideMolecule(config)

Provide all molecule services at once.

function provideMolecule(config: MoleculeModuleConfig): EnvironmentProviders
  • config — Configuration with all providers

Returns: Environment providers

createAsyncState(initialState)

Creates an async-capable state manager.

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

Returns: The created instance.

createCapacitorAppState(options)

Creates an Angular Capacitor app service with reactive state.

Wraps createCapacitorApp from @molecule/app-platform and exposes state changes as RxJS observables.

function createCapacitorAppState(options?: CapacitorAppOptions): CapacitorAppManager
  • options — Capacitor app configuration options

Returns: Capacitor app manager with observables and action methods

createChangePasswordState(client)

Creates a change password state manager with async state tracking.

Generic over the client's user type like createLoginState, so the client the AUTH_CLIENT token provides (AuthClient<unknown>) is accepted as it is.

function createChangePasswordState<T = unknown>(client: AuthClient<T>): ChangePasswordStateManager
  • client — Auth client

Returns: Change password state manager

createDeviceService()

Creates an Angular device service with static device information.

function createDeviceService(): DeviceService

Returns: Device service with device, screen, hardware, and feature info

createLoginState(client)

Creates a login state manager with async state tracking.

function createLoginState<T = unknown>(client: AuthClient<T>): LoginStateManager<T>
  • client — Auth client

Returns: Login state manager

createOAuthState(options)

Creates an OAuth state manager.

Automatically handles OAuth callbacks: when created in a browser, it invokes OAuthStateManager.handleCallback immediately (a guarded no-op when the URL carries no code parameter).

function createOAuthState(options?: OAuthOptions): OAuthStateManager
  • options — OAuth configuration

Returns: The created instance.

createPasswordResetState(client)

Creates a password reset state manager with async state tracking.

Generic over the client's user type like createLoginState, so the client the AUTH_CLIENT token provides (AuthClient<unknown>) is accepted as it is.

function createPasswordResetState<T = unknown>(client: AuthClient<T>): PasswordResetStateManager
  • client — Auth client

Returns: Password reset state manager

createPlatformService()

Creates an Angular platform service with static platform information.

function createPlatformService(): PlatformService

Returns: Platform service with platform flags and isPlatform check

createPromiseState(asyncFn)

Creates a promise state manager for tracking async function state.

function createPromiseState<Args extends unknown[], T>(
  asyncFn: (...args: Args) => Promise<T>,
): PromiseStateManager<T, Args>
  • asyncFn — The async function to track

Returns: Promise state manager with observable state

createSignupState(client)

Creates a signup state manager with async state tracking.

function createSignupState<T = unknown>(client: AuthClient<T>): SignupStateManager<T>
  • client — Auth client

Returns: Signup state manager

createVersionService()

Creates an Angular version service with reactive state.

function createVersionService(): VersionService

Returns: The created instance.

Constants

STATE_PROVIDER

Injection token for state provider.

const STATE_PROVIDER: InjectionToken<StateProvider>

AUTH_CLIENT

Injection token for auth client.

const AUTH_CLIENT: InjectionToken<AuthClient<unknown, Record<never, never>>>

THEME_PROVIDER

Injection token for theme provider.

const THEME_PROVIDER: InjectionToken<ThemeProvider>

ROUTER

Injection token for router.

const ROUTER: InjectionToken<Router>

I18N_PROVIDER

Injection token for i18n provider.

const I18N_PROVIDER: InjectionToken<I18nProvider>

HTTP_CLIENT

Injection token for HTTP client.

const HTTP_CLIENT: InjectionToken<HttpClient>

STORAGE_PROVIDER

Injection token for storage provider.

const STORAGE_PROVIDER: InjectionToken<StorageProvider>

LOGGER_PROVIDER

Injection token for logger provider.

const LOGGER_PROVIDER: InjectionToken<LoggerProvider>

WORKSPACE_PROVIDER

Injection token for the IDE workspace provider.

const WORKSPACE_PROVIDER: InjectionToken<WorkspaceProvider>

EDITOR_PROVIDER

Injection token for the code editor provider.

const EDITOR_PROVIDER: InjectionToken<EditorProvider>

PREVIEW_PROVIDER

Injection token for the live preview provider.

const PREVIEW_PROVIDER: InjectionToken<PreviewProvider>

Injection Notes

Requirements

Peer dependencies:

  • @angular/core ^22.0.0
  • @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-angular-router >=1.4.0 (optional)
  • @molecule/app-state ^1.2.0
  • @molecule/app-storage ^1.1.1
  • @molecule/app-theme ^1.0.2 (optional)
  • @molecule/app-ui ^1.0.1 (optional)
  • @molecule/app-utilities ^1.0.1 (optional)
  • @molecule/app-version ^1.0.1
  • rxjs ^7.8.0

Runtime Dependencies

  • @angular/core

  • @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-angular-router (optional)

  • @molecule/app-state

  • @molecule/app-storage

  • @molecule/app-theme (optional)

  • @molecule/app-ui (optional)

  • @molecule/app-utilities (optional)

  • @molecule/app-version

  • rxjs

  • Peer requirements: Angular 22 (@angular/core is pinned to 22.0.0) and rxjs 7.8+.

  • Translations: import t from THIS package, not from @molecule/app-i18n. The re-exported t reads an internal Angular signal, so template bindings that CALL it (expose it on the component as above) re-evaluate automatically when the locale changes; the plain app-i18n t — or a one-time field assignment like title = t(...) — renders once and goes stale. The signal is bumped by provideMolecule — pass your i18n provider there (or call bumpLocaleVersion() from your own locale-change hook) for the reactivity to fire.

  • provideMolecule only registers the providers you pass; injecting a Molecule service whose token was never provided fails at DI time. Per-concern helpers (provideAuth, provideTheme, ...) exist for piecemeal setup.

  • The Molecule Angular components render through provideDomPlacement(), which provideMolecule includes. An app or test that mounts them without provideMolecule adds provideDomPlacement() to its providers; a component that needs it throws a message naming it. A component never moves a node Angular rendered (appendChild, insertBefore, remove): it uses useHostPresence, setElementPresent, placeElement, placeContent or WrappedChildren, which keep Angular's own inserts working (NG05106).

  • In-app links use the Link directive (<a molLink="/settings">, imports: [Link]): it navigates through the molecule 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-angular/chat, @molecule/app-angular/ai-models, and @molecule/app-angular/push for those features.

Translations

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