Skip to content

aurora ​

@c9up/aurora: components written as tagged templates over signals, rendered to HTML on the server and hydrated in the browser, with no build step. Guide: Introduction.

Installation ​

bash
pnpm add @c9up/aurora
ream configure @c9up/aurora

ream configure @c9up/aurora registers the provider and the @c9up/aurora/middleware router middleware, and writes config/aurora.ts. Optional peer dependencies: @c9up/comet for @c9up/aurora/rpc, @c9up/photon for page visits (visits: true).

Entry points ​

aurora has browser entries and server entries. The browser entries import no Node module; the server entries do. Import a server entry only from server code.

ImportRuns inContents
@c9up/aurorabrowser, serverEverything a component and a page script use: html, component, signals, lists, forms, the HTTP client, render, hydrate, browser helpers, routes, motion, live components.
@c9up/aurora/coreany hostThe host-free part of @c9up/aurora: templates, components, signals, lists, forms, commands, motion. No DOM, no Node module.
@c9up/aurora/rendererany hostThe pieces a renderer for another host (a native one) builds on. Application code does not need it.
@c9up/aurora/hydratebrowserhydrate and resetHydrateWarnings.
@c9up/aurora/ssrany hostrenderToString and renderRetaining.
@c9up/aurora/relaybrowserThe realtime client of @c9up/relay.
@c9up/aurora/rpcbrowserA JSON-RPC client on aurora's HTTP client.
@c9up/aurora/serverNodeAuroraManager, Pages, renderPage, serveAssets, defineConfig.
@c9up/aurora/middlewareNodeThe middleware that puts ctx.aurora on the request.
@c9up/aurora/providerNodeAuroraProvider (default export).
@c9up/aurora/services/mainNodesetAurora, getAurora, clearAurora.
@c9up/aurora/configureNodeconfigure(codemods), run by ream configure @c9up/aurora.

Exports ​

@c9up/aurora ​

Templates and components ​

ExportKindDescription
htmlfunctionhtml(strings: TemplateStringsArray, ...values: unknown[]): TemplateResult: a template. A ${} in a position that cannot be bound safely throws (see the E_AURORA_SLOT_* codes).
isTemplateResultfunctionisTemplateResult(value: unknown): value is TemplateResult.
componentfunctioncomponent<P = Record<string, never>>(setup: (props: P) => TemplateResult): (props?: P) => TemplateResult. setup runs once.
onMountfunctiononMount(fn: EffectCallback): void: runs after the component is in the DOM; may return a cleanup. Only inside setup.
onUnmountfunctiononUnmount(fn: () => void): void. Only inside setup.
createContextfunctioncreateContext<T>(name: string, defaultValue?: T): Context<T>.
providefunctionprovide<T>(context: Context<T>, value: T): T: for the components below, during setup.
injectfunctioninject<T>(context: Context<T>): T: the nearest provided value, or the default; neither throws E_AURORA_MISSING_CONTEXT.
renderfunctionrender(result: TemplateResult, container: Element | DocumentFragment): Disposer: mounts in the browser.
renderToStringfunctionrenderToString(result: TemplateResult): string: the HTML, with the markers hydration reads.
hydratefunctionhydrate(container: Element, factory: () => TemplateResult, options?: HydrateOptions): Disposer: attaches to server-rendered HTML instead of rebuilding it.
onPageLeavefunctiononPageLeave(end: () => void): () => void: runs end when a page visit (visits: true) leaves this page; returns what takes it back.
cnfunctioncn(...inputs: ClassValue[]): string: clsx then twMerge.
clsxfunctionclsx(...inputs: ClassValue[]): string: joins truthy class names.
twMergefunctiontwMerge(classList: string): string: keeps the last of conflicting Tailwind classes.

Signals ​

ExportKindDescription
signalfunctionsignal<T>(initial: T, options?: { equals?: (a: T, b: T) => boolean }): Signal<T>.
memofunctionmemo<T>(fn: () => T, options?: { equals?: (a: T, b: T) => boolean }): ReadSignal<T>: a derived value, recomputed when what it read changes.
effectfunctioneffect(fn: EffectCallback): () => void: reruns when what it read changes; returns its disposer.
onCleanupfunctiononCleanup(fn: () => void): void: runs before the current effect reruns or is disposed.
batchfunctionbatch<T>(fn: () => T): T: one update for several writes.
untrackfunctionuntrack<T>(fn: () => T): T: reads without subscribing.
isSignalfunctionisSignal<T = unknown>(value: unknown): value is Signal<T>.
Signalinterfaces() reads, s(next) writes, s(prev => next) updates.
ReadSignalinterfaces() reads.

