@h3ravel/shared
Version:
Shared Utilities.
399 lines (388 loc) • 14.6 kB
text/typescript
import { H3Event, Middleware, MiddlewareOptions, H3, serve } from 'h3';
import { Edge } from 'edge.js';
import { TypedHeaders, ResponseHeaderMap } from 'fetchdts';
/**
* Adds a dot prefix to nested keys
*/
type DotPrefix<T extends string, U extends string> = T extends '' ? U : `${T}.${U}`;
/**
* Converts a union of objects into a single merged object
*/
type MergeUnion<T> = (T extends any ? (k: T) => void : never) extends (k: infer I) => void ? {
[K in keyof I]: I[K];
} : never;
/**
* Flattens nested objects into dotted keys
*/
type DotFlatten<T, Prefix extends string = ''> = MergeUnion<{
[K in keyof T & string]: T[K] extends Record<string, any> ? DotFlatten<T[K], DotPrefix<Prefix, K>> : {
[P in DotPrefix<Prefix, K>]: T[K];
};
}[keyof T & string]>;
/**
* Builds "nested.key" paths for autocompletion
*/
type DotNestedKeys<T> = {
[K in keyof T & string]: T[K] extends object ? `${K}` | `${K}.${DotNestedKeys<T[K]>}` : `${K}`;
}[keyof T & string];
/**
* Retrieves type at a given dot-path
*/
type DotNestedValue<T, Path extends string> = Path extends `${infer Key}.${infer Rest}` ? Key extends keyof T ? DotNestedValue<T[Key], Rest> : never : Path extends keyof T ? T[Path] : never;
/**
* Interface for the Container contract, defining methods for dependency injection and service resolution.
*/
interface IContainer {
/**
* Binds a transient service to the container.
* @param key - The key or constructor for the service.
* @param factory - The factory function to create the service instance.
*/
bind<T>(key: new (...args: any[]) => T, factory: () => T): void;
bind<T extends UseKey>(key: T, factory: () => Bindings[T]): void;
/**
* Binds a singleton service to the container.
* @param key - The key or constructor for the service.
* @param factory - The factory function to create the singleton instance.
*/
singleton<T extends UseKey>(key: T | (new (...args: any[]) => Bindings[T]), factory: () => Bindings[T]): void;
/**
* Resolves a service from the container.
* @param key - The key or constructor for the service.
* @returns The resolved service instance.
*/
make<T extends UseKey, X = undefined>(key: T | (new (..._args: any[]) => Bindings[T])): X extends undefined ? Bindings[T] : X;
/**
* Checks if a service is registered in the container.
* @param key - The key to check.
* @returns True if the service is registered, false otherwise.
*/
has(key: UseKey): boolean;
}
interface IServiceProvider {
/**
* Sort order
*/
order?: `before:${string}` | `after:${string}` | string | undefined;
/**
* Sort priority
*/
priority?: number;
/**
* Register bindings to the container.
* Runs before boot().
*/
register(): void | Promise<void>;
/**
* Perform post-registration booting of services.
* Runs after all providers have been registered.
*/
boot?(): void | Promise<void>;
}
type IPathName = 'views' | 'routes' | 'assets' | 'base' | 'public' | 'storage' | 'config';
interface IApplication extends IContainer {
/**
* Registers configured service providers.
*/
registerConfiguredProviders(): Promise<void>;
/**
* Registers an array of external service provider classes.
* @param providers - Array of service provider constructor functions.
*/
registerProviders(providers: Array<new (app: IApplication) => IServiceProvider>): void;
/**
* Registers a single service provider.
* @param provider - The service provider instance to register.
*/
register(provider: IServiceProvider): Promise<void>;
/**
* Boots all registered providers.
*/
boot(): Promise<void>;
/**
* Gets the base path of the application.
* @returns The base path as a string.
*/
getBasePath(): string;
/**
* Retrieves a path by name, optionally appending a sub-path.
* @param name - The name of the path property.
* @param pth - Optional sub-path to append.
* @returns The resolved path as a string.
*/
getPath(name: string, pth?: string): string;
/**
* Sets a path for a given name.
* @param name - The name of the path property.
* @param path - The path to set.
* @returns
*/
setPath(name: IPathName, path: string): void;
/**
* Gets the version of the application or TypeScript.
* @param key - The key to retrieve ('app' or 'ts').
* @returns The version string or undefined.
*/
getVersion(key: 'app' | 'ts'): string | undefined;
}
/**
* Interface for the Request contract, defining methods for handling HTTP request data.
*/
interface IRequest {
/**
* The current app instance
*/
app: IApplication;
/**
* Gets route parameters.
* @returns An object containing route parameters.
*/
params: NonNullable<H3Event["context"]["params"]>;
/**
* Gets query parameters.
* @returns An object containing query parameters.
*/
query: Record<string, any>;
/**
* Gets the request headers.
* @returns An object containing request headers.
*/
headers: TypedHeaders<Record<keyof ResponseHeaderMap, string>>;
/**
* Gets all input data (query parameters, route parameters, and body).
* @returns A promise resolving to an object containing all input data.
*/
all<T = Record<string, unknown>>(): Promise<T>;
/**
* Gets a single input field from query or body.
* @param key - The key of the input field.
* @param defaultValue - Optional default value if the key is not found.
* @returns A promise resolving to the value of the input field or the default value.
*/
input<T = unknown>(key: string, defaultValue?: T): Promise<T>;
/**
* Gets the underlying event object or a specific property of it.
* @param key - Optional key to access a nested property of the event.
* @returns The entire event object or the value of the specified property.
*/
getEvent(): H3Event;
getEvent<K extends DotNestedKeys<H3Event>>(key: K): DotNestedValue<H3Event, K>;
}
/**
* Interface for the Response contract, defining methods for handling HTTP responses.
*/
interface IResponse {
/**
* The current app instance
*/
app: IApplication;
/**
* Sets the HTTP status code for the response.
* @param code - The HTTP status code.
* @returns The instance for method chaining.
*/
setStatusCode(code: number): this;
/**
* Sets a response header.
* @param name - The header name.
* @param value - The header value.
* @returns The instance for method chaining.
*/
setHeader(name: string, value: string): this;
/**
* Sends an HTML response.
* @param content - The HTML content to send.
* @returns The HTML content.
*/
html(content: string): string;
/**
* Sends a JSON response.
* @param data - The data to send as JSON.
* @returns The input data.
*/
json<T = unknown>(data: T): T;
/**
* Sends a plain text response.
* @param data - The text content to send.
* @returns The text content.
*/
text(data: string): string;
/**
* Redirects to another URL.
* @param url - The URL to redirect to.
* @param status - The HTTP status code for the redirect (default: 302).
* @returns The redirect URL.
*/
redirect(url: string, status?: number): string;
/**
* Gets the underlying event object or a specific property of it.
* @param key - Optional key to access a nested property of the event.
* @returns The entire event object or the value of the specified property.
*/
getEvent(): H3Event;
getEvent<K extends DotNestedKeys<H3Event>>(key: K): DotNestedValue<H3Event, K>;
}
type RouterEnd = 'get' | 'delete' | 'put' | 'post' | 'patch' | 'apiResource' | 'group' | 'route';
/**
* Interface for the Router contract, defining methods for HTTP routing.
*/
interface IRouter {
/**
* Registers a GET route.
* @param path - The route path.
* @param definition - The handler function or [controller class, method] array.
* @param name - Optional route name.
* @param middleware - Optional middleware array.
*/
get(path: string, definition: EventHandler | [(new (...args: any[]) => IController), methodName: string], name?: string, middleware?: IMiddleware[]): Omit<this, RouterEnd>;
/**
* Registers a POST route.
* @param path - The route path.
* @param definition - The handler function or [controller class, method] array.
* @param name - Optional route name.
* @param middleware - Optional middleware array.
*/
post(path: string, definition: EventHandler | [(new (...args: any[]) => IController), methodName: string], name?: string, middleware?: IMiddleware[]): Omit<this, RouterEnd>;
/**
* Registers a PUT route.
* @param path - The route path.
* @param definition - The handler function or [controller class, method] array.
* @param name - Optional route name.
* @param middleware - Optional middleware array.
*/
put(path: string, definition: EventHandler | [(new (...args: any[]) => IController), methodName: string], name?: string, middleware?: IMiddleware[]): Omit<this, RouterEnd>;
/**
* Registers a DELETE route.
* @param path - The route path.
* @param definition - The handler function or [controller class, method] array.
* @param name - Optional route name.
* @param middleware - Optional middleware array.
*/
delete(path: string, definition: EventHandler | [(new (...args: any[]) => IController), methodName: string], name?: string, middleware?: IMiddleware[]): Omit<this, RouterEnd>;
/**
* Registers an API resource with standard CRUD routes.
* @param path - The base path for the resource.
* @param controller - The controller class handling the resource.
* @param middleware - Optional middleware array.
*/
apiResource(path: string, controller: new (app: IApplication) => IController, middleware?: IMiddleware[]): Omit<this, RouterEnd | 'name'>;
/**
* Generates a URL for a named route.
* @param name - The name of the route.
* @param params - Optional parameters to replace in the route path.
* @returns The generated URL or undefined if the route is not found.
*/
route(name: string, params?: Record<string, string>): string | undefined;
/**
* Set the name of the current route
*
* @param name
*/
name(name: string): this;
/**
* Groups routes with shared prefix or middleware.
* @param options - Configuration for prefix or middleware.
* @param callback - Callback function defining grouped routes.
*/
group(options: {
prefix?: string;
middleware?: EventHandler[];
}, callback: () => this): this;
/**
* Registers middleware for a specific path.
* @param path - The path to apply the middleware.
* @param handler - The middleware handler.
* @param opts - Optional middleware options.
*/
middleware(path: string | IMiddleware[], handler: Middleware, opts?: MiddlewareOptions): this;
}
/**
* Represents the HTTP context for a single request lifecycle.
* Encapsulates the application instance, request, and response objects.
*/
declare class HttpContext {
app: IApplication;
request: IRequest;
response: IResponse;
constructor(app: IApplication, request: IRequest, response: IResponse);
/**
* Factory method to create a new HttpContext instance from a context object.
* @param ctx - Object containing app, request, and response
* @returns A new HttpContext instance
*/
static init(ctx: {
app: IApplication;
request: IRequest;
response: IResponse;
}): HttpContext;
}
/**
* Type for EventHandler, representing a function that handles an H3 event.
*/
type EventHandler = (ctx: HttpContext) => any;
type RouteEventHandler = (...args: any[]) => any;
/**
* Defines the contract for all controllers.
* Any controller implementing this must define these methods.
*/
interface IController {
show(...ctx: any[]): any;
index(...ctx: any[]): any;
store(...ctx: any[]): any;
update(...ctx: any[]): any;
destroy(...ctx: any[]): any;
}
/**
* Defines the contract for all middlewares.
* Any middleware implementing this must define these methods.
*/
interface IMiddleware {
handle(context: HttpContext, next: () => Promise<any>): Promise<any>;
}
declare class PathLoader {
private paths;
/**
* Dynamically retrieves a path property from the class.
* Any property ending with "Path" is accessible automatically.
*
* @param name - The base name of the path property
* @param base - The base path to include to the path
* @returns
*/
getPath(name: IPathName, base?: string): string;
/**
* Programatically set the paths.
*
* @param name - The base name of the path property
* @param path - The new path
* @param base - The base path to include to the path
*/
setPath(name: IPathName, path: string, base?: string): void;
}
type RemoveIndexSignature<T> = {
[K in keyof T as string extends K ? never : number extends K ? never : K]: T[K];
};
type Bindings = {
[key: string]: any;
[key: `app.${string}`]: any;
env(): NodeJS.ProcessEnv;
env<T extends string>(key: T, def?: any): any;
view(templatePath: string, state?: Record<string, any>): Promise<string>;
edge: Edge;
asset(key: string, def?: string): string;
router: IRouter;
config: {
get<X extends Record<string, any>>(): X;
get<X extends Record<string, any>, T extends Extract<keyof X, string>>(key: T, def?: any): X[T];
set<T extends string>(key: T, value: any): void;
load?(): any;
};
'http.app': H3;
'path.base': string;
'load.paths': PathLoader;
'http.serve': typeof serve;
'http.request': IRequest;
'http.response': IResponse;
};
type UseKey = keyof RemoveIndexSignature<Bindings>;
export { type Bindings, type DotFlatten, type DotNestedKeys, type DotNestedValue, type EventHandler, HttpContext, type IApplication, type IContainer, type IController, type IMiddleware, type IPathName, type IRequest, type IResponse, type IRouter, type IServiceProvider, PathLoader, type RouteEventHandler, type RouterEnd, type UseKey };