Skip to main content
Module

x/cav/mod.ts

A server framework for Deno
Go to Latest
import * as cav from "https://deno.land/x/cav@0.0.14/mod.ts";

Classes

An error class for describing exceptions during HTTP processing.

Variables

A special 404 HttpError that should be thrown whenever a handler is refusing to respond to a request due to the path not matching constraints. This is thrown by Rpcs when path matching fails. If a Stack catches this error, it will continue looking for matching routes.

Functions

Utility for creating an Rpc handler specifically for serving static assets. The resolver's path argument is used as the asset path.

Creates a cookie tied to the given request and response headers. The keys provided will be used for cookie signing; if no keys are provided, a random fallback key will be used. Keys need to be provided in an array, making key rotation easier.

Bundles browser-only JavaScript and TypeScript files into a single JavaScript output, with the ability to watch the module graph for changes to trigger a re-bundle. The input file and all of its dependencies will be included in the bundle. Bundling uses Deno's runtime compiler API behind-the-scenes, which requires the --unstable flag.

Constructs a new Client tied to a given base URL. The provided set of packers will be used everywhere that data is packed/unpacked when using this client, including web sockets.

Utility function used in the packing functions that determines if an object is a plain object or not. Because this is such a common operation when checking and serializing unknown objects, it's being exported as part of the API.

Packs a value recursively until it's JSON-compatible. Packers can be plugged in to extend the accepted types beyond what Cav supports by default as well as the packers registered with usePackers(). Referential equality will be preserved whenever the same object or symbol value is encountered more than once. If a value isn't recognized by any of the used packers or the default packers, an error is thrown.

Packs a value into a type that is compatible with a Response BodyInit, making it easy to pack values for sending to an external host/client via HTTP. If a provided value is already compatible with BodyInit, it will be returned with an appropriate mime type, skipping the packing process. During packing, this function extends the default supported types to include Blobs and Files. If a Blob is encountered during packing, the resulting body will be a multipart FormData that encodes the shape of the input as well as the blobs that were encountered. Otherwise, a regular JSON string will be returned. Blobs and Files can be placed anywhere on the input value, even if they are nested.

Constructs a Packer. This simply returns the first argument, it's only used for type annotations.

Packs the value into a JSON string. This function is a one-liner:

Utility for creating an Rpc handler that always redirects. If an origin isn't provided in the redirect url, the origin of the request will be used. Paths can also be relative; if the path starts with a ".", the path will be joined with the pathname of the request using the std path.join() function. If the status isn't provided, 302 is used. Note that paths with trailing slashes will be redirected first to the path without the trailing slash before being redirect to the specified destination. (2 hops)

Returns a parsed body from a given request after checking size constraints. Uses unpackBody to unpack the request body.

Generates or returns a previously generated RequestData for a given request. If this is the first time requestData is being called for the given request, the RequestData object is generated and returned. Every other time the request passes through this function, the same object generated on the first call is returned without further modification.

Creates a TypedResponse from the provided body, which undergoes packing via packBody. Extra packers can be provided using the "packers" option on the init argument. If a Response is passed in as the body, its body will be used without re-packing; headers and status/text will still be updated to match the provided init.

Creates an endpoint handler for resolving Requests into Responses.

Constructs a new RpcInit. This simply returns the first argument, it's only provided for typing purposes so that you don't need to manually specify the type parameters.

Shorthand function for quickly serving a Handler. This function is a one-liner:

Response factory for serving static assets. Asset resolution uses the provided ServeAssetOptions, the Request is only used for caching headers like ETag etc.

Creates a Server using the provided ServerInit. Note that there is no "onError" init option; errors that bubble up to the Server level are logged and a 500 Response is sent back to the client. You should handle errors as close as possible to where the error occurred, for example using the Rpc "onError" init option.

Constructs a StackHandler using the given StackRoutes object. The first matching handler in the provided routes to either return a Response or throw an unknown error halts the matching process. If a handler throws the special NO_MATCH error, the error is suppressed and matching continues. See the documentation for more details about StackRoutes and how routing inside a Stack works.

Unpacks a value packed with pack() into the original value. Referential equality will be restored on the output object. An error will be thrown if a value was packed with an unknown/unused packer.

Unpacks a Request or Response object whose body was packed with packBody(). Any packers used outside of the library defaults during packing need to be provided here as well, or an error may be thrown.

Unpacks the JSON string into the original value. Any packers used during packing (outside of registered packers and the Cav defaults) need to be provided here as well, or an error may be thrown. This function is a one-liner:

The server-side equivalent of the wrapWebSocket function in the client module. Returns a Response which should be returned by the handler for the socket upgrade to complete successfully.

Registers the Packers to be used as defaults in addition to the library defaults for the top-level packing functions. Falsy properties are skipped. If any packer keys conflict with the packers that are already in use, an error is thrown. Returns the input packers argument.

Wraps a regular WebSocket with packing functionality and type support.

Interfaces

Options for bundling TypeScript and JavaScript browser assets.

Cav's cookie interface. This interface provides synchronous access to cookie values. The actual signing of signed cookies needs to be asynchronous, however. In order to compensate for this, once you are done accessing and modifying the cookie, you need to call the async "flush()" in order to sync cookie updates to the response headers that were provided when the cookie was initialized.