Effects that keep re-triggering each other in one update throw E_AURORA_REACTIVE_CYCLE.

Lists ​

ExportKindDescription
eachfunctioneach<T>(items: EachItems<T>, key: (item: T, index: number) => unknown, render: (item: ReadSignal<T>, index: ReadSignal<number>) => unknown, options?: EachOptions): Each: a keyed list; a row moves with its key. Two rows with one key throw E_AURORA_DUPLICATE_KEY.
isEachfunctionisEach(value: unknown): value is Each.
EachItemstypereadonly T[] | Signal<readonly T[]> | ReadSignal<readonly T[]> | (() => readonly T[]).
EachOptionsinterface{ lazy?: boolean | LazyOptions }: render only the rows in view.
LazyOptionsinterface{ estimate?: number; overscan?: number; from?: 'start' | 'end' }.
EachinterfaceWhat each returns.

Forms and commands ​

ExportKindDescription
formfunctionform<T>(options: FormOptions<T>): Form<T>: values, field errors, submission state.
commandfunctioncommand<TArgs extends unknown[], TData>(task: (...args: TArgs) => Promise<TData>): Command<TArgs, TData>: an async action with data, error and loading signals.
FormOptionsinterface{ initial: T; submit: (values: T) => Promise<unknown>; validate?: FormValidate<T> }.
FormValidatetype((values: T) => FieldErrors<T>) | FormSchema<T>.
FormSchemainterfaceA validator object with validate?(values) or validateResult?(values) returning { valid; errors? }.
FieldErrorstypePartial<Record<keyof T, string>>.
Form, FormField, CommandinterfaceSee below.
Form<T> memberSignatureDescription
values / errors / valid / submitting / submitErrorreadonly values: ReadSignal<T>State signals.
fieldfield<K extends keyof T>(key: K): FormField<T[K]>{ value, error, touched, set(value), markTouched() }.
setset<K extends keyof T>(key: K, value: T[K]): void
validatevalidate(): boolean
handleSubmithandleSubmit(event?: { preventDefault(): void }): Promise<void>Validates, then calls submit.
setErrors / resetsetErrors(errors: FieldErrors<T>): void
onSuccess / onFailonSuccess(handler: (data: unknown) => void): this
Command memberSignatureDescription
data / error / loadingreadonly data: ReadSignal<TData | null>
runrun(...args: TArgs): Promise<void>
resetreset(): void
onSuccess / onFail / onSettledonSuccess(handler: (data: TData) => void): this

HTTP ​

ExportKindDescription
HttpClientclassA fetch client with a base URL, default headers, a bearer token, timeouts and the CSRF header.
httpconstA default HttpClient.
isHttpErrorfunctionisHttpError(value: unknown): value is errors.E_AURORA_HTTP_REQUEST_FAILED: the error of a non-2xx answer, with status, response and data.
isAbortErrorfunctionisAbortError(value: unknown): boolean.
HttpClientOptionsinterface{ baseURL?; headers?; token?: string | null | (() => string | null | undefined); credentials?; allowCrossOriginAuth?: boolean; timeout?: number; xsrf?: boolean; xsrfCookieName?: string; xsrfHeaderName?: string }.
HttpRequestOptionsinterface{ query?; headers?; token?; xsrf?; signal?; timeout?; credentials?; allowCrossOriginAuth?; parse?: (raw: unknown) => T }.
HttpResulttype{ ok: true; data: T; error: null } | { ok: false; data: null; error: errors.E_AURORA_HTTP_REQUEST_FAILED }.
HttpClient memberSignatureDescription
constructornew HttpClient(options?: HttpClientOptions)
get / deleteget<T>(url: string, options?: HttpRequestOptions<T>): Promise<T>Rejects with errors.E_AURORA_HTTP_REQUEST_FAILED on a non-2xx.
post / put / patchpost<T>(url: string, body?: unknown, options?: HttpRequestOptions<T>): Promise<T>
rawraw(method: string, url: string, body?: unknown, options?: HttpRequestOptions)
attemptattempt<T>(request: Promise<T>): Promise<HttpResult<T>>A result instead of a rejection.
extendextend(options: HttpClientOptions): HttpClientA client with these options over its own.
setHeader / setHeaders / removeHeader / getHeaderssetHeader(name: string, value: string): this

