@betterportal/theme-runtime
v11.0.13
Published
Backend-assembled BetterPortal browser runtime for theme packages
Readme
@betterportal/theme-runtime
Shared backend and browser-shell runtime for BetterPortal Node shell packages.
The package assembles one JavaScript asset on the backend in this order:
- HTMX core from the installed
htmx.orgpackage. - The shell's typed presentation adapter.
- The BetterPortal
bp-shellruntime. - The bundled HTMX SSE extension.
The browser never discovers or loads extensions dynamically. Required assets are resolved by the backend and missing assets fail bundle creation.
Shell adapters are authored as TSX with jsx-htmx's js() helper:
/** @jsxImportSource jsx-htmx */
import { js } from "jsx-htmx";
import {
buildBetterPortalShellRuntimeAsset,
type BetterPortalShellAdapter
} from "@betterportal/theme-runtime";
const adapterSource = js(() => {
window.BetterPortalShellAdapter = {
setLoading(loading, outlet) {
outlet?.toggleAttribute("data-bp-loading", loading);
}
} satisfies BetterPortalShellAdapter;
});
const asset = await buildBetterPortalShellRuntimeAsset({
adapterSource
});js() returns safe RawText. Pass it directly to the runtime builder or place it directly inside a <script> element. Do not call .toString() and do not wrap it with raw().
The shared runtime owns service/app URL rewriting, managed BP headers, header-aware preload, HTMX lifecycle handling, downloads, history, authentication failures, SSE, bp-route states, and route chrome state. It never discovers service schemas in the browser.
Managed BP headers are sent only to registered app service origins over HTTPS. Local development may use HTTP on localhost, 127.0.0.1, or [::1]; other HTTP service URLs must migrate to HTTPS. Shells publish origins for enabled route, slot, fragment, auth, and shell bindings. Legacy origin-based header ownership and scopes remain supported.
Preload is speculative: disabled controls and the configured auth origin are excluded, HTTP redirects are not followed, and response directives/UI changes wait for explicit activation. Rewritten links retain the tenant URL in href and use the service URL in hx-get. Initial content loaders are one-shot; empty loader URLs are inert. On a main-content 401, the shell owns login navigation and bounds header refresh to five seconds; a late refresh cannot override a newer navigation.
Plain internal <a href="/route"> links and forms using native GET or POST are automatically upgraded to HTMX and routed through the owning service. For default #bp-main navigation, the configured app UI route is authoritative for href and history; the runtime never pushes an unconfigured service path. A bare <form> posts to its current service view. Use bp-no-override (or data-bp-no-override) on an element or ancestor to keep native browser behavior; data-bp-no-route remains supported for shell-owned elements.
Runtime-managed HTMX requests automatically declare Accept: text/html; mode=page|fragment; SSE connects are always marked HX-Request-Type: partial, retain the SSE media type, and receive the same scoped BP auth/context headers as other self-service requests. Explicit non-HTML Accept headers are preserved.
It also reads <meta name="betterportal:session-id" content="<uuidv7>"> and adds bp.session_id to W3C baggage on every runtime-managed request. The ID lasts for one document load, is exposed as document.documentElement.dataset.bpSessionId, and is correlation-only. Shells should render the framework-provided request session; the runtime generates a fallback when the meta tag is missing.
For initial shell rendering, spread betterPortalChromeAttributes(route.chrome) onto the element marked data-bp-shell-root. After route responses, the runtime parses every bp-chrome-* content-type parameter, updates the corresponding data-bp-chrome-* attributes, removes stale attributes, and calls the optional typed applyChrome(chrome, previousChrome, root) adapter hook. Themes should normally use CSS against the data attributes and reserve applyChrome for presentation that cannot be expressed in CSS. Themes must not register duplicate HTMX chrome listeners or infer authentication state from chrome values.
Shell adapters are presentation-only. They may implement loading/error UI, component initialization and disposal, overlay cleanup, scrolling, and optional chrome presentation. A shell package does not add htmx.org; this runtime owns and bundles it. This runtime also imports jsx-htmx, but a shell that imports jsx-htmx directly for TSX must declare it as its own dependency. Do not bundle the stock preload extension: BetterPortal's preload implementation is part of bp-shell so it can attach scoped BP headers and reuse the prefetched response. The fixed HTMX extension allowlist is bp-shell, sse.
The runtime tests include a headless Chromium preload regression. From the workspace root, run npx playwright install chromium once before npm test (Linux CI uses --with-deps).
Plain service anchors are upgraded to main-panel HTMX only when their complete enabled page mount resolves. Preload markers alone do not indicate routing success. Encoded service template placeholders from older shell metadata are recognized when declared in the UI mount. Custom themes must rebuild/redeploy their bundled shared runtime to receive fixes; see 11.0.0 routing notes.
Ordinary service-rendered destinations resolve against the owning service before any UI alias. An identically named UI mount belonging to another service cannot take over the link. Shell-owned navigation is explicitly marked. A configured UI path is a compatibility fallback only when no owning service destination matches.
The shell handles HX-Redirect and HX-Location before HTMX follows them. Absolute registered service URLs are mapped to their app URLs; HX-Redirect retains full-page navigation and HX-Location targets the main outlet. Services must redirect to a different effective page: redirecting /welcome to / when / mounts /welcome is a loop. The runtime reports self redirects and short redirect cycles instead of repeating requests. A changed authorization header permits a same-page reload after sign-in, and POST-to-GET redirects remain supported.
When / has no GET-capable page mount, root navigation uses the same fallback as initial shell loading: a visible non-auth page from the menu, then an enabled concrete non-auth page mount. API routes, pages without GET support, and parameterized routes are excluded. Configure an explicit root mount or a post-login destination for a stable landing page. Custom themes must rebuild their shared runtime bundle to receive this behavior.
HTTP and network errors from partial requests stay with the original request target. An explicit data-bp-mutation-error outlet receives fragment validation HTML or a text message; otherwise the runtime adds an inline alert inside the affected row/component and keeps its controls and entered values. A successful retry clears the alert. Error response navigation/retargeting headers, status retargeting, and out-of-band swaps cannot replace the page. Full-page requests retain the shell's existing error/auth handling. Inherited targets follow HTMX 4's hx-target:inherited semantics (or ordinary inherited attributes when implicitInheritance is enabled).
The root fallback applies only to GET navigation; unmatched root mutations keep their owning service endpoint. Fallback query defaults are preserved, incoming root parameters override matching defaults (including repeated values), and an incoming fragment overrides the fallback fragment. Query defaults used only by the configured service request are retained on that request and stay out of browser history.
Successful fragment responses may retarget the main outlet. The runtime tracks the page generation when each request starts, so a delayed retarget or redirect cannot replace a newer page. HTTP partial failures continue to use the original target.
Responses discarded as stale do not emit HX-Trigger events. Fragment loading indicators belong to the latest request for that target, so an older success, failure, or cancellation cannot clear a newer request's indicator.