Limits what paths/domains a cookie should be deleted for.

Extends the Deno default cookie set options to include the "signed" flag.

In Cav, there is no middleware. To fill the gap, Rpcs can leverage Ctx functions to create context-dependent data related to a request. These functions are where you'd set up databases, create session objects, etc. The value returned from this function is available as the ctx property for the various Rpc event handler functions.

Arguments available to the Ctx function of an Rpc.

Client type representing an Rpc endpoint. Uses the Rpc type definition to determine what the expected arguments and response types are.

Initializer arguments for constructing HttpErrors.

A group of functions used to recognize, pack, and unpack objects and special values that are not strings, basic numbers, booleans, or nulls into objects that are JSON compatible.

A function that parses data. If data is not shaped as expected, an error should be thrown.

An object with a ParserFunction as its "parse" property. Zod compatible.

A metadata object generated once for every request.

A ResponseInit applied to the Rpc response after resolving and packing the value to send to the client. The Headers object is always available. If the resolved value is a Response object already, the status and statusText will be ignored but the headers will still be applied.

After an Rpc matches with an incoming request, the Resolve function is responsible for resolving the request data into a response to send back to the client. The value returned from the Resolver will be packed with the top-level response() function, i.e. it undergoes packing via packBody().

Arguments available to a Resolver function.

Handler for handling errors that occur during response resolution. Meant to turn the errors into responses to send back to the client, using the same serialization process and utilties available in the resolve function. If an error is re-thrown, that error will be serialized as the response.

Arguments available to the OnError function of an Rpc.

An http.Handler constructed by an RpcFactory. Rpcs are one of two fundamental building blocks of Cav server applications, the other being Stacks. Rpcs are responsible for handling a request, and Stacks are responsible for routing a request to the appropriate Rpc. Once a Request reaches an Rpc and the Rpc's path matches the request, the Rpc is expected to handle all errors and return a Response. If the path doesn't match the Rpc's path, the special NO_MATCH error will be thrown. Uncaught errors bubble up to and are handled by the top-level Server, which will log them and respond with a 500 Response.

Initializer options when constructing Rpcs.

Options controlling how assets are found and served.

The standard http.Server type, but with a type parameter indicating the type of the handler that was passed in. The handler will usually be a Stack but could be any other type of Handler.

The standard http.ServerInit type with a type parameter indicating the type of the handler this server is serving. Additionally, the "onError" property has been omitted; errors in Cav should be handled at the Rpc level, as close as possible to where the error occurred. When an error bubbles up to the Server level, it will be logged and a 500 Response will be sent to the client.

Cav's WebSocket wrapper interface.

Initializer options to use when upgrading a request into a web socket using the upgradeWebSocket function.

An http.Handler that routes requests to Rpcs or other Handlers. Stacks are one of two fundamental building blocks of Cav server applications, the other being Rpcs. If a matching handler or Rpc throws the special NO_MATCH error, the stack continues looking for matching handlers to process the request into a response. Stacks can capture path groups while routing the request; the captured groups will become the basis for the ResolverArg's groups property inside a matching Rpc (before parsing).

A routing map used by the constructed Stack to find matching handlers to handle an incoming request.

A Response, but with an unused type parameter indicating the type of the response body.

Initializer options for a TypedResponse. Adds packers to ResponseInit.

Type Aliases

Type alias representing a Packer with any input or output type. Useful for type constraints.

Alias for an Rpc with any resolver or init types. Useful for type constraints.

Matches any given RpcInit. Useful for type constraints.

Type that matches any socket. Useful for type constraints.

Type alias that matches any Stack. Useful for type constraints.

Initializer options for the assets() utility function.

A Proxied function that wraps fetch() with a tailored process for making requests to a Cav server. Each property access on the function itself returns a new Client that extends the URL of the original Client. The periods represent path dividers and the accessed properties are path segments, like this: client("http://localhost/base").nested["pa.th"]() will result in a request to "http://localhost/base/nested/pa.th".

Uses the RpcInit type imported from the server to determine what shape the arguments should be in when making requests to a given Rpc.

A Record of Packers. Packer keys are used to tag packed values on the output JSON, which is required in order to correctly unpack the value on the other side.

An object or function responsible for parsing data or throwing errors if the data isn't shaped as expected. These can either be functions with a single data argument that return the parsed data or an object with a parse(data): unknown function property that does the same. Cav is specifically tuned to be compatible with (but not dependent on) Zod, a schema-based data parsing library. However, any parsing library can be used, as long as its parsers satisfy this Parser interface. (Let me know if more shapes should be supported in a github issue.) You can also write strongly-typed parsing functions and objects by hand if you don't want to use a third-party parsing library.

Extracts the input type of a given Parser.

Extracts the output type of a given Parser.

The ServerInit options available when using the serve() shorthand function.

A Packer's unpack() function receives the raw packed JSON value as its first argument and this registration function as the second. Functions registered with WhenDone will be run last-in-first-out (stack order) when the raw JSON has been processed into the final object instance. WhenDone functions are needed whenever the packed data is more complex than simple JSON values, for example when referential equality needs to be maintained or when the pack function returns anything that needs to be re-packed by some other packer. Referenced objects may not be fully initialized when the registered function is called, but its instance will be instantiated so that references can be fixed.