The CSRF header (X-XSRF-TOKEN from the XSRF-TOKEN cookie) is sent on same-origin requests; the bearer token is not sent to another origin unless allowCrossOriginAuth.

Browser helpers ​

ExportKindDescription
navigate / redirect / replace / reload / back / forwardfunctionLocation and history. navigate(url: string): void.
hashfunctionhash(): Signal<string>.
queryParamfunctionqueryParam(key: string): Signal<string | null>.
mediaQueryfunctionmediaQuery(query: string): Signal<boolean>.
prefersDark / online / visibilityfunction(): Signal<boolean>.
windowSizefunctionwindowSize(): Signal<WindowSize>.
WebStorageclasslocalStorage or sessionStorage under a prefix: get, set, getJSON, setJSON, has, remove, getOrSet, keys, clear.
storage / sessionconstWebStorage over localStorage / sessionStorage.
persistedSignalfunctionpersistedSignal<T>(key: string, initial: T, options?: PersistedSignalOptions): Signal<T>: a signal mirrored to web storage, and across tabs for localStorage (crossTab, true by default).
cookieconstget(name), set(name, value, options?), remove(name, options?); reads the request's cookies during SSR.
cookieSignalfunctioncookieSignal(name: string, initial: string, options?: CookieOptions): Signal<string>.
cookieStatefunctioncookieState<T>(name: string, initial: T, codec: CookieCodec<T>, options?: CookieOptions): Signal<T>.
booleanCookieconstCookieCodec<boolean>.
jsonCookiefunctionjsonCookie<T>(fallback: T): CookieCodec<T>.
setCookieStore / getCookieStorefunctionThe cookie values SSR reads.
clipboardconstcopy(text: string): Promise<boolean>, read(): Promise<string | null>.
sharefunctionshare(data: ShareData): Promise<boolean>: the Web Share API.
CookieOptionsinterface{ path?; maxAge?; expires?; domain?; sameSite?: 'strict' | 'lax' | 'none'; secure? }.
CookieCodecinterface{ parse(raw: string): T; serialize(value: T): string }.
WebStorageOptionsinterface{ prefix?: string; area?: StorageArea }.
PersistedSignalOptionsinterfaceWebStorageOptions plus crossTab?: boolean.
StorageAreatype'local' | 'session'.
WindowSizeinterface{ width: number; height: number }.
ShareDatainterface{ title?; text?; url? }.

Routes ​

ExportKindDescription
urlForfunctionurlFor(name: string, params?: Record<string, string | number>, query?: Record<string, string | number>): string: a named route's URL, on the server and in the browser.
setRouteManifest / getRouteManifestfunctionThe name-to-pattern map urlFor reads; renderPage ships it to the browser.
auroraRoutefunctionauroraRoute(config: AuroraRouteConfig): (ctx: AuroraHttpContext) => Promise<void>: a route handler that renders a component and sends the whole document.
AuroraRouteConfiginterface{ render: (ctx) => TemplateResult | Promise<TemplateResult>; entry?: string; shell?: (body: string, entry: string) => string }.
AuroraHttpContext, AuroraResponseinterfaceThe request context auroraRoute needs.

Hydration state and ids ​

ExportKindDescription
hydrationStatefunctionhydrationState(): HydrationState: 'pending' | 'hydrating' | 'hydrated'.
whenHydratedfunctionwhenHydrated(): Promise<void>.
hydrationErrorsfunctionhydrationErrors(): readonly unknown[].
uidfunctionuid(prefix?: string): string: an id that is the same on the server and in the browser.
withIdScopefunctionwithIdScope<T>(scope: string, work: () => T): T.
resetIdsfunctionresetIds(scope?: string): void.
byIdfunctionbyId(id: string): HTMLElement | null.
HydrateOptionsinterface{ idScope?: string }.
HydrationState, HydrationDetailtype

Motion ​

