@molecule/app-bonds-default-angular

Feature · bonds-default · App (browser) · v1.2.2 · Apache-2.0

Default app-side bond wirings for Angular: the framework-neutral defaults from @molecule/app-bonds-default plus the Angular router setup and bootstrapApp().

npm install @molecule/app-bonds-default-angular

npm · Source on GitHub

How it works

@molecule/app-bonds-default-angular is a ready-made bonds-default feature for the app (browser) side. It composes the core interfaces it needs, so it works with whichever providers your app has bonded.

// src/main.ts
import { provideRouter } from '@angular/router'
import {
  bootstrapApp,
  createDefaultAuthClientWithHttpSync,
  setupAllDefaultBonds,
} from '@molecule/app-bonds-default-angular'
import { provideMoleculeRouter } from '@molecule/app-routing-angular-router'
// Optional providers come from their own subpath — see @remarks.
import { setupAppCodeEditorMonaco } from '@molecule/app-bonds-default-angular/optional/code-editor-monaco.js'

import { App } from './app/app.js'
import { authConfig } from './config.js'
import { routes } from './app/routes.js'

const { authClient, setupAuthDefault } = createDefaultAuthClientWithHttpSync(authConfig)

bootstrapApp({
  App,
  authClient,
  // Async so optional async bonds are AWAITED before the first render.
  setupProviders: async () => {
    setupAllDefaultBonds()
    setupAuthDefault()
    await setupAppCodeEditorMonaco() // only if the app uses the code editor
  },
  providers: [provideRouter(routes), provideMoleculeRouter()],
})

Works with: @molecule/app-bonds-default, @molecule/app-routing, @molecule/app-routing-angular-router

Reference

@molecule/app-bonds-default-angular — default app-side bond wirings for the Angular fleet stack: the framework-neutral defaults re-exported from @molecule/app-bonds-default (auth/http factories, state, fonts, storage, styling, theme, ClassMap, icons, the optional provider subpaths) plus the Angular Router routing setup and bootstrapApp(). Switching framework means changing the package name in the imports — every export keeps its name.

  • bootstrapApp({ App, authClient, setupProviders, providers?, registerPWA? }) — the whole scaffolded src/main.ts: awaits setupProviders() BEFORE the first render, kicks off authClient.initialize() (best-effort), mounts the root component on #root, then registers the PWA. providers are Angular root-injector providers (provideRouter(routes) with provideMoleculeRouter() from @molecule/app-routing-angular-router, provideMolecule({ ... }), …).
  • setupAllDefaultBonds() — wires the NINE universal bonds in one call: state (the vanilla simpleProvider, so createStore() works from the first render), fonts-arimo, routing-angular-router, storage-localstorage, styling-tailwind (registers the tailwind-merge class merger), theme-css-variables (light + dark via getDefaultThemeProvider()), ui-tailwind ClassMap, icons-molecule, clipboard-web (the browser Clipboard API with a selection-and-copy fallback). Each also exists as an individual setupApp*() for apps that wire a la carte.
  • Optional provider wirings live behind subpaths, one module per pair: @molecule/app-bonds-default-angular/optional/<pair>.js — realtime-socketio, keyboard-shortcuts-hotkeys, command-palette-cmdk, client-search-minisearch, code-editor-monaco, virtual-scroll-tanstack, drag-drop-dndkit, charts-chartjs, maps-leaflet, video-hls. Import ONLY the ones the app installs.
  • Auth/http factories — createDefaultAuthClient(authConfig) returns { authClient, setupAuthDefault }; the ...WithHttpSync / ...WithFetchClient variants also keep the bonded http client's bearer token in sync with auth events. All three accept any JSON object profile (createDefaultAuthClient<SessionUser>(config) for an API whose user has no id) and fall back to UserProfile — with its id: string — when no type argument is given. The profile is never inferred from authConfig, so an untyped call keeps the default contract.

What this client already handles

  • getAccessToken() returns a stored token during restore; only 401/403 ends the session, while network/5xx failures retain it.
  • tokenKey/storagePrefix, authScheme, mapAuthResponse, currentUserEndpoint, and profileEndpoint/profileUpdateMethod adapt the API.
  • logout() settles local sign-out; refresh() uses a stored refresh token.

This factory adds no render gate: AuthProvider renders children immediately. The HTTP-sync variants gate requests during restore, not rendering.

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

