alepha
Version:
Alepha is a convention-driven TypeScript framework for building robust, end-to-end type-safe applications, from serverless APIs to full-stack React apps.
904 lines (903 loc) • 30.9 kB
TypeScript
import * as _alepha_core14 from "alepha";
import { Alepha, Async, Descriptor, Hooks, KIND, Service, State, Static, TObject, TSchema } from "alepha";
import { RequestConfigSchema, ServerHandler, ServerProvider, ServerRequest, ServerRouterProvider, ServerTimingProvider } from "alepha/server";
import { ServerRouteCache } from "alepha/server/cache";
import { ClientScope, HttpVirtualClient, LinkProvider, VirtualAction } from "alepha/server/links";
import * as _alepha_logger1 from "alepha/logger";
import * as react0 from "react";
import React, { AnchorHTMLAttributes, CSSProperties, ErrorInfo, FC, PropsWithChildren, ReactNode } from "react";
import * as react_jsx_runtime1 from "react/jsx-runtime";
import { ServerStaticProvider } from "alepha/server/static";
import { DateTimeProvider } from "alepha/datetime";
import { Route, RouterProvider } from "alepha/router";
//#region src/components/ClientOnly.d.ts
interface ClientOnlyProps {
fallback?: ReactNode;
disabled?: boolean;
}
/**
* A small utility component that renders its children only on the client side.
*
* Optionally, you can provide a fallback React node that will be rendered.
*
* You should use this component when
* - you have code that relies on browser-specific APIs
* - you want to avoid server-side rendering for a specific part of your application
* - you want to prevent pre-rendering of a component
*/
declare const ClientOnly: (props: PropsWithChildren<ClientOnlyProps>) => ReactNode;
//#endregion
//#region src/errors/Redirection.d.ts
/**
* Used for Redirection during the page loading.
*
* Depends on the context, it can be thrown or just returned.
*/
declare class Redirection extends Error {
readonly redirect: string;
constructor(redirect: string);
}
//#endregion
//#region src/providers/ReactPageProvider.d.ts
declare const envSchema$2: _alepha_core14.TObject<{
REACT_STRICT_MODE: _alepha_core14.TBoolean;
}>;
declare module "alepha" {
interface Env extends Partial<Static<typeof envSchema$2>> {}
}
declare class ReactPageProvider {
protected readonly log: _alepha_logger1.Logger;
protected readonly env: {
REACT_STRICT_MODE: boolean;
};
protected readonly alepha: Alepha;
protected readonly pages: PageRoute[];
getPages(): PageRoute[];
page(name: string): PageRoute;
pathname(name: string, options?: {
params?: Record<string, string>;
query?: Record<string, string>;
}): string;
url(name: string, options?: {
params?: Record<string, string>;
host?: string;
}): URL;
root(state: ReactRouterState): ReactNode;
protected convertStringObjectToObject: (schema?: TSchema, value?: any) => any;
/**
* Create a new RouterState based on a given route and request.
* This method resolves the layers for the route, applying any query and params schemas defined in the route.
* It also handles errors and redirects.
*/
createLayers(route: PageRoute, state: ReactRouterState, previous?: PreviousLayerData[]): Promise<CreateLayersResult>;
protected createRedirectionLayer(redirect: string): CreateLayersResult;
protected getErrorHandler(route: PageRoute): ErrorHandler | undefined;
protected createElement(page: PageRoute, props: Record<string, any>): Promise<ReactNode>;
renderError(error: Error): ReactNode;
renderEmptyView(): ReactNode;
href(page: {
options: {
name?: string;
};
}, params?: Record<string, any>): string;
compile(path: string, params?: Record<string, string>): string;
protected renderView(index: number, path: string, view: ReactNode | undefined, page: PageRoute): ReactNode;
protected readonly configure: _alepha_core14.HookDescriptor<"configure">;
protected map(pages: Array<PageDescriptor>, target: PageDescriptor): PageRouteEntry;
add(entry: PageRouteEntry): void;
protected createMatch(page: PageRoute): string;
protected _next: number;
protected nextId(): string;
}
declare const isPageRoute: (it: any) => it is PageRoute;
interface PageRouteEntry extends Omit<PageDescriptorOptions, "children" | "parent"> {
children?: PageRouteEntry[];
}
interface PageRoute extends PageRouteEntry {
type: "page";
name: string;
parent?: PageRoute;
match: string;
}
interface Layer {
config?: {
query?: Record<string, any>;
params?: Record<string, any>;
context?: Record<string, any>;
};
name: string;
props?: Record<string, any>;
error?: Error;
part?: string;
element: ReactNode;
index: number;
path: string;
route?: PageRoute;
cache?: boolean;
}
type PreviousLayerData = Omit<Layer, "element" | "index" | "path">;
interface AnchorProps {
href: string;
onClick: (ev?: any) => any;
}
interface ReactRouterState {
/**
* Stack of layers for the current page.
*/
layers: Array<Layer>;
/**
* URL of the current page.
*/
url: URL;
/**
* Error handler for the current page.
*/
onError: ErrorHandler;
/**
* Params extracted from the URL for the current page.
*/
params: Record<string, any>;
/**
* Query parameters extracted from the URL for the current page.
*/
query: Record<string, string>;
/**
* Optional meta information associated with the current page.
*/
meta: Record<string, any>;
}
interface RouterStackItem {
route: PageRoute;
config?: Record<string, any>;
props?: Record<string, any>;
error?: Error;
cache?: boolean;
}
interface TransitionOptions {
previous?: PreviousLayerData[];
}
interface CreateLayersResult {
redirect?: string;
state?: ReactRouterState;
}
//#endregion
//#region src/descriptors/$page.d.ts
/**
* Main descriptor for defining a React route in the application.
*
* The $page descriptor is the core building block for creating type-safe, SSR-enabled React routes.
* It provides a declarative way to define pages with powerful features:
*
* **Routing & Navigation**
* - URL pattern matching with parameters (e.g., `/users/:id`)
* - Nested routing with parent-child relationships
* - Type-safe URL parameter and query string validation
*
* **Data Loading**
* - Server-side data fetching with the `resolve` function
* - Automatic serialization and hydration for SSR
* - Access to request context, URL params, and parent data
*
* **Component Loading**
* - Direct component rendering or lazy loading for code splitting
* - Client-only rendering when browser APIs are needed
* - Automatic fallback handling during hydration
*
* **Performance Optimization**
* - Static generation for pre-rendered pages at build time
* - Server-side caching with configurable TTL and providers
* - Code splitting through lazy component loading
*
* **Error Handling**
* - Custom error handlers with support for redirects
* - Hierarchical error handling (child → parent)
* - HTTP status code handling (404, 401, etc.)
*
* **Page Animations**
* - CSS-based enter/exit animations
* - Dynamic animations based on page state
* - Custom timing and easing functions
*
* **Lifecycle Management**
* - Server response hooks for headers and status codes
* - Page leave handlers for cleanup (browser only)
* - Permission-based access control
*
* @example Simple page with data fetching
* ```typescript
* const userProfile = $page({
* path: "/users/:id",
* schema: {
* params: t.object({ id: t.int() }),
* query: t.object({ tab: t.optional(t.string()) })
* },
* resolve: async ({ params }) => {
* const user = await userApi.getUser(params.id);
* return { user };
* },
* lazy: () => import("./UserProfile.tsx")
* });
* ```
*
* @example Nested routing with error handling
* ```typescript
* const projectSection = $page({
* path: "/projects/:id",
* children: () => [projectBoard, projectSettings],
* resolve: async ({ params }) => {
* const project = await projectApi.get(params.id);
* return { project };
* },
* errorHandler: (error) => {
* if (HttpError.is(error, 404)) {
* return <ProjectNotFound />;
* }
* }
* });
* ```
*
* @example Static generation with caching
* ```typescript
* const blogPost = $page({
* path: "/blog/:slug",
* static: {
* entries: posts.map(p => ({ params: { slug: p.slug } }))
* },
* resolve: async ({ params }) => {
* const post = await loadPost(params.slug);
* return { post };
* }
* });
* ```
*/
declare const $page: {
<TConfig extends PageConfigSchema = PageConfigSchema, TProps extends object = any, TPropsParent extends object = TPropsParentDefault>(options: PageDescriptorOptions<TConfig, TProps, TPropsParent>): PageDescriptor<TConfig, TProps, TPropsParent>;
[KIND]: typeof PageDescriptor;
};
interface PageDescriptorOptions<TConfig extends PageConfigSchema = PageConfigSchema, TProps extends object = TPropsDefault, TPropsParent extends object = TPropsParentDefault> {
/**
* Name your page.
*
* @default Descriptor key
*/
name?: string;
/**
* Optional description of the page.
*/
description?: string;
/**
* Add a pathname to the page.
*
* Pathname can contain parameters, like `/post/:slug`.
*
* @default ""
*/
path?: string;
/**
* Add an input schema to define:
* - `params`: parameters from the pathname.
* - `query`: query parameters from the URL.
*/
schema?: TConfig;
/**
* Load data before rendering the page.
*
* This function receives
* - the request context and
* - the parent props (if page has a parent)
*
* In SSR, the returned data will be serialized and sent to the client, then reused during the client-side hydration.
*
* Resolve can be stopped by throwing an error, which will be handled by the `errorHandler` function.
* It's common to throw a `NotFoundError` to display a 404 page.
*
* RedirectError can be thrown to redirect the user to another page.
*/
resolve?: (context: PageResolve<TConfig, TPropsParent>) => Async<TProps>;
/**
* The component to render when the page is loaded.
*
* If `lazy` is defined, this will be ignored.
* Prefer using `lazy` to improve the initial loading time.
*/
component?: FC<TProps & TPropsParent>;
/**
* Lazy load the component when the page is loaded.
*
* It's recommended to use this for components to improve the initial loading time
* and enable code-splitting.
*/
lazy?: () => Promise<{
default: FC<TProps & TPropsParent>;
}>;
/**
* Set some children pages and make the page a parent page.
*
* /!\ Parent page can't be rendered directly. /!\
*
* If you still want to render at this pathname, add a child page with an empty path.
*/
children?: Array<PageDescriptor> | (() => Array<PageDescriptor>);
parent?: PageDescriptor<PageConfigSchema, TPropsParent>;
can?: () => boolean;
/**
* Catch any error from the `resolve` function or during `rendering`.
*
* Expected to return one of the following:
* - a ReactNode to render an error page
* - a Redirection to redirect the user
* - undefined to let the error propagate
*
* If not defined, the error will be thrown and handled by the server or client error handler.
* If a leaf $page does not define an error handler, the error can be caught by parent pages.
*
* @example Catch a 404 from API and render a custom not found component:
* ```ts
* resolve: async ({ params, query }) => {
* api.fetch("/api/resource", { params, query });
* },
* errorHandler: (error, context) => {
* if (HttpError.is(error, 404)) {
* return <ResourceNotFound />;
* }
* }
* ```
*
* @example Catch an 401 error and redirect the user to the login page:
* ```ts
* resolve: async ({ params, query }) => {
* // but the user is not authenticated
* api.fetch("/api/resource", { params, query });
* },
* errorHandler: (error, context) => {
* if (HttpError.is(error, 401)) {
* // throwing a Redirection is also valid!
* return new Redirection("/login");
* }
* }
* ```
*/
errorHandler?: ErrorHandler;
/**
* If true, the page will be considered as a static page, immutable and cacheable.
* Replace boolean by an object to define static entries. (e.g. list of params/query)
*
* For now, it only works with `@alepha/vite` which can pre-render the page at build time.
*
* It will act as timeless cached page server-side. You can use `cache` to configure the cache behavior.
*/
static?: boolean | {
entries?: Array<Partial<PageRequestConfig<TConfig>>>;
};
cache?: ServerRouteCache;
/**
* If true, force the page to be rendered only on the client-side.
* It uses the `<ClientOnly/>` component to render the page.
*/
client?: boolean | ClientOnlyProps;
/**
* Called before the server response is sent to the client.
*/
onServerResponse?: (request: ServerRequest) => any;
/**
* Called when user leaves the page. (browser only)
*/
onLeave?: () => void;
/**
* @experimental
*
* Add a css animation when the page is loaded or unloaded.
* It uses CSS animations, so you need to define the keyframes in your CSS.
*
* @example Simple animation name
* ```ts
* animation: "fadeIn"
* ```
*
* CSS example:
* ```css
* @keyframes fadeIn {
* from { opacity: 0; }
* to { opacity: 1; }
* }
* ```
*
* @example Detailed animation
* ```ts
* animation: {
* enter: { name: "fadeIn", duration: 300 },
* exit: { name: "fadeOut", duration: 200, timing: "ease-in-out" },
* }
* ```
*
* @example Only exit animation
* ```ts
* animation: {
* exit: "fadeOut"
* }
* ```
*
* @example With custom timing function
* ```ts
* animation: {
* enter: { name: "fadeIn", duration: 300, timing: "cubic-bezier(0.4, 0, 0.2, 1)" },
* exit: { name: "fadeOut", duration: 200, timing: "ease-in-out" },
* }
* ```
*/
animation?: PageAnimation;
}
type ErrorHandler = (error: Error, state: ReactRouterState) => ReactNode | Redirection | undefined;
declare class PageDescriptor<TConfig extends PageConfigSchema = PageConfigSchema, TProps extends object = TPropsDefault, TPropsParent extends object = TPropsParentDefault> extends Descriptor<PageDescriptorOptions<TConfig, TProps, TPropsParent>> {
protected onInit(): void;
get name(): string;
/**
* For testing or build purposes, this will render the page (with or without the HTML layout) and return the HTML and context.
* Only valid for server-side rendering, it will throw an error if called on the client-side.
*/
render(options?: PageDescriptorRenderOptions): Promise<PageDescriptorRenderResult>;
fetch(options?: PageDescriptorRenderOptions): Promise<{
html: string;
response: Response;
}>;
match(url: string): boolean;
pathname(config: any): string;
}
interface PageConfigSchema {
query?: TSchema;
params?: TSchema;
}
type TPropsDefault = any;
type TPropsParentDefault = {};
interface PageDescriptorRenderOptions {
params?: Record<string, string>;
query?: Record<string, string>;
/**
* If true, the HTML layout will be included in the response.
* If false, only the page content will be returned.
*
* @default true
*/
html?: boolean;
hydration?: boolean;
}
interface PageDescriptorRenderResult {
html: string;
state: ReactRouterState;
redirect?: string;
}
interface PageRequestConfig<TConfig extends PageConfigSchema = PageConfigSchema> {
params: TConfig["params"] extends TSchema ? Static<TConfig["params"]> : Record<string, string>;
query: TConfig["query"] extends TSchema ? Static<TConfig["query"]> : Record<string, string>;
}
type PageResolve<TConfig extends PageConfigSchema = PageConfigSchema, TPropsParent extends object = TPropsParentDefault> = PageRequestConfig<TConfig> & TPropsParent & Omit<ReactRouterState, "layers" | "onError">;
type PageAnimation = PageAnimationObject | ((state: ReactRouterState) => PageAnimationObject | undefined);
type PageAnimationObject = CssAnimationName | {
enter?: CssAnimation | CssAnimationName;
exit?: CssAnimation | CssAnimationName;
};
type CssAnimationName = string;
type CssAnimation = {
name: string;
duration?: number;
timing?: string;
};
//#endregion
//#region src/providers/ReactBrowserRouterProvider.d.ts
interface BrowserRoute extends Route {
page: PageRoute;
}
declare class ReactBrowserRouterProvider extends RouterProvider<BrowserRoute> {
protected readonly log: _alepha_logger1.Logger;
protected readonly alepha: Alepha;
protected readonly pageApi: ReactPageProvider;
add(entry: PageRouteEntry): void;
protected readonly configure: _alepha_core14.HookDescriptor<"configure">;
transition(url: URL, previous?: PreviousLayerData[], meta?: {}): Promise<string | void>;
root(state: ReactRouterState): ReactNode;
}
//#endregion
//#region src/providers/ReactBrowserProvider.d.ts
declare const envSchema$1: _alepha_core14.TObject<{
REACT_ROOT_ID: _alepha_core14.TString;
}>;
declare module "alepha" {
interface Env extends Partial<Static<typeof envSchema$1>> {}
}
interface ReactBrowserRendererOptions {
scrollRestoration?: "top" | "manual";
}
declare class ReactBrowserProvider {
protected readonly env: {
REACT_ROOT_ID: string;
};
protected readonly log: _alepha_logger1.Logger;
protected readonly client: LinkProvider;
protected readonly alepha: Alepha;
protected readonly router: ReactBrowserRouterProvider;
protected readonly dateTimeProvider: DateTimeProvider;
options: ReactBrowserRendererOptions;
protected getRootElement(): HTMLElement;
transitioning?: {
to: string;
from?: string;
};
get state(): ReactRouterState;
/**
* Accessor for Document DOM API.
*/
get document(): Document;
/**
* Accessor for History DOM API.
*/
get history(): History;
/**
* Accessor for Location DOM API.
*/
get location(): Location;
get base(): string;
get url(): string;
pushState(path: string, replace?: boolean): void;
invalidate(props?: Record<string, any>): Promise<void>;
go(url: string, options?: RouterGoOptions): Promise<void>;
protected render(options?: RouterRenderOptions): Promise<void>;
/**
* Get embedded layers from the server.
*/
protected getHydrationState(): ReactHydrationState | undefined;
protected readonly onTransitionEnd: _alepha_core14.HookDescriptor<"react:transition:end">;
readonly ready: _alepha_core14.HookDescriptor<"ready">;
}
interface RouterGoOptions {
replace?: boolean;
match?: TransitionOptions;
params?: Record<string, string>;
query?: Record<string, string>;
meta?: Record<string, any>;
/**
* Recreate the whole page, ignoring the current state.
*/
force?: boolean;
}
type ReactHydrationState = {
layers?: Array<PreviousLayerData>;
} & {
[key: string]: any;
};
interface RouterRenderOptions {
url?: string;
previous?: PreviousLayerData[];
meta?: Record<string, any>;
}
//#endregion
//#region src/components/ErrorBoundary.d.ts
/**
* Props for the ErrorBoundary component.
*/
interface ErrorBoundaryProps {
/**
* Fallback React node to render when an error is caught.
* If not provided, a default error message will be shown.
*/
fallback: (error: Error) => ReactNode;
/**
* Optional callback that receives the error and error info.
* Use this to log errors to a monitoring service.
*/
onError?: (error: Error, info: ErrorInfo) => void;
}
/**
* State of the ErrorBoundary component.
*/
interface ErrorBoundaryState {
error?: Error;
}
/**
* A reusable error boundary for catching rendering errors
* in any part of the React component tree.
*/
declare class ErrorBoundary extends React.Component<PropsWithChildren<ErrorBoundaryProps>, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps);
/**
* Update state so the next render shows the fallback UI.
*/
static getDerivedStateFromError(error: Error): ErrorBoundaryState;
/**
* Lifecycle method called when an error is caught.
* You can log the error or perform side effects here.
*/
componentDidCatch(error: Error, info: ErrorInfo): void;
render(): ReactNode;
}
//#endregion
//#region src/components/ErrorViewer.d.ts
interface ErrorViewerProps {
error: Error;
alepha: Alepha;
}
declare const ErrorViewer: ({
error,
alepha
}: ErrorViewerProps) => react_jsx_runtime1.JSX.Element;
//#endregion
//#region src/components/Link.d.ts
interface LinkProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
href: string;
}
declare const Link: (props: LinkProps) => react_jsx_runtime1.JSX.Element;
//#endregion
//#region src/components/NestedView.d.ts
interface NestedViewProps {
children?: ReactNode;
errorBoundary?: false | ((error: Error) => ReactNode);
}
declare const _default: react0.MemoExoticComponent<(props: NestedViewProps) => react_jsx_runtime1.JSX.Element>;
//#endregion
//#region src/components/NotFound.d.ts
declare function NotFoundPage(props: {
style?: CSSProperties;
}): react_jsx_runtime1.JSX.Element;
//#endregion
//#region src/contexts/AlephaContext.d.ts
declare const AlephaContext: react0.Context<Alepha | undefined>;
//#endregion
//#region src/contexts/RouterLayerContext.d.ts
interface RouterLayerContextValue {
index: number;
path: string;
}
declare const RouterLayerContext: react0.Context<RouterLayerContextValue | undefined>;
//#endregion
//#region src/hooks/useActive.d.ts
interface UseActiveOptions {
href: string;
startWith?: boolean;
}
declare const useActive: (args: string | UseActiveOptions) => UseActiveHook;
interface UseActiveHook {
isActive: boolean;
anchorProps: AnchorProps;
isPending: boolean;
}
//#endregion
//#region src/hooks/useAlepha.d.ts
/**
* Main Alepha hook.
*
* It provides access to the Alepha instance within a React component.
*
* With Alepha, you can access the core functionalities of the framework:
*
* - alepha.state() for state management
* - alepha.inject() for dependency injection
* - alepha.events.emit() for event handling
* etc...
*/
declare const useAlepha: () => Alepha;
//#endregion
//#region src/hooks/useClient.d.ts
/**
* Hook to get a virtual client for the specified scope.
*
* It's the React-hook version of `$client()`, from `AlephaServerLinks` module.
*/
declare const useClient: <T extends object>(scope?: ClientScope) => HttpVirtualClient<T>;
//#endregion
//#region src/hooks/useInject.d.ts
/**
* Hook to inject a service instance.
* It's a wrapper of `useAlepha().inject(service)` with a memoization.
*/
declare const useInject: <T extends object>(service: Service<T>) => T;
//#endregion
//#region src/hooks/useQueryParams.d.ts
/**
* Not well tested. Use with caution.
*/
declare const useQueryParams: <T extends TObject>(schema: T, options?: UseQueryParamsHookOptions) => [Partial<Static<T>>, (data: Static<T>) => void];
interface UseQueryParamsHookOptions {
format?: "base64" | "querystring";
key?: string;
push?: boolean;
}
//#endregion
//#region src/services/ReactRouter.d.ts
declare class ReactRouter<T extends object> {
protected readonly alepha: Alepha;
protected readonly pageApi: ReactPageProvider;
get state(): ReactRouterState;
get pages(): PageRoute[];
get browser(): ReactBrowserProvider | undefined;
path(name: keyof VirtualRouter<T>, config?: {
params?: Record<string, any>;
query?: Record<string, any>;
}): string;
getURL(): URL;
get location(): Location;
get current(): ReactRouterState;
get pathname(): string;
get query(): Record<string, string>;
back(): Promise<void>;
forward(): Promise<void>;
invalidate(props?: Record<string, any>): Promise<void>;
go(path: string, options?: RouterGoOptions): Promise<void>;
go(path: keyof VirtualRouter<T>, options?: RouterGoOptions): Promise<void>;
anchor(path: string, options?: RouterGoOptions): AnchorProps;
anchor(path: keyof VirtualRouter<T>, options?: RouterGoOptions): AnchorProps;
base(path: string): string;
/**
* Set query params.
*
* @param record
* @param options
*/
setQueryParams(record: Record<string, any> | ((queryParams: Record<string, any>) => Record<string, any>), options?: {
/**
* If true, this will add a new entry to the history stack.
*/
push?: boolean;
}): void;
}
type VirtualRouter<T> = { [K in keyof T as T[K] extends PageDescriptor ? K : never]: T[K] };
//#endregion
//#region src/hooks/useRouter.d.ts
/**
* Use this hook to access the React Router instance.
*
* You can add a type parameter to specify the type of your application.
* This will allow you to use the router in a typesafe way.
*
* @example
* class App {
* home = $page();
* }
*
* const router = useRouter<App>();
* router.go("home"); // typesafe
*/
declare const useRouter: <T extends object = any>() => ReactRouter<T>;
//#endregion
//#region src/hooks/useRouterEvents.d.ts
type Hook<T extends keyof Hooks> = ((ev: Hooks[T]) => void) | {
priority?: "first" | "last";
callback: (ev: Hooks[T]) => void;
};
/**
* Subscribe to various router events.
*/
declare const useRouterEvents: (opts?: {
onBegin?: Hook<"react:transition:begin">;
onError?: Hook<"react:transition:error">;
onEnd?: Hook<"react:transition:end">;
onSuccess?: Hook<"react:transition:success">;
}, deps?: any[]) => void;
//#endregion
//#region src/hooks/useRouterState.d.ts
declare const useRouterState: () => ReactRouterState;
//#endregion
//#region src/hooks/useSchema.d.ts
declare const useSchema: <TConfig extends RequestConfigSchema>(action: VirtualAction<TConfig>) => UseSchemaReturn<TConfig>;
type UseSchemaReturn<TConfig extends RequestConfigSchema> = TConfig & {
loading: boolean;
};
/**
* Get an action schema during server-side rendering (SSR) or client-side rendering (CSR).
*/
declare const ssrSchemaLoading: (alepha: Alepha, name: string) => RequestConfigSchema | {
loading: boolean;
};
//#endregion
//#region src/hooks/useStore.d.ts
/**
* Hook to access and mutate the Alepha state.
*/
declare const useStore: <Key extends keyof State>(key: Key, defaultValue?: State[Key]) => [State[Key], (value: State[Key]) => void];
//#endregion
//#region src/providers/ReactServerProvider.d.ts
declare const envSchema: _alepha_core14.TObject<{
REACT_SERVER_DIST: _alepha_core14.TString;
REACT_SERVER_PREFIX: _alepha_core14.TString;
REACT_SSR_ENABLED: _alepha_core14.TOptional<_alepha_core14.TBoolean>;
REACT_ROOT_ID: _alepha_core14.TString;
REACT_SERVER_TEMPLATE: _alepha_core14.TOptional<_alepha_core14.TString>;
}>;
declare module "alepha" {
interface Env extends Partial<Static<typeof envSchema>> {}
interface State {
"react.server.ssr"?: boolean;
}
}
declare class ReactServerProvider {
protected readonly log: _alepha_logger1.Logger;
protected readonly alepha: Alepha;
protected readonly pageApi: ReactPageProvider;
protected readonly serverProvider: ServerProvider;
protected readonly serverStaticProvider: ServerStaticProvider;
protected readonly serverRouterProvider: ServerRouterProvider;
protected readonly serverTimingProvider: ServerTimingProvider;
protected readonly env: {
REACT_SSR_ENABLED?: boolean | undefined;
REACT_SERVER_TEMPLATE?: string | undefined;
REACT_SERVER_DIST: string;
REACT_SERVER_PREFIX: string;
REACT_ROOT_ID: string;
};
protected readonly ROOT_DIV_REGEX: RegExp;
protected preprocessedTemplate: PreprocessedTemplate | null;
readonly onConfigure: _alepha_core14.HookDescriptor<"configure">;
get template(): string;
protected registerPages(templateLoader: TemplateLoader): Promise<void>;
protected getPublicDirectory(): string;
protected configureStaticServer(root: string): Promise<void>;
protected configureVite(ssrEnabled: boolean): Promise<void>;
/**
* For testing purposes, creates a render function that can be used.
*/
protected createRenderFunction(name: string, withIndex?: boolean): (options?: PageDescriptorRenderOptions) => Promise<PageDescriptorRenderResult>;
protected createHandler(route: PageRoute, templateLoader: TemplateLoader): ServerHandler;
renderToHtml(template: string, state: ReactRouterState, hydration?: boolean): string | Redirection;
protected preprocessTemplate(template: string): PreprocessedTemplate;
protected fillTemplate(response: {
html: string;
}, app: string, script: string): void;
}
type TemplateLoader = () => Promise<string | undefined>;
interface PreprocessedTemplate {
beforeApp: string;
afterApp: string;
beforeScript: string;
afterScript: string;
}
//#endregion
//#region src/index.d.ts
declare module "alepha" {
interface State {
"react.router.state"?: ReactRouterState;
}
interface Hooks {
"react:server:render:begin": {
request?: ServerRequest;
state: ReactRouterState;
};
"react:server:render:end": {
request?: ServerRequest;
state: ReactRouterState;
html: string;
};
"react:browser:render": {
root: HTMLDivElement;
element: ReactNode;
state: ReactRouterState;
hydration?: ReactHydrationState;
};
"react:transition:begin": {
previous: ReactRouterState;
state: ReactRouterState;
animation?: PageAnimation;
};
"react:transition:success": {
state: ReactRouterState;
};
"react:transition:error": {
state: ReactRouterState;
error: Error;
};
"react:transition:end": {
state: ReactRouterState;
};
}
}
/**
* Provides full-stack React development with declarative routing, server-side rendering, and client-side hydration.
*
* The React module enables building modern React applications using the `$page` descriptor on class properties.
* It delivers seamless server-side rendering, automatic code splitting, and client-side navigation with full
* type safety and schema validation for route parameters and data.
*
* @see {@link $page}
* @module alepha.react
*/
declare const AlephaReact: _alepha_core14.Service<_alepha_core14.Module>;
//#endregion
export { $page, AlephaContext, AlephaReact, AnchorProps, ClientOnly, CreateLayersResult, ErrorBoundary, ErrorHandler, ErrorViewer, Layer, Link, LinkProps, _default as NestedView, NotFoundPage as NotFound, PageAnimation, PageConfigSchema, PageDescriptor, PageDescriptorOptions, PageDescriptorRenderOptions, PageDescriptorRenderResult, PageRequestConfig, PageResolve, PageRoute, PageRouteEntry, PreviousLayerData, ReactBrowserProvider, ReactBrowserRendererOptions, ReactHydrationState, ReactPageProvider, ReactRouter, ReactRouterState, ReactServerProvider, Redirection, RouterGoOptions, RouterLayerContext, RouterLayerContextValue, RouterRenderOptions, RouterStackItem, TPropsDefault, TPropsParentDefault, TransitionOptions, UseActiveHook, UseActiveOptions, UseQueryParamsHookOptions, UseSchemaReturn, VirtualRouter, isPageRoute, ssrSchemaLoading, useActive, useAlepha, useClient, useInject, useQueryParams, useRouter, useRouterEvents, useRouterState, useSchema, useStore };
//# sourceMappingURL=index.d.ts.map