ExportKindDescription
MotionValueclassnew MotionValue(initial: number): set(value), stop(), timing(to: number, options?: TimingOptions) (300 ms by default), after(duration: number, to: number), spring(to: number, options?: SpringOptions) (stiffness 180, damping 12, mass 1 by default).
MotionNodeclassA value derived by interpolate(input, output).
MotionModelclassThe in-process motion driver.
motionDriver / setMotionDriverfunctionThe driver motion values run on; a native renderer installs its own.
readMotionStylefunctionreadMotionStyle(value: unknown): MotionStyle.
MotionStyleinterface{ opacity?; translateX?; translateY?; scale?; visible? }, the values motion=${…} drives. Anything else throws E_AURORA_INVALID_MOTION.
TimingOptionsinterface{ duration?: number; loop?: boolean; yoyo?: boolean }.
SpringOptionsinterface{ stiffness?: number; damping?: number; mass?: number }.
MotionDriver, MotionTracktype

Live components ​

ExportKindDescription
createLiveRegistryfunctioncreateLiveRegistry(options?: LiveRegistryOptions): LiveRegistry: server sessions of live components.
createLiveRouterfunctioncreateLiveRouter(registry: LiveRegistry, relay: RelayBroadcaster): LiveRouter: mounts sessions and routes client events, patches broadcast through relay.
wireLiveEventsfunctionwireLiveEvents(router: LiveHttpRouter, live: LiveRouter, identify: IdentifyLiveCaller<LiveHttpContext>, options?: WireLiveEventsOptions): void: the POST route that receives client events (DEFAULT_LIVE_EVENT_PATH, /__live/event).
authorizeLiveChannelfunctionauthorizeLiveChannel<C>(live: LiveRouter, identify: IdentifyLiveCaller<C>): (ctx: C, params: { id: string }) => Promise<boolean>: a relay authorizer that lets only a session's owner subscribe.
mountLiveSessionfunctionmountLiveSession(factory: () => LiveComponentDefinition, idScope?: string): LiveSession.
liveStorefunctionliveStore(factory: () => LiveComponentDefinition, relay: RelayBroadcaster, channel: string): LiveStore: one shared session broadcast to everyone on a channel.
connectPatchesfunctionconnectPatches(session: LiveSession, relay: RelayBroadcaster, channel: string): () => void.
liveClientfunctionliveClient(opts: LiveClientOptions): () => void: the browser side; applies patches and posts events.
buildLiveTransportfunctionbuildLiveTransport(relayClient: RelaySubscribeClient, http: LiveHttpPoster, options?: { path?: string }): LiveClientTransport. Its keepAlive(id) posts { id, keepAlive: true } to the event route.
DEFAULT_LIVE_KEEP_ALIVE_MSconst120000: how often liveClient keeps its session alive (LiveClientOptions.keepAliveMs).
DEFAULT_LIVE_EVENT_PATHconst'/__live/event'.
LiveComponentDefinitioninterface{ view: TemplateResult; handlers?: Record<string, (payload?: unknown) => void> }.
LiveSessioninterfacerenderToString(), dispatch(event, payload?), drainPatches(), onPatch(listener), dispose().
SlotPatchinterface{ slot: number; value: string }.
LiveRegistryOptionsinterface{ claimTimeoutMs?; idleTimeoutMs?; maxPerOwner?: number; maxSessions?: number }. maxPerOwner 32, maxSessions 10 000, idleTimeoutMs ten minutes.
LiveRegistryinterfacedefine(name, factory), has, mount(name, ownerId), claim, get, ownerOf, dispose, disposeOwner, disposeAll, size.
LiveRouterinterfacemount(name, ownerId): LiveMount, event(id, event, payload, callerId): LiveEventOutcome, keepAlive(id, callerId): LiveEventOutcome, authorizeChannel, ownerOf, disconnect, channelFor.
LiveMountinterface{ id: string; channel: string; html: string }.
LiveEventOutcometype'handled' | 'unknown-session' | 'forbidden' | 'unknown-event'.
LiveStore, LiveSessionHandle, LiveClientOptions, LiveClientTransport, LiveHttpPoster, LiveHttpContext, LiveHttpRouter, LiveEventBody, LiveKeepAliveBody, WireLiveEventsOptions, RelayBroadcaster, RelaySubscribeClient, IdentifyLiveCallertype

Diagnostics, errors and types ​