// src/main.ts
import { provideRouter } from '@angular/router'
import {
  bootstrapApp,
  createDefaultAuthClientWithHttpSync,
  setupAllDefaultBonds,
} from '@molecule/app-bonds-default-angular'
import { provideMoleculeRouter } from '@molecule/app-routing-angular-router'
// Optional providers come from their own subpath — see @remarks.
import { setupAppCodeEditorMonaco } from '@molecule/app-bonds-default-angular/optional/code-editor-monaco.js'

import { App } from './app/app.js'
import { authConfig } from './config.js'
import { routes } from './app/routes.js'

const { authClient, setupAuthDefault } = createDefaultAuthClientWithHttpSync(authConfig)

bootstrapApp({
  App,
  authClient,
  // Async so optional async bonds are AWAITED before the first render.
  setupProviders: async () => {
    setupAllDefaultBonds()
    setupAuthDefault()
    await setupAppCodeEditorMonaco() // only if the app uses the code editor
  },
  providers: [provideRouter(routes), provideMoleculeRouter()],
})

Type

feature

Installation

npm install @molecule/app-bonds-default-angular @angular/common @angular/core @angular/platform-browser @angular/router @molecule/app-bonds-default @molecule/app-routing @molecule/app-routing-angular-router

API

Functions

bootstrapApp(opts)

Boot the Angular app: wire bonds, kick off auth initialization, mount the root component on #root, and (optionally) register the PWA service worker.

The Angular counterpart of the React package's bootstrapApp — the same contract, so switching framework means changing the package name in the import:

  • setupProviders() is AWAITED before the first render, so components may use bonded providers from their very first effect (several optional setups like setupAppRealtimeSocketio are async, and mounting past them races the bond registration).
  • authClient.initialize() is best-effort at boot — the app mounts logged-out and the user can sign in; a failure is logged, not thrown.
  • The application is created with createApplication({ providers }) — the same platform bootstrap bootstrapApplication runs internally — and the root component is mounted ON the #root host element (the same host the React, Vue, Solid and Svelte counterparts mount on). bootstrapApplication itself takes no host: it resolves the component's selector, so an app that prefers Angular's selector-host convention can call it directly instead.
  • registerPWA() runs after the mount.
function bootstrapApp(opts: {
  App: Type<unknown>
  authClient: { initialize: () => Promise<void> }
  setupProviders: () => void | Promise<void>
  /**
   * Angular root-injector providers — `provideRouter(routes)` with
   * `provideMoleculeRouter()`, `provideMolecule({ ... })`,
   * `provideZonelessChangeDetection()`, … Both the
   * `EnvironmentProviders` those functions return and plain `Provider` objects
   * are accepted, exactly as Angular's own `bootstrapApplication` does.
   */
  providers?: Array<Provider | EnvironmentProviders>
  registerPWA?: () => void
}): void
  • opts — The root component, the auth client, the bond wiring, optional Angular providers, and an optional PWA registration callback.

setupAppRoutingAngularRouter()

Wires @molecule/app-routing-angular-router's provider to @molecule/app-routing.

The bond's provider constant is the core's browser router: the Angular Router only exists inside a booted injector, so an import-time constant cannot be Angular-backed. This is what a scaffold wires so molecule packages always have A router (the same role the basic provider plays in the React package); for the Angular-backed router pass provideMoleculeRouter(...) next to Angular's own provideRouter(routes) in bootstrapApp's providers.

function setupAppRoutingAngularRouter(): void

setupAllDefaultBonds()

Wires all 9 universal app-side bonds in one call — state (the vanilla simpleProvider, so createStore() works), fonts, routing, storage, styling, theme, UI ClassMap, icons, clipboard (in that order). Auth + i18n stay per-app because they need app-specific config.

Replaces the individual setupX() calls in per-app bonds/index.ts.

function setupAllDefaultBonds(): void

createDefaultHttpClient(baseURL)

Builds the default fetch-based HTTP client + wires it into @molecule/app-http. Replaces the per-app bonds/http-default.ts shipped by ~52 fleet apps.

function createDefaultHttpClient(baseURL: string): {
  httpClient: HttpClient
  setupHttpDefault: () => void
}

createDefaultHttpClientWithAuthBearer(opts)

