import { l as HttpStatus } from "./schema-DKqL09oQ.mjs"; import { StandardSchemaV1 } from "@standard-schema/spec"; import { OpenAPI } from "openapi-types"; //#region src/internal/utils.d.ts declare const IsStatusResult: unique symbol; //#endregion //#region src/types.d.ts /** * Represents an App object. TAppData represents additional type information not * always stored on the app object itself. */ interface App { /** * Internal references for implementing routing and calling registered * handlers. Subject to breaking changes outside of major versions. * @internal */ "~zeta": { /** * Used for deduplication of hooks. */ id: string; /** * When true, hooks defined on this app should be added to any app that * imports this app. */ exported?: boolean; /** * Path prefix from `CreateAppOptions.prefix`. */ prefix: string; /** * List of routes registered with the app. */ routes: { [method: string]: { [path: string]: RouterData; }; }; /** * Stores arrays of hooks registered on the app. */ hooks: LifeCycleHooks; }; /** * Merge and simplify all the app routes into a single fetch function. */ build: () => ServerSideFetch; /** * Returns your application's OpenAPI spec. You do not need to listen to a * port to call this method. */ getOpenApiSpec: () => OpenAPI.Document; /** * Mark the app as "exported". When an exported app is `use`d by a * parent app, the parent app will inherit all of it's hooks and modifiers. * * Regular, non-exported apps isolate their hooks and modifiers from the * parent app (except for the global hooks, `onGlobalRequest`, `onGlobalError`, and * `onGlobalAfterResponse`, which are always inherited by the parent app). * * The basic example is you can't access a decorated value from a parent app * unless the child app is exported. * * @example * ```ts * const child = createApp() * .decorate("a", "A"); * * const bad = createApp() * .use(child) * .get("/", ({ a }) => { * console.log(a); // => undefined * }); * * const good = createApp() * .use(child.export()) * .get("/", ({ a }) => { * console.log(a); // => "A" * }); * ``` */ export: () => App>; /** * Detect the current environment and use `Bun.serve` or `Deno.serve` to serve the app over a port. * @param port The port to listen on. * @param cb Optional callback to be called when the server is ready. */ listen: (port: number, cb?: () => void) => this; /** * Add a static value to the handler context. */ decorate(key: TKey, value: TValue): App }; }>>>; /** * Add multiple static values to the handler context. */ decorate>(values: TValues): App>>; /** * Add a callback that is called before the route is matched. If the callback * returns a value, it will be merged into the `ctx` object. If the callback * returns a `Response`, it will be returned immediately. * * @param callback The function to call. */ onGlobalRequest(callback: (ctx: OnGlobalRequestContext>) => MaybePromise): this; onGlobalRequest>(callback: (ctx: OnGlobalRequestContext>) => MaybePromise): App>; /** * Add a callback that is called after the route is matched and before the * inputs are validated. If the callback returns a value, it will be merged * into the `ctx` object. If the callback returns a `Response`, it will be * returned immediately. * * @param callback The function to call. */ onTransform(callback: (ctx: OnTransformContext>) => MaybePromise): this; onTransform>(callback: (ctx: OnTransformContext>) => MaybePromise): App>; /** * Add a callback that is called after inputs are validated and before the * handler is called. If the callback returns a value, it will be merged into * the `ctx` object. If the callback returns a `Response`, it will be returned * immediately. * * @param callback The function to call. */ onBeforeHandle(callback: (ctx: OnBeforeHandleContext>) => MaybePromise): this; onBeforeHandle>(callback: (ctx: OnBeforeHandleContext>) => MaybePromise): App>; /** * Add a callback that is called after the handler is called and before the * response is validated. If the callback returns a value, it replaces the * response with it. * * @param callback The function to call. */ onAfterHandle(callback: (ctx: AfterHandleContext>) => MaybePromise): this; /** * Add a callback that is called after the response is validated and before it * is sent to the client. The callback can return a `Response` if you want to * change how the response is built. * * @param callback The function to call. */ onMapResponse(callback: (ctx: AfterHandleContext>) => MaybePromise): this; /** * Add a callback that is called when an error is thrown. The callback can * optionally return a `Response`, which will be used to respond to the * client. * * @param callback The function to call. */ onGlobalError(callback: (ctx: OnGlobalErrorContext>) => MaybePromise): this; /** * Add a callback that is called after the response is sent. * @param callback The function to call. */ onGlobalAfterResponse(callback: (ctx: AfterResponseContext>) => MaybePromise): this; /** * Add an undocumented GET route to the app. */ get(path: TPath, handler: RouteHandler): App>; /** * Add a documented GET route to the app. */ get(path: TPath, def: TRouteDef, handler: RouteHandler): App>; /** * Add an undocumented POST route to the app. */ post(path: TPath, handler: RouteHandler): App>; /** * Add a documented POST route to the app. */ post(path: TPath, def: TRouteDef, handler: RouteHandler): App>; /** * Add an undocumented PUT route to the app. */ put(path: TPath, handler: RouteHandler): App>; /** * Add a documented PUT route to the app. */ put(path: TPath, def: TRouteDef, handler: RouteHandler): App>; /** * Add an undocumented DELETE route to the app. */ delete(path: TPath, handler: RouteHandler): App>; /** * Add a documented DELETE route to the app. */ delete(path: TPath, def: TRouteDef, handler: RouteHandler): App>; /** * Add an undocumented route to the app that responds to any method used. */ any(path: TPath, handler: RouteHandler): App>; /** * Add an documented route to the app that responds to any method used. */ any(path: TPath, def: TRouteDef, handler: RouteHandler): App>; /** * Add an undocumented route to the app using a custom method. */ method(method: TMethod, path: TPath, handler: RouteHandler): App>; /** * Add a documented route to the app using a custom method. */ method(method: TMethod, path: TPath, def: TRouteDef, handler: RouteHandler): App>; /** * Mount another fetch function at `/**`. */ mount(fetch: ServerSideFetch): App>; /** * Mount another fetch function at `${path}/**`. */ mount(path: TPath, fetch: ServerSideFetch): App>; /** * Mount another fetch function at `${path}/**`. */ mount(path: TPath, def: TRouteDef, fetch: ServerSideFetch): App>; /** * Add a subapp to the app. */ use(app: TNewApp): App>>; } /** * Given an `App`, return it's `AppData`. */ type GetAppData = TApp extends App ? TAppData : never; /** * Given an `App`, return the routes defined on it. */ type GetAppRoutes = GetAppData["routes"]; /** * Data stored internally for each route inside the `rou3` router. */ type RouterData = { def?: RouteDef; route: string; hooks: LifeCycleHooks; compiledHandler: CompiledRouteHandler; } & ({ fetch: ServerSideFetch; } | { handler: (ctx: OnBeforeHandleContext) => Promise; }); /** * Function type called internally once a route is matched for a request. */ type CompiledRouteHandler = (request: Request, ctx: any) => MaybePromise; /** * Type of the callback function used for each route. */ type RouteHandler = (ctx: BuildHandlerContext) => MaybePromise>; type GetRouteHandlerReturnType = TRouteDef extends { responses: symbol; } ? any : TRouteDef extends { responses: infer TResponses; } ? TResponses extends StandardSchemaV1 ? StandardSchemaV1.InferInput : TRouteDef["responses"] extends Record> ? StatusResult : never : void; /** * Given an `App`, a method, and a route, return the handler function's type. */ type GetRouteHandler, TRoute extends keyof GetAppRoutes[TMethod]> = TRoute extends BasePath ? GetAppRoutes[TMethod][TRoute] extends RouteDef ? RouteHandler, TRoute, GetAppRoutes[TMethod][TRoute]> : never : never; /** * Internal type used to store a hook on an app. */ type LifeCycleHook = { /** * Used for deducplication. */ id: string; /** * Where this plugin should be applied. * - `global`: Global plugins are hoisted to the top-level app. * - `local`: Local plugins are applied to the app they were added to. * @default "local" */ applyTo: "global" | "local"; /** * The function called when the hook is triggered. */ callback: TCallback; }; /** * Called immediately after receiving the request. Returned record is merged * into the handler context. */ type OnGlobalRequestHook = LifeCycleHook<(ctx: Simplify) => Record | void>; /** * Called before validating the request inputs. Returned record is merged into * the handler context. */ type OnTransformHook = LifeCycleHook<(ctx: Simplify) => MaybePromise | void>>; /** * Called before calling the route handler. Returned record is merged into the * handler context. */ type OnBeforeHandleHook = LifeCycleHook<(ctx: Simplify) => MaybePromise | void>>; /** * Called after calling the route handler. If there is a return value, it * replaces the return value from the handler. Similar to the `onTransform` hook, * but for the response. */ type OnAfterHandleHook = LifeCycleHook<(ctx: Simplify) => MaybePromise>; /** * Called after validating the handler return value. Used to transform the * return value into a `Response`. */ type OnMapResponseHook = LifeCycleHook<(ctx: Simplify) => MaybePromise>; /** * Called if an error is thrown in any other hook other than `onGlobalAfterResponse`. * * Zeta will handle any `HttpError`s thrown, but you can handle your own errors * here. */ type OnGlobalErrorHook = LifeCycleHook<(ctx: Simplify) => void>; /** * Called after the response is sent back to the client. */ type OnGlobalAfterResponseHook = LifeCycleHook<(ctx: Simplify) => void>; type LifeCycleHooks = { onGlobalRequest?: OnGlobalRequestHook[]; onTransform?: OnTransformHook[]; onBeforeHandle?: OnBeforeHandleHook[]; onAfterHandle?: OnAfterHandleHook[]; onMapResponse?: OnMapResponseHook[]; onGlobalError?: OnGlobalErrorHook[]; onGlobalAfterResponse?: OnGlobalAfterResponseHook[]; }; type LifeCycleHookName = keyof LifeCycleHooks; /** * Base data type associated with each app. */ type AppData = { exported: boolean; prefix: BasePrefix; ctx: BaseCtx; routes: BaseRoutes; transport: AnyTransport; }; /** * Minimal data type that works with `AppData`. */ type DefaultAppData = { exported: false; prefix: ""; ctx: {}; routes: {}; transport: AnyTransport; }; /** * Minimal data type that matches `AppData["ctx"]`. */ type BaseCtx = Record; /** * Minimal data type that matches `AppData["routes"]`. */ type BaseRoutes = { [method: string]: { [path: BasePath]: RouteDef; }; }; /** * Minimal data type that matches `AppData["routes"][method][path]`, containing information about the route. */ type RouteDef = Simplify & { headers?: StandardSchemaV1>; params?: StandardSchemaV1>; query?: StandardSchemaV1>; body?: StandardSchemaV1; responses?: StandardSchemaV1 | Record; }>; /** * Used for `TDef` when a route definition is not passed. Essentially removes type-safety from a route. */ type AnyDef = { headers: StandardSchemaV1>; params: StandardSchemaV1>; query: StandardSchemaV1>; body: StandardSchemaV1; responses: any; }; /** * Base type representing what strings can be passed as a `prefix` when creating an app. */ type BasePrefix = BasePath | ""; /** * Base type representing what a route's string must look like. */ type BasePath = `/${string}`; interface RequestContext { request: Request; url: URL; path: string; method: string; set: Setter; } /** * `ctx` type used in the `onGlobalRequest` hook. */ type OnGlobalRequestContext = TCtx & RequestContext; /** * `ctx` type used in the `onTransform` hook. */ type OnTransformContext = OnGlobalRequestContext & { route: string; params?: Record; query?: Record; headers?: Record; body?: any; }; /** * `ctx` type used in the `onBeforeHandle` hook. */ type OnBeforeHandleContext = OnTransformContext; /** * `ctx` type used in the `onAfterHandle` hook. */ type AfterHandleContext = OnTransformContext & { response?: unknown; }; /** * `ctx` type used in the `onMapResponse` hook. */ type OnMapResponseContext = AfterHandleContext & {}; /** * `ctx` type used in the `onGlobalError` hook. */ type OnGlobalErrorContext = OnGlobalRequestContext & Partial & { error: unknown; }; /** * `ctx` type used in the `onGlobalAfterResponse` hook. */ type AfterResponseContext = OnGlobalRequestContext & Partial & { response: Response; }; /** * Given an `AppData` type, return the type of it's `ctx`. */ type GetAppDataCtx = TAppData extends { ctx: infer TCtx; } ? TCtx : never; type StatusFn> = TMap extends never ? never : (status: TStatus, body: StandardSchemaV1.InferInput) => StatusResult; type GetResponseStatusMap = TRouteDef extends { responses: unknown; } ? TRouteDef["responses"] extends symbol ? Record> : TRouteDef["responses"] extends StandardSchemaV1 ? { 200: TRouteDef["responses"]; } : TRouteDef["responses"] extends Record ? TRouteDef["responses"] : any : never; type StatusResult = { [IsStatusResult]: true; status: number; body: unknown; }; /** * Build the `ctx` type used for request handlers. */ type BuildHandlerContext = Simplify>, InputParams> & { route: TPath; } & GetRequestParamsOutputFromDef & { status: StatusFn>; }>; /** * Given two `App`s, merge their data to match the behavior of `TParent.use(TChild)`. */ type UseApp = App, GetAppData>>>; /** * Same as `UseApp`, but instead of app instances, it merges the `AppData` of each. */ type UseAppData = TChildData extends { exported: true; } ? MergeAppData, "ctx" | "routes">> : MergeAppData, "routes">>; /** * Merge two `App` types together. See `MergeAppData` for details. */ type MergeApp = T1 extends App ? T2 extends App ? App>> : never : never; /** * Merge two `AppData` types together. * - `prefix`: The second app's prefix overrides the first if present. * - `ctx`: The second app's context gets merged with the first if present. Any * existing keys are overwritten to match the second app's context. * - `exported`: The second app's exported status overrides the first if * present. * - `routes`: See `MergeRoutes` for details. * - `transport`: Use the original transport, it cannot be overridden */ type MergeAppData> = Simplify<{ prefix: T2["prefix"] extends string ? T2["prefix"] : T1["prefix"]; ctx: T2["ctx"] extends BaseCtx ? Simplify> : T1["ctx"]; exported: T2["exported"] extends boolean ? T2["exported"] : T1["exported"]; routes: T2["routes"] extends BaseRoutes ? Simplify> : T1["routes"]; transport: T1["transport"]; }>; /** * Merges two route objects together, 2 levels deep. If the same method/path * combination exists in both apps, the second app's route overrides the first. */ type MergeRoutes, B extends Record> = Simplify>; /** * Given an app and a new prefix, return a new app type with app's original * prefix applied to each route, and with the new prefix stored in the * `AppData`. */ type ApplyAppPrefix = App, TNewPrefix>>>; /** * Same as `ApplyAppPrefix`, but at the `AppData` level. */ type ApplyAppDataPrefix = { ctx: TAppData["ctx"]; exported: TAppData["exported"]; prefix: TNewPrefix; routes: TAppData["prefix"] extends BasePath ? { [TMethod in keyof TAppData["routes"]]: Simplify> } : TAppData["routes"]; transport: TAppData["transport"]; }; /** * Given a route definition, return the input types of all the params. */ type GetRequestParamsInputFromDef = TRouteDef extends AnyDef ? { headers?: Record; params?: Record; query?: Record; body?: any; } : Simplify<{ [key in keyof GetDefParams]: TRouteDef[key] extends StandardSchemaV1 ? StandardSchemaV1.InferInput : never }>; /** * Given a set of routes, a method, and a route, return the input types of all * the schemas in the route definition. */ type GetRequestParamsInput = TRoute extends BasePath ? GetRequestParamsInputFromDef : never; /** * Given a route definition, return the input type of the response schema. */ type GetResponseInputFromDef = TRouteDef["responses"] extends undefined ? undefined : TRouteDef["responses"] extends StandardSchemaV1 ? StandardSchemaV1.InferInput : never; /** * Given a set of routes, a method, and a route, return the input type of the * response schema in the route definition. */ type GetResponseInput = TPath extends BasePath ? GetResponseInputFromDef : never; /** * Helper type for converting a schema or object containing schemas to their * output types. */ type ToStandardSchemaOutputs = T extends StandardSchemaV1 ? StandardSchemaV1.InferOutput : T extends { [key in keyof T]: any } ? { [key in keyof T]: ToStandardSchemaOutputs } : never; /** * Given a route definition, return the output type of the param schemas. */ type GetRequestParamsOutputFromDef = ToStandardSchemaOutputs>; /** * Given a set of routes, a method, and a route, return the output type of the * param schemas. */ type GetRequestParamsOutput = TRoute extends BasePath ? GetRequestParamsOutputFromDef : never; type SuccessStatusCodes = 200 | HttpStatus.Ok | 201 | HttpStatus.Created | 202 | HttpStatus.Accepted | 203 | HttpStatus.NonAuthoritativeInformation | 204 | HttpStatus.NoContent | 205 | HttpStatus.ResetContent | 206 | HttpStatus.PartialContent | 207 | HttpStatus.MultiStatus | 208 | HttpStatus.AlreadyReported | 226 | HttpStatus.ImUsed; /** * Given a `RouteDef`, return a union of all possible handler return values. * * If `responses` is defined, it will be a discriminated union of objects * containing the status and body. * * If only `response` is defined, it will be the output of that schema. * * If neither is defined, it will be `void`. */ type GetResponseOutputFromDef = TRouteDef["responses"] extends undefined ? undefined : TRouteDef["responses"] extends StandardSchemaV1 ? StandardSchemaV1.InferOutput : { [key in SuccessStatusCodes & keyof TRouteDef["responses"]]: TRouteDef["responses"][key] extends StandardSchemaV1 ? StandardSchemaV1.InferOutput : unknown }[SuccessStatusCodes & keyof TRouteDef["responses"]]; /** * Given a set of routes, a method, and a route, return the output type of the * response schema. */ type GetResponseOutput = TPath extends BasePath ? GetResponseOutputFromDef : 1; type InputParams = "headers" | "params" | "query" | "body"; /** * Given a route definition, return an object with only the input parameeters. */ type GetDefParams = { [key in InputParams & keyof TRouteDef]: TRouteDef[key] }; /** * To generate open API docs, Zeta needs to know how process and extract * some information from your schema. This adapter is responsible for * providing additional functions for parsing your schema. */ interface SchemaAdapter { /** * Convert a standard schema definition to it's JSON schema. * @param schema The schema to convert. * @returns The JSON schema. */ toJsonSchema: (schema: any) => any; getMeta: (schema: StandardSchemaV1) => Record | undefined; } interface Transport { /** * Actually bind the server to a local port for hosting. */ listen: (port: number, fetch: ServerSideFetch, cb?: () => void) => void; /** * Callback where the ctx object can be modified based on the args provided to the fetch function. */ decorate?: (ctx: any, ...fetchArgs: TFetchArgs) => void; } type AnyTransport = Transport<[request: Request, ...params: any[]]>; /** * Basic object type used to store custom status and headers set while handling the request. */ interface Setter { /** * Set this value to change the status code returned. */ status: number; /** * Set a value on this header to change which headers are sent in the response. */ headers: Record; } /** * Given a union of objects, combine them into a single object that's easy to read. */ type Simplify = T extends { [key: string]: any; } ? { [K in keyof T]: T[K] } : T; /** * Returns either a Promise of a type or just the type itself. */ type MaybePromise = Promise | T; /** * A function that, given a request, returns a response. This type is compliant with WinterCG. */ type ServerSideFetch = TTransport extends Transport ? (...args: Params) => MaybePromise : never; /** * Apply a string prefix to all the keys of an object. */ type PrefixObjectKeys> = { [K in keyof TObject as `${TPrefix}${string & K extends "/" ? "" : string & K}`]: TObject[K] }; /** * A helper type that models a single-level object spread: { ...L, ...R } * It takes all properties from R, and all properties from L that are not in R. */ type Spread = Omit & R; /** * Merges two objects, A and B, two levels deep. * * It combines the keys from both A and B. * - If a key exists only in A or only in B, it's carried over. * - If a key exists in *both* A and B, it recursively merges their * values using a single-level spread (`Spread`). * This ensures properties from B's inner objects overwrite those from A's. */ type Merge = Omit & { [K in keyof B]: K extends keyof A ? Simplify> : B[K] }; //#endregion export { RouteHandler as $, LifeCycleHook as A, OnBeforeHandleHook as B, GetResponseInput as C, GetResponseStatusMap as D, GetResponseOutputFromDef as E, MergeApp as F, OnGlobalRequestHook as G, OnGlobalErrorContext as H, MergeAppData as I, OnTransformContext as J, OnMapResponseContext as K, MergeRoutes as L, LifeCycleHooks as M, MaybePromise as N, GetRouteHandler as O, Merge as P, RouteDef as Q, OnAfterHandleHook as R, GetRequestParamsOutputFromDef as S, GetResponseOutput as T, OnGlobalErrorHook as U, OnGlobalAfterResponseHook as V, OnGlobalRequestContext as W, PrefixObjectKeys as X, OnTransformHook as Y, RequestContext as Z, GetAppDataCtx as _, App as a, StatusFn as at, GetRequestParamsInputFromDef as b, ApplyAppPrefix as c, UseApp as ct, BasePrefix as d, RouterData as et, BaseRoutes as f, GetAppData as g, DefaultAppData as h, AnyTransport as i, Simplify as it, LifeCycleHookName as j, GetRouteHandlerReturnType as k, BaseCtx as l, UseAppData as lt, CompiledRouteHandler as m, AfterResponseContext as n, ServerSideFetch as nt, AppData as o, StatusResult as ot, BuildHandlerContext as p, OnMapResponseHook as q, AnyDef as r, Setter as rt, ApplyAppDataPrefix as s, Transport as st, AfterHandleContext as t, SchemaAdapter as tt, BasePath as u, GetAppRoutes as v, GetResponseInputFromDef as w, GetRequestParamsOutput as x, GetRequestParamsInput as y, OnBeforeHandleContext as z };