ExportKindDescription
countRerendersfunctioncountRerenders(options?: RerenderOptions): RerenderCounter: counts effect, memo, slot, list, attribute, property and setup reruns; can highlight or log them.
errorsnamespaceThe package's errors, one class per code, see Errors
TemplateResultinterfaceWhat html returns.
Disposertype() => void.
Contextinterface{ key: symbol; name: string; hasDefault: boolean; defaultValue: T | undefined }.
ClassValuetypeWhat cn and clsx take.
RerenderCounter, RerenderEvent, RerenderKind, RerenderOptionstype

@c9up/aurora/core ​

The host-free subset of @c9up/aurora: html, isTemplateResult, component, onMount, onUnmount, createContext, provide, inject, signal, memo, effect, onCleanup, batch, untrack, isSignal, each, isEach, form, command, uid, withIdScope, cn, clsx, twMerge, the motion exports, countRerenders, errors and their types. A component that imports only from here runs on the server, in the browser and on a phone.

@c9up/aurora/renderer ​

ExportKindDescription
TemplateScannerclassReads a template's static parts and says where each slot sits.
assertBindablefunctionassertBindable(scanner: TemplateScanner): BindablePosition: throws the E_AURORA_SLOT_* code for a refused position.
assertBindablePropertyfunctionassertBindableProperty(element: string, property: string): void.
readComponentLifecyclefunctionreadComponentLifecycle(result: TemplateResult): ComponentLifecycle | undefined: the mount hooks and cleanups a component() attached.
bindTemplateContextfunctionbindTemplateContext(result: TemplateResult, value: unknown): unknown: runs a slot's function under its template's context.
captureContextfunctioncaptureContext(): <T>(fn: () => T) => T: the providers in reach now, for work done later.
setOwnerfunctionsetOwner(owner: Array<() => void> | undefined): Array<() => void> | undefined: where effects created now are disposed.
readEach / readEachItemsfunctionreadEach(value: unknown): EachList | undefined; readEachItems<T>(items: EachItems<T>): readonly T[].
LazyLayoutclassRow heights and spacers of a lazy list.
firstWindow / sameWindowfunctionThe first rows of a lazy list; window equality.
guardUrlAttribute / guardUrlPropertyfunctionThe URL guard applied to URL-bearing attributes and properties.
isTemplateResultfunction
ComponentLifecycle, EachList, LazyList, LazyView, LazyWindow, BindablePosition, EffectCallback, TemplateResulttype

@c9up/aurora/hydrate and @c9up/aurora/ssr ​

ExportEntryDescription
hydrate/hydrateSame as in @c9up/aurora.
HydrateOptions/hydrate{ idScope?: string }.
resetHydrateWarnings/hydrateresetHydrateWarnings(): void: lets a mismatch warning print again.
renderToString/ssrSame as in @c9up/aurora.
renderRetaining/ssrrenderRetaining(result: TemplateResult, owned: Set<() => void>): string: renders and hands the disposers to the caller.

@c9up/aurora/relay ​

ExportKindDescription
relayfunctionrelay(): RelayClient: the page's single connection to relay, opened on first call.
configureRelayfunctionconfigureRelay(options: RelayOptions): void.
RelayClientinterfacesubscribe<E>(channel: string, handler: (event: E) => void): () => void, on(status, callback): () => void, close(): void.
RelayStatustype'connecting' | 'connected' | 'disconnected' | 'reconnecting'.
RelayOptionsinterfaceSee below.
RelayStream, RelayStreamEvent, RelayFetchtypeWhat stream and fetch replace.
RelayOptionsTypeDefaultDescription
sseUrlstring'/__relay/events'
subscribeUrlstring'/__relay/subscribe'
unsubscribeUrlstring'/__relay/unsubscribe'
bearerstring''Token sent with subscribe requests.
maxReconnectAttemptsnumber5
onReconnectAttempt / onReconnectFailedfunctionnone
stream(url: string) => RelayStreamnew EventSource(url)
fetchRelayFetchfetch

@c9up/aurora/rpc ​

ExportKindDescription
createRpcClientfunctioncreateRpcClient(options?: RpcClientOptions): RpcClient: a @c9up/comet client sending through an HttpClient.
RpcClientOptionsinterface{ url?: string; http?: HttpClient; headers?: Record<string, string>; xsrf?: boolean; xsrfCookieName?: string; xsrfHeaderName?: string }. url defaults to /rpc, xsrf to true.
RpcError, isRpcErrorre-exportFrom @c9up/comet.
RpcClient, RpcCall, RpcCallOptions, RpcResulttypeFrom @c9up/comet.