Variant of createDefaultHttpClient that adds a request interceptor injecting the JWT bearer token from the auth client AND (optionally) stripping a leading /api/ from request URLs.

Replaces ~20 per-app bonds/http-default.ts files that hand-roll this same wiring. Pass stripApiPrefix: true when the app uses baseURL: '/api' to handle pages that pass /api/-prefixed paths (would otherwise resolve to /api/api/... and 404). Pass authScheme when the API reads another scheme than Bearer: it is an option of THIS constructor (createDefaultHttpClientWithAuthBearer({ authScheme: 'Token', … }), or createFetchClient({ baseURL, authScheme: 'Token' }) directly), never a property of the client it returns. The client is built with the same scheme, so a token the client also holds — the one a default auth bond's token sync gives it — is sent with that scheme too, not as Bearer.

function createDefaultHttpClientWithAuthBearer(opts: {
  baseURL: string
  withCredentials?: boolean
  stripApiPrefix?: boolean
  getToken: () => string | null | undefined
  /**
   * The scheme of the `Authorization` header the token from `getToken()` is sent
   * with: `Bearer` (default), or what the API expects, e.g. `Token` for an API
   * that reads `Authorization: Token <jwt>`. Pass it to this constructor — the
   * same option `@molecule/app-http`'s client config calls `authScheme`, and not
   * a property of the client that comes back.
   */
  authScheme?: string
}): {
  httpClient: HttpClient
  setupHttpDefault: () => void
}

createDefaultAuthClient(authConfig)

Builds the default JWT auth client + wires it into @molecule/app-auth. Apps pass their own authConfig (which lives in src/config.ts).

TUser is the profile the app's pages read, and may be any JSON object type — including a profile with NO id ({ username, email, bio, image }), as in the factory it wraps. Never add a synthetic id to satisfy a type: nothing in the client reads it, and the fabricated value then travels into storage, getUser() and every page. Omit the type parameter and the default is UserProfile, whose id: string stays required — the profile is never inferred from authConfig (not even from an annotated config variable), so an untyped wrapper call keeps the default contract.