@c9up/aurora/server ​

ExportKindDescription
defineConfigfunctiondefineConfig(config: AuroraManagerConfig): AuroraManagerConfig.
AuroraManagerclassPages, assets and rendering for the application; ctx.aurora renders through it.
PagesclassResolves a page name to its module under pages.root.
renderPagefunctionrenderPage<P>(ctx: RenderHttpContext, pages: Pages, name: string, props: P, options?: RenderPageOptions): Promise<void>: renders a page and sends the document.
serveAssetsfunctionserveAssets(options: ServeAssetsOptions): (ctx: AssetsHttpContext) => Promise<void>: a static file handler confined to root.
packageAssetDirfunctionpackageAssetDir(specifier: string): string: the dist/ of an installed package.
auroraContextfunctionSame as in @c9up/aurora/middleware.
errorsnamespaceThe package's errors, one class per code, see Errors
pageImportErrorfunctionBuilds the error of a page that failed to import.
AuroraManagerConfiginterfaceSee Configuration.
PagesConfiginterface{ root: string; urlPrefix?: string; extension?: string }.
PageFactorytype(props: P) => TemplateResult | Promise<TemplateResult>: a page module's default export.
RenderPageOptionsinterfaceSee below.
SharedPropstypeRecord<string, unknown>.
SharedPropsResolvertype(ctx: RenderHttpContext) => SharedProps | Promise<SharedProps>.
ClientRoutesFiltertype{ only?: readonly string[]; except?: readonly string[] } | ((name: string, pattern: string) => boolean).
RenderHttpContext, RenderResponse, AssetsHttpContext, AssetsRequest, AssetsResponse, ServeAssetsOptions, AuroraRequestRenderertype
AuroraManager memberSignatureDescription
constructornew AuroraManager(config: AuroraManagerConfig)
renderrender(ctx: RenderHttpContext, name: string, props: unknown, options?: RenderPageOptions): Promise<void>renderPage with the config's defaults.
pagesreadonly pages: Pages
assetsPrefix / auroraAssetPath / pageAssetPathreadonly assetsPrefix: string/__assets, /__assets/aurora, /__assets/pages by default.
browserPackagesreadonly browserPackages: readonly BrowserPackage[]Packages served to the browser.
importmapreadonly importmap: Record<string, string>
auroraAssetsHandler / pageAssetsHandlerauroraAssetsHandler(): (ctx: AssetsHttpContext) => Promise<void>The asset handlers the provider mounts.
Pages memberSignatureDescription
constructornew Pages(config: PagesConfig)urlPrefix defaults to /__assets/pages, extension to .js.
registerregister<P>(name: string, factory: PageFactory<P>): voidA page without a file, for bundled apps and tests.
resolveresolve(name: string): Promise<PageFactory>Imports the page module on every call.
urlForurlFor(name: string): stringThe page module's URL for the browser.
RenderPageOptionsTypeDescription
titlestring<title>.
langstring<html lang>.
noncestringCSP nonce for the inline scripts.
headExtrastringMarkup added to <head>.
jsonLdobject | readonly object[]Structured data.
rootId / rootTag / rootClassstringThe element the page renders into. A tag that is not a plain element name throws E_AURORA_ILLEGAL_ROOT_TAG.
importmapRecord<string, string>Merged over the config's.
sharedSharedProps | SharedPropsResolverMerged over the config's.
assetsVersionstring
routes / clientRoutesRecord<string, string> / ClientRoutesFilterNamed routes sent to the browser for urlFor.
cookiesstring[]Cookies the server reads from the request so cookieSignal renders the same state as the browser. Never list a session, signed or httpOnly cookie.

@c9up/aurora/middleware, @c9up/aurora/services/main, @c9up/aurora/provider ​

ExportEntryDescription
AuroraContextMiddleware/middleware (default)Middleware class: puts ctx.aurora on the request.
auroraContext/middlewareauroraContext(ctx, next: () => Promise<void>): Promise<void>: the same as a function.
AuroraRequestRenderer/middlewarectx.aurora: render(name: string, props?: unknown, options?: RenderPageOptions): Promise<void>.
setAurora / getAurora / clearAurora/services/mainThe AuroraManager the module singleton holds. Reading it before it is set throws E_AURORA_NOT_BOOTED.
AuroraProvider/provider (default)Binds the manager and mounts the asset middleware.
AuroraAppContext/providerThe host the provider needs: container, config.
configure/configureconfigure(codemods): Promise<void>.

Configuration ​

config/aurora.ts exports defineConfig({ … }) from @c9up/aurora/server. The configure stub writes pages.root: 'resources/pages' and root.tag: 'div'.

OptionTypeDefaultDescription
pages.rootstring(required)The pages directory; relative to the application root. ctx.aurora.render('dashboard/show') loads dashboard/show.js there.
pages.urlPrefixstring<assetsPrefix>/pagesURL the browser loads pages from.
pages.extensionstring'.js'
sharedSharedProps | SharedPropsResolvernoneProps merged into every page.
root.tag / root.classstringThe page's root element.
assetsVersionstringnoneVersion sent in the page; with visits, a deploy reloads stale clients.
clientRoutesClientRoutesFilternoneWhich named routes every page carries to the browser.
assetsPrefixstring'/__assets'Where the asset routes mount.
importmapRecord<string, string>aurora's ownImportmap entries merged over aurora's.
browserPackagesstring[][]More packages served to the browser ('@c9up/atom'); @c9up/comet and @c9up/chronos are served when installed.
visitsbooleanfalsePage visits without a document reload, through photon's protocol. Needs @c9up/photon 0.1.25 or later.
auroraDistRoot / cometDistRoot / chronosDistRoot / photonDistRootstringthe installed package's dist/Serve another build.

Container bindings ​

TokenResolves to
AuroraManager (class), 'aurora'The AuroraManager built from config/aurora.ts.