Type the config with the SAME type (const authConfig: AuthClientConfig<MyUser> = { … }) so its mapAuthResponse is checked against MyUser, and name that type at the call (createDefaultAuthClient<MyUser>(authConfig)): a mapper that omits a required custom field then fails at that call instead of shipping a signed-in page that reads undefined. An annotated config alone does not supply the type argument — that is a 1.8 caller shape this major changes (see AuthClientConfig's migration note in @molecule/app-auth).

TRegister is the app's own extra registration fields (for example { username: string }), passed on to @molecule/app-auth's factory so authClient.register({ username, email, password }) type-checks with no cast. See the module guidance for the lifecycle and API adaptations already included.

function createDefaultAuthClient<
  TUser extends AuthProfileConstraint<TUser> = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(
  authConfig: NoInfer<AuthClientConfigOptions<TUser>>,
): {
  authClient: AuthClient<TUser, TRegister>
  setupAuthDefault: () => void
}

createDefaultAuthClientWithHttpSync(authConfig)

Variant of createDefaultAuthClient that also keeps the bonded @molecule/app-http client's bearer token in sync with the auth client's session. Required by apps whose http client must carry the JWT on every request — without this wiring, authed endpoints return 401 after page reloads or token refresh.

The sync is a LIVE read: @molecule/app-http's setAuthTokenSource registers the auth client's token, and every client the app bonds, before or after this setup, reads it on each request — so the order of the setup*() calls in bonds/index.ts does not matter and never needs changing for auth. A session adopted with no auth event (useAuth().setSession(), an OAuth callback's setAccessToken(), the same profile under a new token) is therefore sent by the next request, not the previous account's bearer. A transport without setAuthTokenResolver is followed through a request interceptor (see setAuthTokenSource for which request first carries the change), and auth events still push the token to it.

A cookie session (no body token) resolves to null, so the request carries NO Authorization header — a kept bearer would answer as the PRIOR session. Requests also wait for the session restore, so a page that fetches viewer data on mount cannot race it (see registerAuthGate).

The profile type is createDefaultAuthClient's: a JSON object type of named fields (see AuthProfileShape), including an app profile with no id.

function createDefaultAuthClientWithHttpSync<
  TUser extends AuthProfileConstraint<TUser> = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(
  authConfig: NoInfer<AuthClientConfigOptions<TUser>>,
): {
  authClient: AuthClient<TUser, TRegister>
  setupAuthDefault: () => void
}

createDefaultAuthClientWithFetchClient(authConfig, fetchClientOptions)

Most aggressive variant — bonds a fetch-based HTTP client with the given baseURL (so molecule pkg useGet('/path') calls hit ${baseURL}/path instead of the SPA's catch-all route), AND keeps its bearer token in sync with the auth client's session, read on every request: a session adopted with no auth event (setSession(), setAccessToken()) is sent by the next request. The token uses the auth config's authScheme (default Bearer); a client bonded after this setup gets the same source and auth events.

The auth client restores a stored token AND user SYNCHRONOUSLY, so the first render is the signed-in UI — do not gate a protected page (or a provider of yours) on a current-user request. This bond registers whenRestored() as the HTTP gate, so requests still wait for the background restore/verification to settle; only useAuth().status === 'loading' means "no decision yet" (a page that waits on its own /me pays a round trip on every navigation).

Used by apps where molecule packages render pricing / billing / other authed JSON-fetching screens that need both behaviors.

Requests are also held until the session restore settles (see registerAuthGate), so a page that fetches viewer-dependent data on mount cannot race it and answer for an anonymous viewer.

The profile type is createDefaultAuthClient's: a JSON object type of named fields (see AuthProfileShape), including an app profile with no id.

function createDefaultAuthClientWithFetchClient<
  TUser extends AuthProfileConstraint<TUser> = UserProfile,
  TRegister extends RegisterExtraShape<TRegister> = Record<never, never>,
>(
  authConfig: NoInfer<AuthClientConfigOptions<TUser>>,
  fetchClientOptions: { baseURL: string; withCredentials?: boolean },
): {
  authClient: AuthClient<TUser, TRegister>
  setupAuthDefault: () => void
}

getDefaultThemeProvider()

Returns (and lazily constructs) the shared default CSS-variables theme provider.

function getDefaultThemeProvider(): ReturnType<typeof createCSSVariablesThemeProvider>

setupAppClipboardWeb()

Wires @molecule/app-clipboard-web to @molecule/app-clipboard: the browser's Clipboard API, falling back to a selection-and-copy where that API is missing or refuses (a plain-HTTP page, an iframe without the clipboard-write permission, a document that lost focus).

WITHOUT this, writeText() throws "No provider set" and copyTextWithFallback() only tries the legacy copy command, so a copy button built on them works in fewer places than a raw navigator.clipboard call.

function setupAppClipboardWeb(): void

setupAppFontsArimo()

Wires @molecule/app-fonts-arimo to @molecule/app-fonts.

function setupAppFontsArimo(): void

setupAppIconsMolecule()

Wires @molecule/app-icons-molecule to @molecule/app-icons.

function setupAppIconsMolecule(): void

setupAppStateSimple()

Wires the framework-agnostic simpleProvider from @molecule/app-state as the active state provider.

WITHOUT this, createStore() throws @molecule/app-state: No provider set. Call setProvider() first — nothing else in a scaffolded app wires the state bond, so the documented createStore() + useStore() pattern failed at the first render and every page came up blank while tsc passed.

function setupAppStateSimple(): void

setupAppStorageLocalstorage()

Wires @molecule/app-storage-localstorage to @molecule/app-storage.

function setupAppStorageLocalstorage(): void

setupAppStylingTailwind()

Wires @molecule/app-styling-tailwind: registers tailwind-merge as the class merger for @molecule/app-styling's cn(), so conflicting Tailwind utilities resolve (last wins). Tailwind itself is configured via env vars + the Vite plugin; this is the one runtime hook the framework-agnostic styling core needs so it carries no Tailwind dependency of its own.

function setupAppStylingTailwind(): void

setupAppThemeCssVariables()

Wires the default light + dark CSS-variables theme provider to @molecule/app-theme.

function setupAppThemeCssVariables(): void

setupAppUiTailwind()

Wires @molecule/app-ui-tailwind classMap to @molecule/app-ui.

function setupAppUiTailwind(): void

Injection Notes

Requirements

Peer dependencies:

  • @angular/common ^22.0.0
  • @angular/core ^22.0.0
  • @angular/platform-browser ^22.0.0
  • @angular/router ^22.0.0
  • @molecule/app-bonds-default ^1.2.1
  • @molecule/app-charts ^1.0.1 (optional)
  • @molecule/app-charts-chartjs ^1.0.1 (optional)
  • @molecule/app-client-search ^1.0.0 (optional)
  • @molecule/app-client-search-minisearch ^1.0.0 (optional)
  • @molecule/app-code-editor ^1.0.1 (optional)
  • @molecule/app-code-editor-monaco ^1.0.1 (optional)
  • @molecule/app-command-palette ^1.0.1 (optional)
  • @molecule/app-command-palette-cmdk ^1.0.1 (optional)
  • @molecule/app-drag-drop ^1.0.1 (optional)
  • @molecule/app-drag-drop-dndkit ^1.0.1 || ^2.0.0 (optional)
  • @molecule/app-keyboard-shortcuts ^1.0.1 (optional)
  • @molecule/app-keyboard-shortcuts-hotkeys ^1.0.1 (optional)
  • @molecule/app-maps ^1.0.1 (optional)
  • @molecule/app-maps-leaflet ^1.0.1 (optional)
  • @molecule/app-realtime ^1.0.1 (optional)
  • @molecule/app-realtime-socketio ^1.0.1 (optional)
  • @molecule/app-routing ^1.0.1
  • @molecule/app-routing-angular-router ^1.0.0
  • @molecule/app-video ^2.0.0 (optional)
  • @molecule/app-video-hls ^1.0.4 (optional)
  • @molecule/app-virtual-scroll ^1.0.1 (optional)
  • @molecule/app-virtual-scroll-tanstack ^1.0.1 (optional)

Runtime Dependencies

  • @angular/common

  • @angular/core

  • @angular/platform-browser

  • @angular/router

  • @molecule/app-bonds-default

  • @molecule/app-charts (optional)

  • @molecule/app-charts-chartjs (optional)

  • @molecule/app-client-search (optional)

  • @molecule/app-client-search-minisearch (optional)

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

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

  • @molecule/app-command-palette (optional)

  • @molecule/app-command-palette-cmdk (optional)

  • @molecule/app-drag-drop (optional)

  • @molecule/app-drag-drop-dndkit (optional)

  • @molecule/app-keyboard-shortcuts (optional)

  • @molecule/app-keyboard-shortcuts-hotkeys (optional)

  • @molecule/app-maps (optional)

  • @molecule/app-maps-leaflet (optional)

  • @molecule/app-realtime (optional)

  • @molecule/app-realtime-socketio (optional)

  • @molecule/app-routing

  • @molecule/app-routing-angular-router

  • @molecule/app-video (optional)

  • @molecule/app-video-hls (optional)

  • @molecule/app-virtual-scroll (optional)

  • @molecule/app-virtual-scroll-tanstack (optional)

  • Optional setups are NOT exported from the package root. Import each from its own subpath — @molecule/app-bonds-default-angular/optional/maps-leaflet.js, not from '@molecule/app-bonds-default-angular'. A bundler must RESOLVE every import() in a module it pulls into the graph, before tree-shaking can drop anything, so importing a subpath whose provider pair the app has not installed fails its build. Only import a subpath the app actually installs.

  • setupAllDefaultBonds() does NOT wire the optional bonds. Those ship as separate ASYNC setups — setupAppRealtimeSocketio, setupAppKeyboardShortcutsHotkeys, setupAppCommandPaletteCmdk, setupAppCodeEditorMonaco, setupAppVirtualScrollTanstack, setupAppDragDropDndkit, setupAppChartsChartjs, setupAppMapsLeaflet, setupAppVideoHls — and MUST be awaited inside setupProviders (make it async). bootstrapApp awaits setupProviders() before mounting so bonded providers exist by a component's first effect; a fire-and-forget async setup races the mount and intermittently loses.

  • Plain createDefaultAuthClient does NOT attach the JWT to the bonded http client. If molecule packages call authed /api endpoints, use createDefaultAuthClientWithHttpSync (or ...WithFetchClient to also bond a fetch client with a baseURL) — otherwise those endpoints return 401 after a page reload or token refresh.

  • getDefaultThemeProvider() constructs lazily because the CSS-variables theme provider touches localStorage at construction — importing this package is SSR/test-safe, but only CALL it in a DOM environment. Apps with custom themes build their own provider and skip setupAppThemeCssVariables().