'aurora' is declared on ContainerBindings, and ctx.aurora on the HTTP context, by @c9up/aurora/server. In start() the provider mounts the asset routes as server middleware: /__assets/aurora/*, /__assets/pages/*, and one route per browser package.

Errors ​

CodeRaised when
E_AURORA_ILLEGAL_PAGE_NAMEA page name holds characters a page name may not.
E_AURORA_PAGE_OUTSIDE_ROOTThe resolved page path lands outside pages.root.
E_AURORA_PAGE_NOT_FOUNDNo file for this page name.
E_AURORA_PAGE_IMPORT_FAILEDThe page is on disk and its module graph refused to load.
E_AURORA_PAGE_INVALID_EXPORTThe page module does not default-export a factory.
E_AURORA_ILLEGAL_ROOT_TAGrenderPage was given a root tag that is not a plain element name.
E_AURORA_OUTSIDE_COMPONENTonMount / onUnmount was called outside a component() setup.
E_AURORA_MISSING_CONTEXTinject found no provider, and the context has no default.
E_AURORA_NOT_BOOTEDThe manager singleton was read before the provider or setAurora set it.
E_AURORA_UNKNOWN_ROUTEurlFor was given a name absent from the route manifest.
E_AURORA_MISSING_ROUTE_PARAMSurlFor was not given every required param.
E_AURORA_UNKNOWN_LIVE_COMPONENTA live component was mounted before registry.define() named it.
E_AURORA_LIVE_SESSION_LIMITThe registry holds maxSessions already, all of them in use. Status 503.
E_AURORA_RELAY_REQUEST_FAILEDA relay request came back with a non-2xx status.
E_AURORA_UNSAFE_URLA navigation URL failed the same-origin or scheme check.
E_AURORA_SLOT_IN_TAG_NAMEA ${} where a tag name goes.
E_AURORA_SLOT_IN_ATTRIBUTE_NAMEA ${} where an attribute name goes.
E_AURORA_SLOT_IN_RAW_TEXTA ${} inside <script>, <style>, <textarea>, <title>…
E_AURORA_SLOT_IN_COMMENTA ${} inside a comment, a <!…> / <?…> or a CDATA section.
E_AURORA_SLOT_IN_EVENT_ATTRIBUTEA ${} in an on* attribute.
E_AURORA_SLOT_IN_SRCDOCA ${} in srcdoc.
E_AURORA_SLOT_IN_BASE_URLA ${} in <base href>.
E_AURORA_SLOT_IN_SCRIPT_SOURCEA ${} in the URL a <script> loads.
E_AURORA_SLOT_IN_HTML_PROPERTYA .prop binding names a property that parses its value as HTML.
E_AURORA_TEMPLATE_IN_ATTRIBUTEA nested html template in an attribute value or .value.
E_AURORA_FILE_INPUT_VALUE.value was given a non-empty string on an <input type="file">.
E_AURORA_DUPLICATE_KEYTwo rows of an each() list share a key.
E_AURORA_INVALID_LAZYeach(…, { lazy }) was given an invalid estimate or overscan.
E_AURORA_VISITS_NEED_PHOTONvisits is on and @c9up/photon is missing or too old.
E_AURORA_VISIT_PROPSWith visits on, a page's props were not an object.
E_AURORA_INVALID_MOTIONmotion=${…} was not an object of motion values, or named a property motion cannot drive.
E_AURORA_REACTIVE_CYCLEEffects kept re-running each other in one update.
E_AURORA_VISIT_NO_PAGE_DATAWith visits on, the page carries no usable page data script (script[data-aurora-page]) to boot from.
E_AURORA_VISIT_CROSS_ORIGIN_MODULEWith visits on, a page module's URL is not on the page's own origin.
E_AURORA_VISIT_ASYNC_FIRST_PAGEWith visits on, the first page's factory is async: a hydrated page renders synchronously.
E_AURORA_INVALID_LIVE_LIMITA live registry limit (maxSessions, maxPerOwner, claimTimeoutMs, idleTimeoutMs) is not a positive number.
E_AURORA_BROWSER_ENTRY_OUTSIDE_DISTA browser package declares its entry outside the dist/ aurora serves for it.
E_AURORA_BROWSER_ENTRY_AT_ROOTA browser package has its entry at the package root: serving it would publish the whole package.
E_AURORA_BROWSER_PACKAGE_CLASHTwo browser packages would mount on the same asset path.
E_AURORA_HTTP_REQUEST_FAILEDAn HttpClient request came back with a non-2xx status. Carries response and the parsed data; status is the response's.
E_AURORA_INTERNALAn invariant inside aurora broke: a bug in aurora.

Migration ​

  • AuroraError is gone: test error.code, or error instanceof errors.E_AURORA_* with import { errors } from '@c9up/aurora' (also exported by @c9up/aurora/core and @c9up/aurora/server).
  • AuroraRangeError is gone: E_AURORA_INVALID_LIVE_LIMIT is no longer a RangeError; catch it by its code.
  • HttpError becomes errors.E_AURORA_HTTP_REQUEST_FAILED, with the same status, response and data; isHttpError still narrows to it.
  • The AuroraErrorCode type is gone: error.code is a string.
  • Templates are read the way the browser reads them. A slot in onclick ="${v}", srcdoc ="${v}", <script src ="${v}"> or <base href ="${v}"> (whitespace before the =), in x/onclick="${v}", in <img ='${v}'>, or inside <script/x> or <style/x> now throws the error the ordinary spelling throws. href = "${url}" (whitespace on both sides) no longer throws E_AURORA_SLOT_IN_ATTRIBUTE_NAME: it is an href, guarded like href="${url}". Write the ordinary spelling.
  • renderToString writes an unquoted value that holds a slot between double quotes: title=${x} comes out as title="…", and title="" when x is empty. A test that compared the markup byte for byte must expect the quotes.
  • The page data script is now <script type="application/json" data-aurora-page>, written first in the <body>, before the root; it no longer has id="aurora-page-data". Code that read it with getElementById('aurora-page-data') must use document.querySelector('script[data-aurora-page][type="application/json"]').
  • With visits on, a page module is imported only from the page's own origin: a modules pattern on another origin (or data:, or //host/…) throws E_AURORA_VISIT_CROSS_ORIGIN_MODULE. Serve page modules from your own origin.
  • A live registry ends a claimed session after ten minutes without an event or a keep-alive (idleTimeoutMs, was off). liveClient sends the keep-alive through buildLiveTransport; a custom transport needs a keepAlive(id) posting { id, keepAlive: true }, or set idleTimeoutMs yourself.
  • A full live registry now evicts the oldest unclaimed session, or the least recently used one silent for half of idleTimeoutMs, before mount throws E_AURORA_LIVE_SESSION_LIMIT. An event the component does not handle no longer claims the session.
  • @click ="${h}", @click= "${h}" and x="1"@click="${h}" are listeners on the server too: renderToString no longer calls h and writes nothing for them.

See also ​