brick.ts

@brickkit/core

Services, actions, tools, resources, databases, secrets, the HTTP runtime, and the typed contract of a Brick application.

llms.txt

@brickkit/core exports 176 names: 63 functions, 8 classes, 68 interfaces, 34 types, 3 variables. It also re-exports 4 from @sinclair/typebox and 33 from drizzle-orm.

import { ACTION_ACCESS_KEY, ActionExecutionError, attachDatabase } from "@brickkit/core";

Functions

FunctionDescription
attachDatabaseAttach a defined database.
bindCompiledApplicationBuild artifact binder: consumes emitted functions, with no runtime handler code generation.
brickCreate the HTTP application: an Elysia app that serves every service's actions (and the tools that opt in with http: true) as routes, with /_health, an Ope…
buildErrorHelpersThe error helpers an action receives: one function per error code that throws an ActionExecutionError with that code and status.
buildFtsMatchQueryBuilds an FTS5 MATCH condition for a resource search term.
compileBrickApplicationStartup compiler: analyzes once, then binds live callbacks.
compileRoutePlanWork out, once at startup, everything an action's route needs to answer a request: where its input comes from (body, query, or path), the validators, the autho…
createActionHandlerAn Elysia handler for one action: compileRoutePlan and executeCompiledRoute together.
createBrickClientCreate an Eden/tRPC-style typed client for the application contract TApp.
createDatabaseCreates a database instance based on the provided configuration.
createEndpointHandlerWrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping.
createMcpHandlerStateless MCP JSON-RPC POST handler.
createMcpRegistryCollect only explicitly defined tools, without exposing ordinary actions.
createPostgresDatabaseCreates a PostgreSQL Drizzle instance using postgres-js.
createServiceProxyA typed way to call another service's actions in-process.
createSQLiteDatabaseCreates a zero-config SQLite database using Bun's native bun:sqlite engine and Drizzle ORM.
defineActionDefine an action: a typed, validated function that Brick serves over HTTP, runs in-process, and exposes to the typed client and OpenAPI.
defineDatabaseDeclare a service's database: its engine, its Drizzle tables, and how to reach it.
defineResourceDeclares a plugin host without registering actions or changing the schema.
defineResourcePluginDefine a plugin that installs onto a resource (a table and its entity) with resource.use(plugin).
defineServiceDeclare a service: a named group of actions, tools, and resources with its own database and request context.
defineServicePluginDefine a plugin that installs onto a service with service.use(plugin).
defineToolDefine a tool: an action that AI agents can call through MCP.
emitHandlerFactoryEmits framework code only.
endpointPathsOpenAPI paths fragment for declared endpoints (raw HTML included).
ensureResourceIndexesEnsures secondary indexes exist for a resource table.
ensureSQLiteFtsCreates the FTS5 sidecar table + sync triggers + backfills existing rows.
executeCompiledRouteAnswer one request for a compiled route: read the input, run the action, and return its output or the error response, with the x-trace-id and x-request-id …
generateOpenApiSpecBuild the OpenAPI 3.1 document for the services: one path per action route, with request and response schemas from the actions' TypeBox schemas, their declared…
generateSQLiteIndexDdlGenerates idempotent secondary index DDL for a Drizzle table.
generateSQLiteTableDdlGenerates an idempotent SQLite CREATE TABLE IF NOT EXISTS definition directly from a Drizzle table schema.
getActionAccessHow an action is protected: "public" when nothing checks the caller, "authorized" when an authorize does, and "scoped" when the action also limits what…
getCompiledCheckThe compiled validator for a TypeBox schema.
getGlobalRegistryThe registry every defineService adds to: it is how brick(), the OpenAPI generator, createServiceProxy, and the dashboard find services by name.
getPluginActionRouteWhere a plugin mounted an action over HTTP, for the OpenAPI generator, the compiler, and the typed client.
getPluginEndpointsThe raw HTTP endpoints plugins registered on a service, ready to mount on the application.
hoistAnchoredSchemasTypeBox expresses recursive schemas with bare $id/$ref anchors (\{ $id: "T0", ..., \{ $ref: "T0" \} \}).
isBrickAppWhether a value is an application made by brick().
isBrickServerErrorWhether an error from the typed client is a BrickServerError: the server answered with a 5xx that is not one of the contract's declared errors, and the error…
isBrickTransportErrorWhether an error from the typed client is a BrickTransportError: the request got no meaningful answer from the server (a network failure, a body that was not…
isDatabaseHandleWhether a value is a database handle made by defineDatabase.
isToolWhether a value was made with defineTool, as opposed to defineAction.
listSecretsMetadata for introspection (values never exposed — future dashboard use).
loadCompiledBrickAppBuild artifact bootstrap: bind generated handlers while evaluating the original app.
overrideSecretTest/session override for one secret (undefined clears the override).
overrideSecretsBulk overrides (test/session scoped).
referencePluginStandalone Elysia plugin serving GET <path> with the Scalar HTML page.
registerReferenceRouteMounts the Scalar reference route onto an existing app.
requestLoggingPluginElysia plugin that logs each request as METHOD path → status (elapsedms).
requireBrickAppCheck that a module's default export is an application ready to be served, for tools that load an entry file.
resetGlobalRegistryStart over with an empty global registry.
resetSecretsClear registry and overrides.
resolveEndpointDbResolve the db for an endpoint: explicit service first, else first service holding one.
resolveSecretsValidate every registered secret at boot.
scalarDocsHTMLRenders the Scalar API reference page for the given OpenAPI URL.
secretDeclare a secret.
setActionAccessRecord how an action is protected, for tools that cannot read it from the configuration: plugins such as crud enforce access inside execute, so the action …
swaggerDocsHTMLRenders the Swagger UI page.
syncSchemaExplicit SQLite development/test schema preparation helper.
toErrorResponseTurn what an action threw into the JSON body of its HTTP response, and record the failure on the active trace.
toOpenApiPath/p/:slug → /p/\{slug\} for OpenAPI.
traceRouteWrap a raw route handler so each of its requests gets a server span.
validateWithSchemaCheck a value against a schema, the way actions check their input and output.

attachDatabase

function attachDatabase<TDb>(
  service: Service<TDb, any>,
  database: DatabaseHandle<TDb>,
): TDb

Attach a defined database. Schema changes remain the caller's responsibility.

Parameters

NameTypeDescription
serviceService<TDb, any>
databaseDatabaseHandle<TDb>

Returns TDb

Source: packages/core/src/db/index.ts:93

bindCompiledApplication

function bindCompiledApplication(
  ir: BrickIR,
  services: Service<any, any>[],
  factories: readonly HandlerFactory[],
): CompiledApplication

Build artifact binder: consumes emitted functions, with no runtime handler code generation.

Parameters

NameTypeDescription
irBrickIR
servicesService<any, any>[]
factoriesreadonly HandlerFactory[]

Returns CompiledApplication

Source: packages/core/src/compiler.ts:103

brick

function brick(options: CreateServerOptions = {}): BrickApp

Create the HTTP application: an Elysia app that serves every service's actions (and the tools that opt in with http: true) as routes, with /_health, an OpenAPI document at /openapi.json, Scalar at /docs, Swagger UI at /swagger, and the shape of the services at /_brick/services.

Services come from the global registry unless services is given. The app does not listen by itself: export it from your entry file, where brick dev, brick start, and the Vite plugin load it, or call app.listen(port) in your own server bootstrap.

Parameters

NameTypeDescription
options?CreateServerOptions default {}prefix for action routes (default /api), services, title, version, and description for the OpenAPI document, docs and the paths of its pages, requestLogging, reference, endpoints, secrets, telemetry, documentation, and dashboard. See CreateServerOptions.

Returns BrickApp — The app, with definition (its services, prefix, and routes), endpoint() to add raw routes, and listEndpoints() to list them.

Throws

  • When a required secret is missing, or documentation or dashboard is invalid.

Example

import { brick } from "@brickkit/core";
import { pagesService } from "./services/pages";

export default brick({
  services: [pagesService],
  title: "Pages API",
  telemetry: true,
});

Source: packages/core/src/server.ts:115

buildErrorHelpers

function buildErrorHelpers<
  TErrors extends Record<string, ActionErrorDefinition>,
>(
  errorsDef?: TErrors,
): ErrorBuilder<TErrors>

The error helpers an action receives: one function per error code that throws an ActionExecutionError with that code and status. The standard HTTP codes (BAD_REQUEST, UNAUTHORIZED, FORBIDDEN, NOT_FOUND, CONFLICT, INTERNAL_SERVER_ERROR) are always there; the action's own errors add to them or replace one.

Parameters

NameTypeDescription
errorsDef?TErrorsThe action's errors: for each code, its message and status (default 400).

Returns ErrorBuilder<TErrors> — Helpers that take an optional message, details, and ErrorOptions, and always throw.

Source: packages/core/src/action.ts:70

buildFtsMatchQuery

function buildFtsMatchQuery(search: string): string | null

Builds an FTS5 MATCH condition for a resource search term. Returns null when the term has no usable tokens or FTS errors. Caller falls back to LIKE in that case.

Parameters

NameTypeDescription
searchstring

Returns string \| null

Source: packages/core/src/db/index.ts:342

compileBrickApplication

function compileBrickApplication(
  options: { services: Service<any, any>[]; prefix?: string; mode?: "specialized" | "generic"; },
): CompiledApplication

Startup compiler: analyzes once, then binds live callbacks.

Parameters

NameTypeDescription
options{ services: Service<any, any>[]; prefix?: string; mode?: "specialized" | "generic"; }

Returns CompiledApplication

Source: packages/core/src/compiler.ts:79

compileRoutePlan

function compileRoutePlan(
  service: Service,
  action: Action,
  routePath: string,
  method?: string,
): CompiledRoutePlan

Work out, once at startup, everything an action's route needs to answer a request: where its input comes from (body, query, or path), the validators, the authorization and execute functions, and its logger. Low level: brick() does this for every route.

Parameters

NameTypeDescription
serviceServiceThe service the action belongs to.
actionActionThe action.
routePathstringThe route's path.
method?stringThe HTTP method (POST by default).

Returns CompiledRoutePlan — The plan executeCompiledRoute runs.

Source: packages/core/src/action-handler.ts:38

createActionHandler

function createActionHandler(
  service: Service,
  action: Action,
  routePath: string,
  method?: string,
): (elysiaCtx: any) => Promise<any>

An Elysia handler for one action: compileRoutePlan and executeCompiledRoute together. Use it to mount an action on your own Elysia app; brick() does it for you.

Parameters

NameTypeDescription
serviceServiceThe service the action belongs to.
actionActionThe action.
routePathstringThe route's path.
method?stringThe HTTP method (POST by default).

Returns (elysiaCtx: any) => Promise<any> — A function from the Elysia context to the response.

Source: packages/core/src/action-handler.ts:324

createBrickClient

function createBrickClient<TApp extends Record<string, any>>(
  options: BrickClientOptions & { contract: TApp },
): BrickClient<TApp>

function createBrickClient<TApp extends Record<string, any>>(
  options: BrickClientOptions,
): BrickClient<TApp>

Create an Eden/tRPC-style typed client for the application contract TApp. TApp is a type-only parameter: import type { AppServer } keeps backend implementations out of the frontend bundle.

Parameters

NameTypeDescription
optionsBrickClientOptions & { contract: TApp }

Returns BrickClient<TApp>

Source: packages/core/src/client.ts:572

createDatabase

function createDatabase<
  TSchema extends Record<string, unknown> = Record<string, unknown>,
>(
  config: DatabaseConfig<TSchema> = {},
): BunSQLiteDatabase<TSchema> | PostgresDatabase<TSchema>

Creates a database instance based on the provided configuration. Zero-config: calling createDatabase() returns an ultra-fast Bun-native SQLite database in :memory: mode wrapped with Drizzle ORM.

Parameters

NameTypeDescription
config?DatabaseConfig<TSchema> default {}

Returns BunSQLiteDatabase<TSchema> \| PostgresDatabase<TSchema>

Source: packages/core/src/db/index.ts:70

createEndpointHandler

function createEndpointHandler(
  def: EndpointDefinition,
  services: Service<any, any>[],
): (elysiaCtx: any) => Promise<unknown>

Wrap a raw handler with trace ids, logger, db, and mesh-consistent error mapping.

Parameters

NameTypeDescription
defEndpointDefinition
servicesService<any, any>[]

Returns (elysiaCtx: any) => Promise<unknown>

Source: packages/core/src/endpoints.ts:71

createMcpHandler

function createMcpHandler(
  options: McpHandlerOptions,
): (request: Request, ctx?: Partial<ActionContext>) => Promise<Response>

Stateless MCP JSON-RPC POST handler. Wrap with the app's authentication.

Parameters

NameTypeDescription
optionsMcpHandlerOptions

Returns (request: Request, ctx?: Partial<ActionContext>) => Promise<Response>

Source: packages/core/src/mcp.ts:89

createMcpRegistry

function createMcpRegistry(options: McpRegistryOptions): McpRegistry

Collect only explicitly defined tools, without exposing ordinary actions.

Parameters

NameTypeDescription
optionsMcpRegistryOptions

Returns McpRegistry

Source: packages/core/src/mcp.ts:33

createPostgresDatabase

function createPostgresDatabase<
  TSchema extends Record<string, unknown> = Record<string, unknown>,
>(
  config: PostgresDatabaseConfig<TSchema> = {},
): PostgresDatabase<TSchema>

Creates a PostgreSQL Drizzle instance using postgres-js. Static imports (both are hard dependencies in package.json) so bundlers (Nitro/Rollup) trace and ship the driver. bun:sqlite stays lazy in sqlite.ts since it only exists under Bun.

Parameters

NameTypeDescription
config?PostgresDatabaseConfig<TSchema> default {}

Returns PostgresDatabase<TSchema>

Source: packages/core/src/db/postgres.ts:46

createServiceProxy

function createServiceProxy<T extends Record<string, any>>(
  serviceName: string,
  options: ProxyOptions = {},
): T

A typed way to call another service's actions in-process. Each property of the proxy is an action of that service: call it with the action's input, and optionally a call context.

The call runs through the target's own validation and authorization, with the target's database and context (never the caller's), and shows as an rpc span in the trace. Only in-process dispatch exists: with isMonolith: false a call throws. Use the typed client to call a service over HTTP.

Parameters

NameTypeDescription
serviceNamestringThe registered name of the service to call.
options?ProxyOptions default {}from (the calling service's name, which becomes ctx.caller in the target and cannot be spoofed), context (defaults for every call), and isMonolith.

Returns T — A proxy typed as T, usually the target's actions.

Throws

  • On a call, when the service or the action is not registered.

Example

import { createServiceProxy } from "@brickkit/core";

const pages = createServiceProxy<{ get(input: { id: string }): Promise<Page> }>(
  "pages",
  { from: "billing" },
);
const page = await pages.get({ id: "p_1" });

Source: packages/core/src/rpc.ts:31

createSQLiteDatabase

function createSQLiteDatabase<
  TSchema extends Record<string, unknown> = Record<string, unknown>,
>(
  config: SQLiteDatabaseConfig<TSchema> = {},
): BunSQLiteDatabase<TSchema>

Creates a zero-config SQLite database using Bun's native bun:sqlite engine and Drizzle ORM. Defaults to an ultra-fast in-memory database (:memory:).

Bun-only: the driver is loaded lazily so importing @brickkit/core on other runtimes (e.g. Node) stays safe until this function is actually called.

Parameters

NameTypeDescription
config?SQLiteDatabaseConfig<TSchema> default {}

Returns BunSQLiteDatabase<TSchema>

Source: packages/core/src/db/sqlite.ts:53

defineAction

function defineAction<
  TInputSchema extends TSchema | undefined = undefined,
  TOutputSchema extends TSchema | undefined = undefined,
  TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>,
  TContext extends ActionContext = ActionContext,
>(
  config: ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>,
): Action<TInputSchema, TOutputSchema, TErrors, TContext>

function defineAction<
  TInputSchema extends TSchema | undefined = undefined,
  TOutputSchema extends TSchema | undefined = undefined,
  TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>,
  TContext extends ActionContext = ActionContext,
>(
  config: ActionConfigWithoutAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>,
): Action<TInputSchema, TOutputSchema, TErrors, TContext>

Define an action: a typed, validated function that Brick serves over HTTP, runs in-process, and exposes to the typed client and OpenAPI.

A call runs in order: the input is validated against input (an invalid one is a VALIDATION_FAILED error, HTTP 400); authorize runs, if there is one; execute runs; and its result is validated against output (a mismatch is a server error, HTTP 500). Throw error.CODE(...) from execute for a declared failure or a standard one such as error.NOT_FOUND(). Any other thrown value becomes INTERNAL_SERVER_ERROR (500), with the cause kept out of the response and in the log.

authorize returns false to refuse: the call fails with UNAUTHORIZED (401) when there is no ctx.user, and FORBIDDEN (403) when there is one. Where it is given, execute can rely on what it checked.

Parameters

NameTypeDescription
configActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>name, execute, and optionally description, input and output (TypeBox schemas), errors, authorize, method and path to change the route (POST by default), tags, and emits.

Returns Action<TInputSchema, TOutputSchema, TErrors, TContext> — The action. Register it with service.action(action); call it directly with action.run(input, ctx).

Example

import { defineAction, t } from "@brickkit/core";

export const getPage = defineAction({
  name: "get",
  method: "GET",
  input: t.Object({ id: t.String() }),
  output: t.Object({ id: t.String(), title: t.String() }),
  errors: { PAGE_GONE: { message: "That page was removed", status: 410 } },
  authorize: ({ user }) => user != null,
  execute: async ({ input, ctx, error }) => {
    const page = await findPage(ctx.db, input.id);
    if (!page) throw error.NOT_FOUND("No such page");
    return page;
  },
});

Source: packages/core/src/action.ts:144

defineDatabase

function defineDatabase<
  TSchema extends Record<string, unknown> = Record<string, unknown>,
>(
  options?: SQLiteDefinition<TSchema>,
): DatabaseHandle<BunSQLiteDatabase<TSchema>, TSchema>

function defineDatabase<
  TSchema extends Record<string, unknown> = Record<string, unknown>,
>(
  options: PostgresDefinition<TSchema>,
): DatabaseHandle<PostgresJsDatabase<TSchema> & { $client: Sql }, TSchema>

Declare a service's database: its engine, its Drizzle tables, and how to reach it. Nothing connects until the handle is used (getDb()), so defining one has no side effects.

SQLite is the default and needs no options. Pass engine: "postgres" with a url for Postgres. Options that belong to the other engine (such as url for SQLite, or path for Postgres) are refused.

Parameters

NameTypeDescription
options?SQLiteDefinition<TSchema>engine ("sqlite" or "postgres"), tables, an optional name, and the engine's connection settings.

Returns DatabaseHandle<BunSQLiteDatabase<TSchema>, TSchema> — A handle to give to defineService({ database }). getDb() returns the Drizzle database.

Throws

  • When the engine is unsupported, or an option does not suit the engine.

Example

import { defineDatabase } from "@brickkit/core";
import { sqliteTable, text } from "drizzle-orm/sqlite-core";

const pages = sqliteTable("pages", {
  id: text("id").primaryKey(),
  title: text("title").notNull(),
});

export const database = defineDatabase({ tables: { pages } });

Source: packages/core/src/db/define.ts:109

defineResource

function defineResource<
  TTable = any,
  TCtx extends ActionContext = ActionContext,
  const O extends ResourceTypeOptions = ResourceTypeOptions,
>(
  service: Service<any, any>,
  config: ResourceConfig<TTable, TCtx> & O,
): Resource<TTable, TCtx, ResourceIdentity<TTable, O>>

Declares a plugin host without registering actions or changing the schema.

Parameters

NameTypeDescription
serviceService<any, any>
configResourceConfig<TTable, TCtx> & O

Returns Resource<TTable, TCtx, ResourceIdentity<TTable, O>>

Source: packages/core/src/resource.ts:13

defineResourcePlugin

function defineResourcePlugin<
  S extends Service<any, any> = Service<any, any>,
  R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>,
  A extends object = object,
>(
  definition: Omit<ResourcePlugin<S, R, A>, typeof pluginKind> & { setup: (context: ResourcePluginContext<S, R>,) => A & (A extends PromiseLike<unknown> ? never …,
): ResourcePlugin<S, R, A>

Define a plugin that installs onto a resource (a table and its entity) with resource.use(plugin). Its setup receives the service, the resource, and a routes registrar, whose routes are scoped under the resource's name, and returns the typed API that resource.use hands back. crud is built this way.

Parameters

NameTypeDescription
definitionOmit<ResourcePlugin<S, R, A>, typeof pluginKind> & { setup: (context: ResourcePluginContext<S, R>,) => A & (A extends PromiseLike<unknown> ? never : unknown); }A unique name, optional routes controls, and setup, which must be synchronous.

Returns ResourcePlugin<S, R, A> — The plugin descriptor, frozen.

Throws

  • When the name is empty or has surrounding whitespace.

Source: packages/core/src/plugin.ts:191

defineService

function defineService<
  TDb = BunSQLiteDatabase<Record<string, unknown>>,
  TServiceContext extends Record<string, any> = Record<string, any>,
>(
  name: string,
  options?: ServiceOptions<TServiceContext, TDb>,
): Service<TDb, TServiceContext>

Declare a service: a named group of actions, tools, and resources with its own database and request context. It is registered globally, so brick(), the OpenAPI generator, and createServiceProxy find it by name.

Add actions with service.action(...), tools with service.tool(...), resources with service.resource(...), and plugins with service.use(...).

Parameters

NameTypeDescription
namestringUnique name. It is the service's segment of every action route (/api/<name>/<action>) and appears in OpenAPI and the dashboard. Defining a second service with the same name replaces the first and logs a warning.
options?ServiceOptions<TServiceContext, TDb>database (a handle from defineDatabase), context (adds fields such as the signed-in user to every action's ctx), and auth, rateLimit, cache, resilience, telemetry, and lifecycle.

Returns Service<TDb, TServiceContext> — The service.

Example

import { defineDatabase, defineService, t } from "@brickkit/core";

const database = defineDatabase({ tables: { pages } });

export const pagesService = defineService("pages", {
  database,
  // Added to `ctx` in every action of this service.
  context: async ({ request }) => ({ user: await readUser(request) }),
});

pagesService.action({
  name: "list",
  input: t.Object({ limit: t.Optional(t.Number()) }),
  output: t.Array(t.Object({ id: t.String(), title: t.String() })),
  execute: ({ input, ctx }) =>
    ctx.db.select().from(pages).limit(input.limit ?? 20),
});

Source: packages/core/src/service.ts:450

defineServicePlugin

function defineServicePlugin<
  S extends Service<any, any> = Service<any, any>,
  A = unknown,
>(
  definition: Omit<ServicePlugin<S, A>, typeof pluginKind> & { setup: (context: ServicePluginContext<S>,) => A & (A extends PromiseLike<unknown> ? never : unknow…,
): ServicePlugin<S, A>

Define a plugin that installs onto a service with service.use(plugin). Its setup receives the service and a routes registrar for adding actions and raw HTTP endpoints, and returns the typed API that service.use hands back.

Parameters

NameTypeDescription
definitionOmit<ServicePlugin<S, A>, typeof pluginKind> & { setup: (context: ServicePluginContext<S>,) => A & (A extends PromiseLike<unknown> ? never : unknown); }A unique name, optional routes controls that let the user move or switch off the plugin's routes, and setup, which must be synchronous.

Returns ServicePlugin<S, A> — The plugin descriptor, frozen.

Throws

  • When the name is empty or has surrounding whitespace.

Example

import { defineServicePlugin, t } from "@brickkit/core";

export const greeting = (salutation = "Hello") =>
  defineServicePlugin({
    name: "example/greeting",
    setup({ routes }) {
      const hello = routes.action({
        name: "hello",
        input: t.Object({ name: t.String() }),
        output: t.String(),
        execute: ({ input }) => `${salutation}, ${input.name}!`,
      });
      return { hello };
    },
  });

const api = greeterService.use(greeting("Welcome"));
await api.hello({ input: { name: "Ada" } });

Source: packages/core/src/plugin.ts:163

defineTool

function defineTool<
  TInputSchema extends TSchema | undefined = undefined,
  TOutputSchema extends TSchema | undefined = undefined,
  TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>,
  TContext extends ActionContext = ActionContext,
>(
  config: ToolConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>,
): Tool<TInputSchema, TOutputSchema, TErrors, TContext>

function defineTool<
  TInputSchema extends TSchema | undefined = undefined,
  TOutputSchema extends TSchema | undefined = undefined,
  TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>,
  TContext extends ActionContext = ActionContext,
>(
  config: ToolConfigWithoutAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>,
): Tool<TInputSchema, TOutputSchema, TErrors, TContext>

Define a tool: an action that AI agents can call through MCP. It takes the same configuration as defineAction (validation, authorize, errors), plus title, annotations (the MCP hints about what the tool does), and http to also serve it over HTTP and in OpenAPI (off by default).

Parameters

NameTypeDescription
configToolConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>An action configuration and tool options. input must be an object schema, since MCP passes arguments by name.

Returns Tool<TInputSchema, TOutputSchema, TErrors, TContext> — The tool, which is also an action. Register it with service.tool(tool).

Throws

  • When input is not an object schema.

Example

import { defineTool, t } from "@brickkit/core";

export const echoTool = defineTool({
  name: "echo",
  title: "Echo a message",
  description: "Returns the message it is given.",
  input: t.Object({ message: t.String() }),
  output: t.String(),
  execute: ({ input }) => `Echo: ${input.message}`,
});

Source: packages/core/src/tool.ts:33

emitHandlerFactory

function emitHandlerFactory(route: RouteIR): string

Emits framework code only. User callbacks remain closures bound separately.

Parameters

NameTypeDescription
routeRouteIR

Returns string

Source: packages/core/src/compiler/emit.ts:4

endpointPaths

function endpointPaths(defs: EndpointDefinition[]): Record<string, any>

OpenAPI paths fragment for declared endpoints (raw HTML included).

Parameters

NameTypeDescription
defsEndpointDefinition[]

Returns Record<string, any>

Source: packages/core/src/endpoints.ts:152

ensureResourceIndexes

function ensureResourceIndexes(
  db: any,
  table: any,
  opts: { ownerField?: string; sortFields?: string[]; searchFields?: string[]; } = {},
): void

Ensures secondary indexes exist for a resource table. SQLite: B-tree indexes for owner scope + sort + composite hot path. Postgres: same B-trees plus pg_trgm GIN indexes for substring search. Best-effort: failures warn and continue (e.g. read-only replicas).

Parameters

NameTypeDescription
dbany
tableany
opts?{ ownerField?: string; sortFields?: string[]; searchFields?: string[]; } default {}

Source: packages/core/src/db/index.ts:204

ensureSQLiteFts

function ensureSQLiteFts(db: any, table: any, searchCols: string[]): void

Creates the FTS5 sidecar table + sync triggers + backfills existing rows. Idempotent; safe to call on every resource registration. No-op on Postgres (relies on pg_trgm instead) and when searchCols is empty.

Parameters

NameTypeDescription
dbany
tableany
searchColsstring[]

Source: packages/core/src/db/index.ts:278

executeCompiledRoute

function executeCompiledRoute(
  plan: CompiledRoutePlan,
  elysiaCtx: any,
): Promise<any>

Answer one request for a compiled route: read the input, run the action, and return its output or the error response, with the x-trace-id and x-request-id headers set. Low level: brick() mounts this for every route.

Parameters

NameTypeDescription
planCompiledRoutePlanFrom compileRoutePlan.
elysiaCtxanyThe Elysia request context: params, body, query, headers, request, and set.

Returns Promise<any> — The action's output, or an error envelope with the status set on set.

Source: packages/core/src/action-handler.ts:149

generateOpenApiSpec

function generateOpenApiSpec(
  options: OpenApiGeneratorOptions = {},
): Record<string, any>

Build the OpenAPI 3.1 document for the services: one path per action route, with request and response schemas from the actions' TypeBox schemas, their declared errors, tags by service, and a bearer security scheme where any action needs authorization.

brick() calls this for /openapi.json; call it yourself to write the document to a file or feed another tool.

Parameters

NameTypeDescription
options?OpenApiGeneratorOptions default {}title, version, and description for the info block, prefix (default /api), and the services or registry to describe (the global registry by default).

Returns Record<string, any> — The document as a plain object.

Source: packages/core/src/openapi.ts:114

generateSQLiteIndexDdl

function generateSQLiteIndexDdl(
  table: any,
  opts: { ownerField?: string; sortFields?: string[] } = {},
): string[]

Generates idempotent secondary index DDL for a Drizzle table. Covers owner scoping, sort columns, and exact-match filters. UNIQUE columns already carry an implicit index — skipped here. FTS/trigram indexes are handled separately by the search layer.

Parameters

NameTypeDescription
tableany
opts?{ ownerField?: string; sortFields?: string[] } default {}

Returns string[]

Source: packages/core/src/db/index.ts:138

generateSQLiteTableDdl

function generateSQLiteTableDdl(table: any): string

Generates an idempotent SQLite CREATE TABLE IF NOT EXISTS definition directly from a Drizzle table schema.

Parameters

NameTypeDescription
tableany

Returns string

Source: packages/core/src/db/index.ts:105

getActionAccess

function getActionAccess(action: Action | object): ActionAccessInfo

How an action is protected: "public" when nothing checks the caller, "authorized" when an authorize does, and "scoped" when the action also limits what rows the caller can reach. It reads what a plugin recorded with setActionAccess, else the action's own authorize, and keeps the policy consistent with the flags.

Parameters

NameTypeDescription
actionAction | objectAn action, or any object a plugin described.

Returns ActionAccessInfo — hasAuthorize, hasScope, and policy.

Source: packages/core/src/access.ts:48

getCompiledCheck

function getCompiledCheck<T extends TSchema>(schema: T): TypeCheck<T>

The compiled validator for a TypeBox schema. Compiling is slow and checking is fast, so each schema is compiled once and kept for as long as the schema object lives.

Parameters

NameTypeDescription
schemaTA TypeBox schema.

Returns TypeCheck<T> — Its TypeCheck, with Check(value) and Errors(value).

Source: packages/core/src/typebox.ts:18

getGlobalRegistry

function getGlobalRegistry(): ServiceRegistry

The registry every defineService adds to: it is how brick(), the OpenAPI generator, createServiceProxy, and the dashboard find services by name.

Returns ServiceRegistry — The current global registry.

Source: packages/core/src/registry.ts:98

getPluginActionRoute

function getPluginActionRoute(
  action: Action<any, any, any, any>,
  prefix = "/api",
): false | { path: string; method: PluginRouteMethod; clientPath: string[] | undefined; plugin: string; resource: string | undefined; } | undefined

Where a plugin mounted an action over HTTP, for the OpenAPI generator, the compiler, and the typed client.

Parameters

NameTypeDescription
actionAction<any, any, any, any>An action.
prefix?string default "/api"The application's route prefix (default /api).

Returns false \| { path: string; method: PluginRouteMethod; clientPath: string[] \| undefined; plugin: string; resource: string \| undefined; } \| undefined — undefined when no plugin bound the action (it uses its own route), false when the plugin's route was switched off, otherwise the route's path and method, the clientPath the typed client uses, and the owning plugin and resource.

Source: packages/core/src/plugin.ts:323

getPluginEndpoints

function getPluginEndpoints(
  service: Service<any, any>,
  prefix = "/api",
): { path: string; method: PluginRouteMethod; service: Service<any, any>; summary: string | undefined; description: string | undefined; tags: string[] | undefined…

The raw HTTP endpoints plugins registered on a service, ready to mount on the application. Each handler resolves the service's context before it runs.

Parameters

NameTypeDescription
serviceService<any, any>The service plugins were installed on.
prefix?string default "/api"The application's route prefix (default /api).

Returns { path: string; method: PluginRouteMethod; service: Service<any, any>; summary: string \| undefined; description: string \| undefined; tags: string[] \| undefined; handler: (context: Omit<PluginEndpointContext, "ctx">) => … — The enabled endpoints: path, method, handler, and the summary, description, and tags for OpenAPI.

Source: packages/core/src/plugin.ts:350

hoistAnchoredSchemas

function hoistAnchoredSchemas(spec: Record<string, any>): string[]

TypeBox expresses recursive schemas with bare $id/$ref anchors ({ $id: "T0", ..., { $ref: "T0" } }). OpenAPI interprets a bare $ref as an external file reference, so downstream tooling tries to load a file named T0 and fails. Hoist every anchored subschema into #/components/schemas/ and rewrite the refs to local pointers. First definition wins when one $id is declared twice.

Parameters

NameTypeDescription
specRecord<string, any>

Returns string[]

Source: packages/core/src/openapi.ts:47

isBrickApp

function isBrickApp(app: unknown): app is BrickApp

Whether a value is an application made by brick(). It checks for the methods and definition a BrickApp has, so it also recognizes one built by another copy of the package.

Parameters

NameTypeDescription
appunknownAnything, such as the default export of an entry file.

Returns app is BrickApp — true for a BrickApp, narrowing its type.

Source: packages/core/src/app-entry.ts:11

isBrickServerError

function isBrickServerError(err: unknown): err is BrickServerError

Whether an error from the typed client is a BrickServerError: the server answered with a 5xx that is not one of the contract's declared errors, and the error carries its status, url, and body.

Parameters

NameTypeDescription
errunknownWhat a client call threw.

Returns err is BrickServerError — true for a server error, narrowing its type.

Source: packages/core/src/client.ts:187

isBrickTransportError

function isBrickTransportError(err: unknown): err is BrickTransportError

Whether an error from the typed client is a BrickTransportError: the request got no meaningful answer from the server (a network failure, a body that was not JSON, or a 4xx outside the declared contract).

Parameters

NameTypeDescription
errunknownWhat a client call threw.

Returns err is BrickTransportError — true for a transport error, narrowing its type.

Source: packages/core/src/client.ts:173

isDatabaseHandle

function isDatabaseHandle(value: unknown): value is DatabaseHandle<unknown>

Whether a value is a database handle made by defineDatabase.

Parameters

NameTypeDescription
valueunknownAnything.

Returns value is DatabaseHandle<unknown> — true for a handle, narrowing its type.

Source: packages/core/src/db/define.ts:73

isTool

function isTool(value: unknown): value is Tool<any, any, any, any>

Whether a value was made with defineTool, as opposed to defineAction.

Parameters

NameTypeDescription
valueunknownAnything.

Returns value is Tool<any, any, any, any> — true for a tool, narrowing its type.

Source: packages/core/src/tool.ts:82

listSecrets

function listSecrets(
  opts: { source?: SecretSource } = {},
): Array<{ name: string; hasDefault: boolean; isSet: boolean }>

Metadata for introspection (values never exposed — future dashboard use).

Parameters

NameTypeDescription
opts?{ source?: SecretSource } default {}

Returns Array<{ name: string; hasDefault: boolean; isSet: boolean }>

Source: packages/core/src/secrets.ts:196

loadCompiledBrickApp

function loadCompiledBrickApp(
  load: () => Promise<{ default: unknown }>,
  ir: BrickIR,
  bind: ApplicationBinder,
): Promise<BrickApp>

Build artifact bootstrap: bind generated handlers while evaluating the original app.

Parameters

NameTypeDescription
load() => Promise<{ default: unknown }>
irBrickIR
bindApplicationBinder

Returns Promise<BrickApp>

Source: packages/core/src/compiler.ts:28

overrideSecret

function overrideSecret(name: string, value: string | undefined): void

Test/session override for one secret (undefined clears the override).

Parameters

NameTypeDescription
namestring
valuestring | undefined

Source: packages/core/src/secrets.ts:208

overrideSecrets

function overrideSecrets(values: Record<string, string | undefined>): void

Bulk overrides (test/session scoped).

Parameters

NameTypeDescription
valuesRecord<string, string | undefined>

Source: packages/core/src/secrets.ts:213

referencePlugin

function referencePlugin(opts: ReferenceOptions = {}): Elysia

Standalone Elysia plugin serving GET <path> with the Scalar HTML page.

Parameters

NameTypeDescription
opts?ReferenceOptions default {}

Returns Elysia

Source: packages/core/src/docs.ts:72

registerReferenceRoute

function registerReferenceRoute(
  app: Elysia,
  opts: ReferenceOptions = {},
): Elysia

Mounts the Scalar reference route onto an existing app.

Parameters

NameTypeDescription
appElysia
opts?ReferenceOptions default {}

Returns Elysia

Source: packages/core/src/docs.ts:85

requestLoggingPlugin

function requestLoggingPlugin(opts: RequestLoggingOptions = {}): Elysia

Elysia plugin that logs each request as METHOD path → status (elapsedms). Timing is tracked per-Request via a WeakMap. The onError hook only logs and returns undefined so existing error mapping is preserved. Logging only — no CORS headers are set here.

Hooks are registered with the "global" scope so they propagate to the parent app when mounted via app.use(...) — Elysia scopes plain instance hooks to the plugin's own routes. Timing is captured in beforeHandle because request hooks are not propagated from a used instance. Unmatched routes (no beforeHandle) fall back to Date.now().

Parameters

NameTypeDescription
opts?RequestLoggingOptions default {}

Returns Elysia

Source: packages/core/src/request-logger.ts:41

requireBrickApp

function requireBrickApp(app: unknown): BrickApp

Check that a module's default export is an application ready to be served, for tools that load an entry file.

Parameters

NameTypeDescription
appunknownThe default export of an entry file.

Returns BrickApp — The app.

Throws

  • When it is not a BrickApp, or it already called .listen(): the entry must only build the app, and leave listening to the server bootstrap.

Source: packages/core/src/app-entry.ts:39

resetGlobalRegistry

function resetGlobalRegistry(): void

Start over with an empty global registry. For tests, which define the same services again in each case; an application never needs it.

Source: packages/core/src/registry.ts:106

resetSecrets

function resetSecrets(): void

Clear registry and overrides. Test-only.

Source: packages/core/src/secrets.ts:222

resolveEndpointDb

function resolveEndpointDb(
  service: Service<any, any> | string | undefined,
  services: Service<any, any>[],
): any

Resolve the db for an endpoint: explicit service first, else first service holding one.

Parameters

NameTypeDescription
serviceService<any, any> | string | undefined
servicesService<any, any>[]

Returns any

Source: packages/core/src/endpoints.ts:52

resolveSecrets

function resolveSecrets(
  opts: { source?: SecretSource } = {},
): Record<string, unknown>

Validate every registered secret at boot. Throws a single error listing all missing required secrets. Returns the resolved values.

Parameters

NameTypeDescription
opts?{ source?: SecretSource } default {}

Returns Record<string, unknown>

Source: packages/core/src/secrets.ts:176

scalarDocsHTML

function scalarDocsHTML(specUrl: string, title: string): string

Renders the Scalar API reference page for the given OpenAPI URL.

Parameters

NameTypeDescription
specUrlstring
titlestring

Returns string

Source: packages/core/src/docs.ts:48

secret

function secret(name: string, options: SecretOptions = {}): SecretRef<string>

Declare a secret. Idempotent: re-declaring the same name returns the original ref (first declaration wins) so module re-evaluation is safe.

Parameters

NameTypeDescription
namestring
options?SecretOptions default {}

Returns SecretRef<string>

Source: packages/core/src/secrets.ts:161

setActionAccess

function setActionAccess(action: object, info: ActionAccessInfo): void

Record how an action is protected, for tools that cannot read it from the configuration: plugins such as crud enforce access inside execute, so the action has no authorize to find. Introspection, OpenAPI, and the dashboard read what is recorded here.

Parameters

NameTypeDescription
actionobjectThe action to describe.
infoActionAccessInfoWhether it checks authorization and whether it scopes queries, and the resulting policy.

Source: packages/core/src/access.ts:30

swaggerDocsHTML

function swaggerDocsHTML(specUrl: string, title: string): string

Renders the Swagger UI page.

Parameters

NameTypeDescription
specUrlstring
titlestring

Returns string

Source: packages/core/src/docs.ts:93

syncSchema

function syncSchema(
  tablesOrService: Map<string, any> | any[] | Record<string, any> | Service,
  dbInstance?: any,
): Promise<void> | void

Explicit SQLite development/test schema preparation helper. Never called by services, resources, auth, or server startup. Not a migration runner; PostgreSQL schema management is caller-owned.

Parameters

NameTypeDescription
tablesOrServiceMap<string, any> | any[] | Record<string, any> | Service
dbInstance?any

Returns Promise<void> \| void

Source: packages/core/src/db/index.ts:365

toErrorResponse

function toErrorResponse(err: unknown, context: ErrorContext): ErrorEnvelope

Turn what an action threw into the JSON body of its HTTP response, and record the failure on the active trace. Declared failures and validation errors keep their code, status, and details; anything else is logged and answered as a generic INTERNAL_SERVER_ERROR (500) so internals are never exposed.

Parameters

NameTypeDescription
errunknownWhatever was thrown.
contextErrorContextA logger with error(), and the requestId to put in the body.

Returns ErrorEnvelope — The envelope: name, code, message, status, requestId, and details or errors when there are any.

Source: packages/core/src/error-response.ts:46

toOpenApiPath

function toOpenApiPath(elysiaPath: string): string

/p/:slug → /p/{slug} for OpenAPI.

Parameters

NameTypeDescription
elysiaPathstring

Returns string

Source: packages/core/src/endpoints.ts:142

traceRoute

function traceRoute<T>(
  route: string,
  handler: (context: RawRouteContext) => T,
): (context: RawRouteContext) => T

Wrap a raw route handler so each of its requests gets a server span. Use it for routes registered directly on the app, outside actions and endpoints, such as auth or webhook routes. Spans are recorded whenever a tracer provider is registered; brick({ telemetry }) does not apply to these routes.

The wrapper forwards only the fields listed in RawRouteContext. Elysia decides what to parse from the handler's destructuring, and forwarding the whole context would parse the body and leave request.json() with nothing.

Parameters

NameTypeDescription
routestring
handler(context: RawRouteContext) => T

Returns (context: RawRouteContext) => T

Source: packages/core/src/telemetry.ts:75

validateWithSchema

function validateWithSchema<T extends TSchema>(
  schema: T | undefined,
  value: unknown,
): | { success: true; data: Static<T> } | { success: false; errors: ValidationErrorItem[] }

Check a value against a schema, the way actions check their input and output.

Parameters

NameTypeDescription
schemaT | undefinedA TypeBox schema, or undefined to accept anything.
valueunknownThe value to check.

Returns \| { success: true; data: Static<T> } \| { success: false; errors: ValidationErrorItem[] } — { success: true, data }, or { success: false, errors } with a path, message, type, and the offending value for each problem.

Source: packages/core/src/typebox.ts:35

Classes

ActionExecutionError

class ActionExecutionError extends Error

Constructor

NameTypeDescription
constructornew ( code: string, message: string, status = 400, details?: unknown, options?: ErrorOptions, )

Properties

NameTypeDescription
readonly codestring
readonly statusnumber
readonly details?unknown

Methods

NameTypeDescription
toJSONtoJSON(): { name: string; code: string; message: string; status: number; details: unknown; }

Source: packages/core/src/types.ts:101

BrickServerError

class BrickServerError extends Error

The server answered 5xx without a declared code / ValidationError shape, i.e. an unexpected failure rather than a modelled domain error.

Constructor

NameTypeDescription
constructornew (message: string, opts: { status: number; url: string; body: unknown })

Properties

NameTypeDescription
readonly kind"server"
readonly statusnumber
readonly urlstring
readonly bodyunknown

Source: packages/core/src/client.ts:147

BrickTransportError

class BrickTransportError extends Error

The request never received a meaningful server answer: DNS / connection failure, a malformed body, or a 4xx response outside the declared contract (no code and no ValidationError shape).

Constructor

NameTypeDescription
constructornew ( message: string, opts: { status?: number; url: string; body?: unknown; cause?: unknown }, )

Properties

NameTypeDescription
readonly kind"transport"
readonly status?number
readonly urlstring
readonly body?unknown
readonly cause?unknown

Source: packages/core/src/client.ts:123

SecretRef

class SecretRef<T = string>

Constructor

NameTypeDescription
constructornew (name: string, options: SecretOptions = {})

Properties

NameTypeDescription
readonly namestring
readonly optionsSecretOptions
hasDefaultbooleanTrue when a default was declared (i.e. the secret is optional).

Methods

NameTypeDescription
defaultdefault(value: string): thisFallback used when the source has no value. Makes the secret optional.
transformtransform<U>(fn: (raw: string) => U): SecretRef<U>Convert the raw string (e.g. Number, JSON.parse, v === "true"). Runs before validators; a throwing transform fails resolution.
validatevalidate(fn: SecretValidator<T>): thisRun a custom check on the (transformed) value at every resolution.
urlurl(this: SecretRef<string>): SecretRef<string>Shorthand validator: value must parse as a URL. String refs only.
valuevalue(source: SecretSource = envSource): T | undefinedResolved (transformed, validated) value or undefined. Never throws on missing.
requirerequire(source: SecretSource = envSource): TResolved value, or throws naming the missing/invalid secret.
isSetisSet(source: SecretSource = envSource): booleanTrue when a value would resolve (override, source, or default).

Source: packages/core/src/secrets.ts:42

ServiceImpl

class ServiceImpl<TDb = BunSQLiteDatabase<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>> implements Service<TDb, TServiceContext>

Constructor

NameTypeDescription
constructornew (name: string, options: ServiceOptions<TServiceContext, TDb> = {})

Properties

NameTypeDescription
readonly namestring
readonly optionsServiceOptions<TServiceContext, TDb>
readonly actionsMap<string, Action<any, any, any, any>>
readonly toolsMap<string, Tool<any, any, any, any>>
readonly tablesMap<string, any>
readonly resourcesMap<string, Resource<any, BaseContext<TDb> & TServiceContext, {}>>
readonly preparationsMap<string, PreparationContribution>
dbTDb | undefined
isBuiltboolean
resource<TTable = any, const TOptions extends ResourceTypeOptions = ResourceTypeOptions>(config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext> & TOptions & Record<Exclude<keyof TOptions, keyof ResourceConfig>, neve…

Methods

NameTypeDescription
useuse<A>(plugin: ServicePlugin<this, A>): A
buildbuild(): thisCloses declarations after plugins have registered their actions and preparations.
contributePreparationcontributePreparation(contribution: PreparationContribution): void
listPreparationslistPreparations(): PreparationContribution[]
prepareContributionsprepareContributions(): void
registerTableregisterTable(table: any): this
getResourcegetResource( name: string, ): Resource<any, BaseContext<TDb> & TServiceContext> | undefined
listResourceslistResources(): Resource<any, BaseContext<TDb> & TServiceContext>[]
actionaction(actionOrConfig: any): any
tooltool(toolOrConfig: any): any
getToolgetTool(name: string): Tool<any, any, any, any> | undefined
listToolslistTools(): Tool<any, any, any, any>[]
getActiongetAction(name: string): Action<any, any, any, any> | undefined
listActionslistActions(): Action<any, any, any, any>[]
getDbgetDb(): TDb | undefined
setDbsetDb(database: DatabaseHandle<TDb>): void
resolveContextresolveContext( callCtx?: Partial<BaseContext<TDb> & TServiceContext>, ): Promise<BaseContext<TDb> & TServiceContext>Resolves the complete service execution context once per incoming request. Merges framework BaseContext with the service's custom context hook. Always rebuilds context for this service to prevent caller context from overriding.
introspectintrospect(): ServiceSchema

Source: packages/core/src/service.ts:46

ServiceRegistry

class ServiceRegistry

Properties

NameTypeDescription
revisionnumberDefinition revision for invalidating serialized architecture snapshots.

Methods

NameTypeDescription
touchtouch(): void
setApplicationRoutessetApplicationRoutes(application: ArchitectureApplication): voidRemember the actual registered routes for subsequent registry exports.
registerregister(service: Service): void
getget(name: string): Service | undefined
hashas(name: string): boolean
listlist(): Service[]
clearclear(): void
exportArchitectureexportArchitecture(application?: ArchitectureApplication): ArchitectureSchema

Source: packages/core/src/registry.ts:9

UnknownToolError

class UnknownToolError extends Error

Constructor

NameTypeDescription
constructornew (name: string)

Source: packages/core/src/mcp.ts:25

ValidationError

class ValidationError extends Error

Constructor

NameTypeDescription
constructornew (message: string, errors: ValidationErrorItem[] = [], status = 400)

Properties

NameTypeDescription
readonly code"VALIDATION_FAILED"
readonly statusnumber
readonly errorsValidationErrorItem[]

Methods

NameTypeDescription
toJSONtoJSON(): { name: string; code: string; message: string; status: number; errors: ValidationErrorItem[]; }

Source: packages/core/src/types.ts:74

Interfaces

Action

interface Action<TInputSchema extends TSchema | undefined = any, TOutputSchema extends TSchema | undefined = any, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext>

Properties

NameTypeDescription
(call)(params: { input?: TInputSchema extends TSchema ? Static<TInputSchema> : any; ctx?: Partial<TContext>; }): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>
namestring
serviceName?string
plugin?stringOwning plugin descriptor name for plugin actions (e.g. @brickkit/crud).
resource?stringOwning resource name for resource-plugin actions (e.g. page).
configActionConfig<TInputSchema, TOutputSchema, TErrors, TContext>
outputValidationSchema?TSchemaOptional runtime-only output schema. When present, validateOutput and HTTP output checking validate against it instead of config.output, while config.output remains the published contract (client types, OpenAPI). Lets projected/subset responses validate at runtime without leaking optionality into the generated contract.
errorHelpers?ErrorBuilder<TErrors>

Methods

NameTypeDescription
runrun( input?: TInputSchema extends TSchema ? Static<TInputSchema> : any, ctx?: Partial<TContext>, ): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>
executeexecute( params: { input?: TInputSchema extends TSchema ? Static<TInputSchema> : any; ctx?: Partial<TContext>; }, ): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>
executeResolved?executeResolved( params: { input?: TInputSchema extends TSchema ? Static<TInputSchema> : any; ctx: TContext; }, ): Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any>
validateInputvalidateInput( input: unknown, ): | { success: true; data: any } | { success: false; errors: ValidationErrorItem[] }
validateOutputvalidateOutput( output: unknown, ): | { success: true; data: any } | { success: false; errors: ValidationErrorItem[] }

Source: packages/core/src/types.ts:261

ActionAccessInfo

interface ActionAccessInfo

Properties

NameTypeDescription
hasAuthorizeboolean
hasScopeboolean
policyActionAccessPolicy

Source: packages/core/src/access.ts:4

ActionConfigWithAuthorize

interface ActionConfigWithAuthorize<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors>

Properties

NameTypeDescription
authorize(params: { user?: TContext extends { user: infer U } ? U : any; input: TInputSchema extends TSchema ? Static<TInputSchema> : any; ctx: TContext; }) => boolean | Promise<boolean>
execute(params: { input: TInputSchema extends TSchema ? Static<TInputSchema> : any; ctx: NarrowAuthorizedContext<TContext>; error: ErrorBuilder<TErrors>; }) => | Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : …

Source: packages/core/src/types.ts:202

ActionConfigWithoutAuthorize

interface ActionConfigWithoutAuthorize<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, TContext extends ActionContext = ActionContext> extends BaseActionConfig<TInputSchema, TOutputSchema, TErrors>

Properties

NameTypeDescription
authorize?undefined
execute(params: { input: TInputSchema extends TSchema ? Static<TInputSchema> : any; ctx: TContext; error: ErrorBuilder<TErrors>; }) => | Promise<TOutputSchema extends TSchema ? Static<TOutputSchema> : any> | (TOutputSchema ext…

Source: packages/core/src/types.ts:225

ActionErrorDefinition

interface ActionErrorDefinition

Properties

NameTypeDescription
status?number
messagestring

Source: packages/core/src/types.ts:62

ActionSchema

interface ActionSchema

Properties

NameTypeDescription
namestring
method?"GET" | "POST" | "PUT" | "PATCH" | "DELETE"Present only when this action has a registered HTTP route.
path?string
serviceName?string
plugin?stringOwning plugin descriptor name for plugin actions (e.g. @brickkit/crud).
resource?stringOwning resource name for resource-plugin actions (e.g. page).
description?string
inputSchema?unknown
outputSchema?unknown
hasAuthorizeboolean
hasScope?boolean
accessPolicy?ActionAccessPolicy
errors?Record<string, ActionErrorDefinition>
emits?string[]
tags?string[]

Source: packages/core/src/types.ts:480

ApiDocument

interface ApiDocument

A named OpenAPI document ready to render.

Properties

NameTypeDescription
titlestring
documentOpenApiDocument

Source: packages/core/src/docs.ts:17

ArchitectureSchema

interface ArchitectureSchema

Properties

NameTypeDescription
versionstring
servicesServiceSchema[]

Source: packages/core/src/types.ts:517

BaseActionConfig

interface BaseActionConfig<TInputSchema extends TSchema | undefined = undefined, TOutputSchema extends TSchema | undefined = undefined, TErrors extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>>

Properties

NameTypeDescription
namestring
description?string
path?stringEffective HTTP path, including the prefix; replaces the default action path.
method?"GET" | "POST" | "PUT" | "PATCH" | "DELETE"Single HTTP method exposed for this action (default POST).
input?TInputSchema
output?TOutputSchema
errors?TErrors
emits?string[]
tags?string[]

Source: packages/core/src/types.ts:181

BaseContext

interface BaseContext<TDb = any>

Base framework context supplied to all service resolvers and action executions.

Properties

NameTypeDescription
requestRequest
dbTDb
loggerLogger
traceIdstring
requestId?string
caller?string
tenantId?string
services?Record<string, any>
metadata?Record<string, unknown>

Source: packages/core/src/types.ts:23

BrickCallOptions

interface BrickCallOptions

Properties

NameTypeDescription
headers?Record<string, string>Extra headers merged over the client defaults for this call only.
signal?AbortSignalAbort signal for this call only. Never wrapped: aborts reject with AbortError.
timeoutMs?numberPer-call timeout in milliseconds. Implemented with AbortSignal.timeout.

Source: packages/core/src/client.ts:109

BrickClientAction

interface BrickClientAction<TInput = unknown, TOutput = unknown, TErrors = {}>

Browser-safe action metadata generated by the Brick Vite plugin.

Properties

NameTypeDescription
kind"action"
namestring
serviceNamestring
plugin?stringOwning plugin descriptor name for plugin actions (e.g. @brickkit/crud).
resource?stringOwning resource name for resource-plugin actions (e.g. page).
config{ path: string; method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" }
readonly __types?{ input: TInput; output: TOutput; errors: TErrors }Type information only; never emitted at runtime.

Source: packages/core/src/client.ts:92

BrickClientOptions

interface BrickClientOptions

Eden/tRPC-style typed HTTP client inferred from Brick-TS application contracts.

The frontend imports only the contract type — never a backend implementation:

import { createBrickClient } from "@brickkit/core/client";
import type { AppServer } from "./server"; // `import type`: erased at build

const api = createBrickClient<AppServer>({ baseUrl: "http://localhost:4000" });
const pages = await api.page.list({ limit: 10, sort: "-createdAt" });
const created = await api.page.create({ title: "Hello", content: "World" });

Build the contract from individually-typed actions (each defineAction call preserves its input/output/error literal types):

// server.ts (backend)
export const listPages = pagesService.action({ name: "page.list", ... });
export const createPage = pagesService.action({ name: "page.create", ... });
export const contract = { page: { list: listPages, create: createPage } };
export type AppServer = typeof contract;

Result / error convention

The client uses a throw-based convention that mirrors local action.execute semantics, because TypeScript promises cannot encode thrown exception types:

  • Success → the promise resolves with the action output.
  • Declared domain failures (your errors: { SLUG_EXISTS: ... }) and framework guards (UNAUTHORIZED/FORBIDDEN/NOT_FOUND/...) → rejected with ActionExecutionError carrying the declared code, status, message, and details. Narrow with instanceof and read err.code.
  • Input/output validation failures → rejected with ValidationError, exactly as local execution throws.
  • Network failures, unparsable bodies, and non-OK responses outside the declared contract → BrickTransportError (4xx) or BrickServerError (5xx).
  • Cancellation via AbortSignal → the native AbortError propagates unwrapped so err.name === "AbortError" keeps working.

URL mapping

A client path is a namespace walk ending in an action call. The leaf segment decides the route, matching the server compiler (packages/cli/src/compiler):

Client callHTTP request
Generated browser contracts carry each action's HTTP method and path,
including plugin routes and consumer overrides. Without runtime metadata,
callers use POST /api/<service>/<action> with dotted action names.
GET/DELETE input is serialized as a query string; other methods send JSON.

Properties

NameTypeDescription
baseUrlstringServer origin, e.g. "http://localhost:4000". No trailing slash required.
prefix?stringRoute prefix the server was mounted with (default "/api"). Must match the prefix passed to brick({ prefix }).
headers?| Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>)Default headers sent with every call (e.g. an Authorization bearer). A thunk is re-evaluated per call, so rotated tokens stay fresh.
fetch?(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>fetch implementation. Defaults to globalThis.fetch.
signal?AbortSignalDefault signal applied to every call (per-call signal wins).
timeoutMs?numberDefault per-call timeout in milliseconds (per-call timeoutMs wins).
contract?Record<string, any>Browser-safe route metadata generated by the Brick Vite plugin. Required for custom methods/paths and plugin routes. Without a contract, calls use POST and service/action names inferred from namespace keys.

Source: packages/core/src/client.ts:62

BrickIR

interface BrickIR

Properties

NameTypeDescription
readonly version1
readonly target"bun-elysia"
readonly prefixstring
readonly servicesreadonly string[]
readonly routesreadonly RouteIR[]
readonly preparationsreadonly { service: string; name: string; metadata: unknown; }[]
readonly diagnosticsreadonly string[]

Source: packages/core/src/compiler/ir.ts:24

CacheOptions

interface CacheOptions

Properties

NameTypeDescription
driver?"memory" | "redis"
defaultTtl?number

Source: packages/core/src/types.ts:433

CompiledApplication

interface CompiledApplication

Properties

NameTypeDescription
readonly irBrickIR
readonly routesreadonly CompiledRoute[]

Source: packages/core/src/compiler.ts:55

CompiledRoute

interface CompiledRoute

Properties

NameTypeDescription
readonly irRouteIR
readonly handlerCompiledHandler

Source: packages/core/src/compiler.ts:51

CompiledRoutePlan

interface CompiledRoutePlan

Properties

NameTypeDescription
serviceService<any, any>
actionAction<any, any, any, any>
actionNamestring
serviceNamestring
routePathstring
method?string
isGetLikeboolean
hasInputboolean
hasContextHookboolean
contextHook?(baseCtx: any) => Promise<any> | any
hasAuthorizeboolean
authorize?(params: any) => boolean | Promise<boolean>
execute(params: any) => Promise<any> | any
inputChecker?{ Check: (val: any) => boolean; Errors: (val: any) => Iterable<any>; }
outputChecker?{ Check: (val: any) => boolean; Errors: (val: any) => Iterable<any>; }
coercions?Array<{ key: string; isNumber: boolean; isBoolean: boolean; isArray?: boolean; }>
loggerLogger
errorBuilderany
cachedDbany

Source: packages/core/src/types.ts:522

CreateServerOptions

interface CreateServerOptions

Properties

NameTypeDescription
port?number
compiler?booleanGenerate specialized handlers once at startup (default true).
compilation?CompiledApplicationAhead-of-time handlers already bound to the supplied services.
services?Service<any, any>[]
prefix?string
title?string
version?string
description?string
docs?boolean
openApiPath?string
docsPath?string
swaggerPath?string
requestLogging?boolean | RequestLoggingOptions
reference?boolean | ReferenceOptionstrue serves a Scalar page at /reference. Options serve one only with a path; documents adds OpenAPI documents to the dashboard's APIs view.
secrets?{ source?: SecretSource; validate?: boolean }
endpoints?EndpointDefinition[]Raw endpoints (outside the JSON action mesh), mounted at startup.
telemetry?booleanRecord request, action, and RPC spans with OpenTelemetry (default false). Spans go to the globally registered tracer provider; without one they are no-ops. brick dev shows them in its dashboard.
documentation?string | DocumentationOptionsDeveloper documentation for the brick dev dashboard (its Docs tab): a folder of .md/.mdx pages in Fumadocs' layout, with frontmatter and meta.json for ordering. A string is the folder. Relative paths start at the folder of the app entry, as they read in the file that sets them (from src/app.ts, "../docs" is docs/ at the project root). Needs fumadocs-core and @mdx-js/mdx installed.
dashboard?DashboardOptionsMonitoring dashboard for brick start, on a port of its own and behind auth. Setting it turns on telemetry. See DashboardOptions.

Source: packages/core/src/server.ts:34

DashboardAuth

interface DashboardAuth

Who may open the dashboard that brick start serves for monitoring.

Properties

NameTypeDescription
token?string | readonly string[]Secrets that let a request in. A browser asks for one in its sign-in prompt (any user name, the secret as the password), and monitors and scripts send Authorization: Bearer <secret>. Give several to rotate one while the other still works. Each is at least 16 characters long; openssl rand -base64 32 makes a good one.
authorize?(request: Request,) => boolean | Response | Promise<boolean | Response>Your own check, to sign people in with the auth the app already has: read a session cookie, verify a Better Auth or Clerk session, look at a header a proxy adds. It receives the request (method, URL, and headers; no body) and returns true to let it in, false to refuse it with 401, or a Response to send instead, such as a redirect to your login page. If it throws or takes longer than five seconds, the request is refused with 503. A request is let in when it carries a valid token, or when this returns true; give both to let monitors in by token and people in by sign-in.

Source: packages/core/src/dashboard.ts:2

DashboardOptions

interface DashboardOptions

The monitoring dashboard brick start serves beside the app, on a port of its own: live requests, logs, errors, and the shape of the service, so it stays reachable when the app's own routes are not. brick dev has its own dashboard, set by command line options, and ignores this.

Setting it turns on telemetry, since the dashboard shows what is traced. While it is on, ctx.logger and console lines written during a request go to the dashboard instead of the console.

Properties

NameTypeDescription
port?numberDefault 9400.
host?stringThe address to listen on. Default 127.0.0.1, reachable only from the same machine. In a container use 0.0.0.0, which needs auth: the dashboard will not start on any other address without it.
auth?DashboardAuth
historyDays?numberDays of finished requests to keep on disk, in .brick/ of the working folder. Default 0: only what happened since the process started, which is lost when it restarts. Needs a folder that outlives the container.

Source: packages/core/src/dashboard.ts:38

DatabaseAdapter

interface DatabaseAdapter<TDb = any, TConfig = any>

Methods

NameTypeDescription
createDatabasecreateDatabase(config?: TConfig): TDb

Source: packages/core/src/db/postgres.ts:36

DatabaseConfig

interface DatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>> extends Omit<SQLiteDatabaseConfig<TSchema>, "client">, Omit<PostgresDatabaseConfig<TSchema>, "client">

Properties

NameTypeDescription
client?| SQLiteDatabaseConfig<TSchema>["client"] | PostgresDatabaseConfig<TSchema>["client"]
engine?"sqlite" | "postgres" | "clickhouse"Database engine. Default: 'sqlite'
name?stringOptional service name associated with this database

Source: packages/core/src/db/index.ts:46

DatabaseHandle

interface DatabaseHandle<TDb, TSchema extends Record<string, unknown> = Record<string, unknown>>

Properties

NameTypeDescription
readonly kind"brick-database"
readonly name?string
readonly engine"sqlite" | "postgres"
readonly tablesReadonly<Record<string, Table>>
readonly schemaTSchema

Methods

NameTypeDescription
getDbgetDb(): TDb
close?close(): void | Promise<void>

Source: packages/core/src/db/define.ts:54

DefaultServiceContext

interface DefaultServiceContext

Default fallback service context for untyped or simple services.

Properties

NameTypeDescription
user?any
session?any
[index][key: string]: any

Source: packages/core/src/types.ts:38

DocumentationOptions

interface DocumentationOptions

Developer documentation for the brick dev dashboard.

Properties

NameTypeDescription
dirstringFolder of .md/.mdx pages. A relative path starts at the folder of the app entry, as it reads in the file that sets it.
components?stringModule whose exports are React components for MDX, added to the built-in ones; a relative path starts where dir does. A default export or a components export holds the name-to-component map. The dashboard bundles it, so it may import anything the project has.

Source: packages/core/src/docs.ts:23

EndpointContext

interface EndpointContext

Context for raw endpoint handlers: Elysia route fields + Brick extras.

Properties

NameTypeDescription
paramsRecord<string, string>
queryRecord<string, string | undefined>
bodyunknown
headersRecord<string, string>
requestRequest
set{ status?: number; headers: Record<string, string> }Elysia response setter (status/headers). Mutate like in app.get.
dbanyDrizzle db from service (or first service with one); undefined when none.
loggerEndpointLogger
traceIdstring
requestIdstring

Source: packages/core/src/endpoints.ts:22

EndpointDefinition

interface EndpointDefinition

Properties

NameTypeDescription
methodEndpointMethod
pathstringElysia-style path, e.g. /p/:slug.
handler(ctx: EndpointContext) => unknown | Promise<unknown>
service?Service<any, any> | stringDb source: instance or registered service name. Defaults to first service with a db.
database?DatabaseHandle<unknown>Explicit database handle, independent of a service.
summary?string
description?string
tags?string[]

Source: packages/core/src/endpoints.ts:37

EndpointLogger

interface EndpointLogger

Logger subset handed to endpoint handlers (mirrors action context loggers).

Properties

NameTypeDescription
info(...args: any[]) => void
warn(...args: any[]) => void
error(...args: any[]) => void
debug(...args: any[]) => void

Source: packages/core/src/endpoints.ts:14

ErrorEnvelope

interface ErrorEnvelope

Properties

NameTypeDescription
namestring
codestring
messagestring
statusnumber
requestIdstring
details?unknown
errors?ValidationError["errors"]

Source: packages/core/src/error-response.ts:4

LifecycleOptions

interface LifecycleOptions

Properties

NameTypeDescription
onInit?(ctx: { db?: any; logger?: Logger }) => Promise<void>
onDestroy?() => Promise<void>

Source: packages/core/src/types.ts:457

Logger

interface Logger

The logger on action, tool, and endpoint contexts. While a dashboard is on (brick dev, or brick start with the dashboard option) a line logged during a traced request appears in the dashboard with that request, instead of on the console (as does a plain console.log); anywhere else it prints to the console.

Properties

NameTypeDescription
info(...args: any[]) => void
warn(...args: any[]) => void
error(...args: any[]) => void
debug(...args: any[]) => void

Source: packages/core/src/types.ts:13

McpHandlerOptions

interface McpHandlerOptions

Properties

NameTypeDescription
registryMcpRegistry
serverInfo{ name: string; version: string; title?: string }
protocolVersions?readonly string[]Versions supported by this transport, newest first.

Source: packages/core/src/mcp.ts:71

McpRegistry

interface McpRegistry

Methods

NameTypeDescription
listToolslistTools(): McpToolDefinition[]
callToolcallTool( name: string, args?: Record<string, unknown>, ctx?: Partial<ActionContext>, ): Promise<unknown>

Source: packages/core/src/mcp.ts:16

McpRegistryOptions

interface McpRegistryOptions

Properties

NameTypeDescription
services?readonly Pick<Service<any, any>, "listTools">[]
tools?readonly Tool<any, any, any, any>[]

Source: packages/core/src/mcp.ts:11

McpToolDefinition

interface McpToolDefinition

Properties

NameTypeDescription
namestring
title?string
descriptionstring
inputSchemaunknown
annotationsToolAnnotations

Source: packages/core/src/mcp.ts:3

OpenApiGeneratorOptions

interface OpenApiGeneratorOptions

Properties

NameTypeDescription
title?string
version?string
description?string
prefix?string
services?Service<any, any>[]
registry?ServiceRegistry

Source: packages/core/src/openapi.ts:7

PluginEndpointContext

interface PluginEndpointContext<C extends ActionContext = ActionContext>

Properties

NameTypeDescription
paramsRecord<string, string>
queryRecord<string, string | undefined>
bodyunknown
headersRecord<string, string>
requestRequest
set{ status?: number; headers: Record<string, string> }
ctxC

Source: packages/core/src/plugin.ts:24

PluginRouteRegistrar

interface PluginRouteRegistrar<C extends ActionContext = ActionContext, S extends PluginRouteScope = PluginRouteScope>

Methods

NameTypeDescription
actionaction< I extends TSchema | undefined = undefined, O extends TSchema | undefined = undefined, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( config: ActionConfigWithAuthorize<I, O, E, C> & { path: string; method: PluginRouteMethod; scope?: S; }, ): Action<I, O, E, C>
actionaction< I extends TSchema | undefined = undefined, O extends TSchema | undefined = undefined, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( config: ActionConfigWithoutAuthorize<I, O, E, C> & { path: string; method: PluginRouteMethod; scope?: S; }, ): Action<I, O, E, C>
endpointendpoint( config: { name: string; path: string; method: PluginRouteMethod; scope?: S; handler: (context: PluginEndpointContext<C>) => unknown | Promise<unknown>; summary…, ): void

Source: packages/core/src/plugin.ts:36

PostgresDatabaseConfig

interface PostgresDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>>

Properties

NameTypeDescription
client?SqlExisting postgres-js client. Connection options are ignored; the caller owns its lifecycle.
url?stringDatabase connection URL (e.g. postgresql://user:pass@host:5432/dbname)
connectionString?stringConnection string alias
host?string
port?number
user?string
password?string
database?string
ssl?boolean | "require" | "allow" | "prefer" | "verify-full"
max?number
prepare?booleanDisable prepared statements (required for transaction-mode poolers such as Supabase's Supavisor on :6543, which cannot hold named prepared statements across transactions).
schema?TSchemaOptional Drizzle schema for relational queries
schemaName?stringCustom schema name for Encore-style isolated schemas

Source: packages/core/src/db/postgres.ts:4

PreparationContribution

interface PreparationContribution

Generic preparation declarations consumed by the application compiler.

Properties

NameTypeDescription
readonly namestring

Methods

NameTypeDescription
describedescribe(): unknown
prepareprepare(): void

Source: packages/core/src/types.ts:389

ProxyOptions

interface ProxyOptions

Properties

NameTypeDescription
isMonolith?boolean
from?stringName of the service creating this proxy. Populates ctx.caller on the target's envelope.
context?Partial<ActionContext>

Source: packages/core/src/types.ts:695

RateLimitOptions

interface RateLimitOptions

Properties

NameTypeDescription
maxRequestsnumber
windownumber | string
scope?"ip" | "user" | "tenant"

Source: packages/core/src/types.ts:427

ReferenceDocument

interface ReferenceDocument

An extra OpenAPI document for the API reference, such as Better Auth's.

Properties

NameTypeDescription
titlestringName in the reference's list of documents.
document| OpenApiDocument | (() => OpenApiDocument | Promise<OpenApiDocument>)The document, or a function returning it; called each time the app starts.

Source: packages/core/src/docs.ts:7

ReferenceOptions

interface ReferenceOptions

Properties

NameTypeDescription
path?stringAlso serve a standalone Scalar page here. Without a path, no page is served.
title?string
specUrl?string
documents?ReferenceDocument[]More OpenAPI documents for the brick dev dashboard's APIs view.

Source: packages/core/src/docs.ts:38

RequestLoggingOptions

interface RequestLoggingOptions

Properties

NameTypeDescription
enabled?boolean
logger?(msg: string) => void

Source: packages/core/src/request-logger.ts:3

ResilienceOptions

interface ResilienceOptions

Properties

NameTypeDescription
timeoutMs?number
retry?{ attempts: number; backoff: "linear" | "exponential"; delayMs: number; }
circuitBreaker?{ errorThresholdPercentage: number; resetTimeoutMs: number; }

Source: packages/core/src/types.ts:438

Resource

interface Resource<TTable = any, TCtx extends ActionContext = ActionContext, TOptions = {}>

Properties

NameTypeDescription
readonly namestring
readonly serviceNamestring
readonly tableTTable
readonly idTOptions extends { id: infer I extends Column; } ? I : Column
readonly idFieldstring
readonly configResourceConfig<TTable, TCtx> & TOptions

Methods

NameTypeDescription
useuse< P extends ResourcePlugin<Service<TCtx["db"], Omit<TCtx, keyof BaseContext>>, this, any>, >( plugin: P, ): this & ResourcePluginAPI<P, TTable, TCtx, this>

Source: packages/core/src/types.ts:395

ResourceConfig

interface ResourceConfig<TTable = any, _TCtx = any>

A resource declares identity and a table; plugins supply behavior.

Properties

NameTypeDescription
namestring
tableTTable
id?Column

Source: packages/core/src/types.ts:363

ResourcePlugin

interface ResourcePlugin<S extends Service<any, any>, R extends Resource<any, any, any>, A extends object>

Properties

NameTypeDescription
readonly [pluginKind]"resource"
readonly namestring
readonly routes?PluginRoutes
readonly setup(context: ResourcePluginContext<S, R>) => A

Source: packages/core/src/plugin.ts:122

ResourcePluginContext

interface ResourcePluginContext<S extends Service<any, any> = Service<any, any>, R extends Resource<any, any, any> = Resource<any, ContextOf<S>, any>>

Properties

NameTypeDescription
serviceS
resourceR
routesPluginRouteRegistrar<ContextOf<S>>

Source: packages/core/src/plugin.ts:86

ResourcePluginTypes

interface ResourcePluginTypes

Plugins may specialize their returned API for the installation host.

Properties

NameTypeDescription
readonly tableunknown
readonly contextunknown
readonly resourceunknown
readonly apiobject

Source: packages/core/src/plugin.ts:96

RouteIR

interface RouteIR

Properties

NameTypeDescription
readonly methodRouteMethod
readonly pathstring
readonly servicestring
readonly actionstring
readonly kind"action"
readonly inputboolean
readonly outputboolean
readonly contextboolean
readonly authorizeboolean
readonly inputPrecedencereadonly ("query" | "params" | "body")[]
readonly coercionsreadonly { readonly key: string; readonly type: "number" | "boolean" | "array"; }[]
readonly inputSchema?unknownJSON projection for inspection and stale-artifact detection, not runtime validation.
readonly outputSchema?unknown

Source: packages/core/src/compiler/ir.ts:5

SecretOptions

interface SecretOptions

Properties

NameTypeDescription
default?stringFallback when the source has no value. Secrets without a default are required.

Source: packages/core/src/secrets.ts:31

SecretSource

interface SecretSource

Type-safe secrets & environment variables.

Declare each secret once at module scope instead of scattering untyped process.env.FOO reads:

const port = secret("PORT").default("3333").transform(Number).require(); const baseUrl = secret("BASE_URL").url().require(); const key = secret("STRIPE_KEY").validate((v) => v.startsWith("sk_") || "must start with sk_" ).require();

Values resolve from the environment (Bun populates process.env from .env locally; in prod the same env source applies — a future SecretSource such as AWS can slot in without touching call sites).

Resolution order per secret: test/session override → source (process.env by default) → declared default. resolveSecrets() validates every registered secret at boot and throws listing all missing required ones.

Methods

NameTypeDescription
getget(name: string): string | undefined

Source: packages/core/src/secrets.ts:22

Service

interface Service<TDb = BunSQLiteDatabase<Record<string, unknown>>, TServiceContext extends Record<string, any> = Record<string, any>>

Properties

NameTypeDescription
readonly namestring
readonly optionsServiceOptions<TServiceContext, TDb>
readonly actionsMap<string, Action<any, any, any, any>>
readonly toolsMap<string, Tool<any, any, any, any>>
readonly tablesMap<string, any>
readonly resourcesMap<string, Resource<any, BaseContext<TDb> & TServiceContext>>
readonly db?TDb
readonly isBuilt?boolean
readonly preparationsMap<string, PreparationContribution>

Methods

NameTypeDescription
useuse<A>(plugin: ServicePlugin<this, A>): A
buildbuild(): this
actionaction< TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( action: Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>, ): this
actionaction< TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( config: ActionConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>, ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>
actionaction< TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( config: ActionConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>, ): Action<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>
tooltool< TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( action: Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>, ): this
tooltool< TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( config: ToolConfigWithAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>, ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>
tooltool< TIn extends TSchema | undefined = undefined, TOut extends TSchema | undefined = undefined, TErr extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, >( config: ToolConfigWithoutAuthorize<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>, ): Tool<TIn, TOut, TErr, BaseContext<TDb> & TServiceContext>
resourceresource< TTable = any, const TOptions extends ResourceTypeOptions = ResourceTypeOptions, >( config: ResourceConfig<TTable, BaseContext<TDb> & TServiceContext> & TOptions & Record<Exclude<keyof TOptions, keyof ResourceConfig>, never>, ): Resource<TTable, BaseContext<TDb> & TServiceContext, ResourceIdentity<TTable, TOptions>>
contributePreparationcontributePreparation(contribution: PreparationContribution): void
listPreparationslistPreparations(): PreparationContribution[]
prepareContributionsprepareContributions(): void
registerTableregisterTable(table: any): this
getActiongetAction(name: string): Action<any, any, any, any> | undefined
listActionslistActions(): Action<any, any, any, any>[]
getToolgetTool(name: string): Tool<any, any, any, any> | undefined
listToolslistTools(): Tool<any, any, any, any>[]
getResourcegetResource( name: string, ): Resource<any, BaseContext<TDb> & TServiceContext> | undefined
listResourceslistResources(): Resource<any, BaseContext<TDb> & TServiceContext>[]
getDbgetDb(): TDb | undefined
setDbsetDb(database: DatabaseHandle<TDb>): void
resolveContextresolveContext( callCtx?: Partial<BaseContext<TDb> & TServiceContext>, ): Promise<BaseContext<TDb> & TServiceContext>
introspectintrospect(): ServiceSchema

Source: packages/core/src/types.ts:555

ServiceAuthOptions

interface ServiceAuthOptions

Properties

NameTypeDescription
requireAuth?boolean
allowedRoles?string[]
policy?(ctx: ActionContext) => boolean | Promise<boolean>

Source: packages/core/src/types.ts:421

ServiceOptions

interface ServiceOptions<TServiceContext extends Record<string, any> = Record<string, any>, TDb = any>

Properties

NameTypeDescription
database?DatabaseHandle<TDb>
context?(baseCtx: BaseContext<TDb> & { user?: unknown },) => Promise<TServiceContext> | TServiceContext
auth?ServiceAuthOptions
rateLimit?RateLimitOptions
cache?CacheOptions
resilience?ResilienceOptions
telemetry?TelemetryOptions
lifecycle?LifecycleOptions

Source: packages/core/src/types.ts:462

ServicePlugin

interface ServicePlugin<S extends Service<any, any>, A>

Properties

NameTypeDescription
readonly [pluginKind]"service"
readonly namestring
readonly routes?PluginRoutes<"app" | "service">
readonly setup(context: ServicePluginContext<S>) => A

Source: packages/core/src/plugin.ts:116

ServicePluginContext

interface ServicePluginContext<S extends Service<any, any> = Service<any, any>>

Properties

NameTypeDescription
serviceS
routesPluginRouteRegistrar<ContextOf<S>, "app" | "service">

Source: packages/core/src/plugin.ts:80

ServiceSchema

interface ServiceSchema

Properties

NameTypeDescription
namestring
optionsRecord<string, unknown>The service options as JSON: functions, such as context and hooks, are left out.
hasDatabaseboolean
databaseConfig?{ name?: string; engine: "sqlite" | "postgres"; tables: string[]; }
actionsActionSchema[]
tools?{ name: string }[]MCP tools. A tool with an HTTP route is also listed under actions.
resources?{ name: string }[]

Source: packages/core/src/types.ts:501

SQLiteDatabaseConfig

interface SQLiteDatabaseConfig<TSchema extends Record<string, unknown> = Record<string, unknown>>

Properties

NameTypeDescription
path?stringDatabase file path or ':memory:' (default: ':memory:')
filename?stringAlias for path
wal?booleanWhether to enable WAL journal mode for file-based DBs (default: true)
foreignKeys?booleanWhether to enforce foreign key constraints (default: true)
client?DatabaseOptional existing bun:sqlite Database instance
schema?TSchemaOptional Drizzle schema object for typed relational queries

Source: packages/core/src/db/sqlite.ts:22

StandardErrorMap

interface StandardErrorMap

Properties

NameTypeDescription
BAD_REQUEST(overrideMessage?: string, details?: unknown, options?: ErrorOptions,) => never
UNAUTHORIZED(overrideMessage?: string, details?: unknown, options?: ErrorOptions,) => never
FORBIDDEN(overrideMessage?: string, details?: unknown, options?: ErrorOptions,) => never
NOT_FOUND(overrideMessage?: string, details?: unknown, options?: ErrorOptions,) => never
CONFLICT(overrideMessage?: string, details?: unknown, options?: ErrorOptions,) => never
INTERNAL_SERVER_ERROR(overrideMessage?: string, details?: unknown, options?: ErrorOptions,) => never
[index][key: string]: | ((overrideMessage?: string, details?: unknown, options?: ErrorOptions,) => never) | undefined

Source: packages/core/src/types.ts:131

TelemetryOptions

interface TelemetryOptions

Properties

NameTypeDescription
traceQueries?boolean
auditLog?boolean
tags?Record<string, string>

Source: packages/core/src/types.ts:451

Tool

interface Tool<I extends TSchema | undefined = any, O extends TSchema | undefined = any, E extends Record<string, ActionErrorDefinition> = Record<string, ActionErrorDefinition>, C extends ActionContext = ActionContext> extends Action<I, O, E, C>

Properties

NameTypeDescription
readonly kind"tool"
config| ToolConfigWithAuthorize<I, O, E, C> | ToolConfigWithoutAuthorize<I, O, E, C>

Source: packages/core/src/types.ts:347

ToolAnnotations

interface ToolAnnotations

MCP tool metadata, kept with the executable definition.

Properties

NameTypeDescription
title?string
readOnlyHint?boolean
destructiveHint?boolean
idempotentHint?boolean
openWorldHint?boolean

Source: packages/core/src/types.ts:316

ToolOptions

interface ToolOptions

Properties

NameTypeDescription
title?string
annotations?ToolAnnotations
http?booleanAlso register HTTP routes and OpenAPI. Defaults to false.

Source: packages/core/src/types.ts:323

ValidationErrorItem

interface ValidationErrorItem

Properties

NameTypeDescription
pathstring
messagestring
value?unknown
type?number

Source: packages/core/src/types.ts:67

Types

ActionAccessPolicy

type ActionAccessPolicy = "public" | "authorized" | "scoped";

Source: packages/core/src/types.ts:478

ActionConfig

type ActionConfig<
  TInputSchema extends TSchema | undefined = any,
  TOutputSchema extends TSchema | undefined = any,
  TErrors extends Record<string, ActionErrorDefinition> = Record<
    string,
    ActionErrorDefinition
  >,
  TContext extends ActionContext = ActionContext,
> =
  | ActionConfigWithAuthorize<TInputSchema, TOutputSchema, TErrors, TContext>
  | ActionConfigWithoutAuthorize<
      TInputSchema,
      TOutputSchema,
      TErrors,
      TContext
    >;

Source: packages/core/src/types.ts:244

ActionContext

type ActionContext<
  TDb = any,
  TServiceContext = DefaultServiceContext,
> = BaseContext<TDb> & TServiceContext;

The combined execution context: BaseContext & TServiceContext.

Source: packages/core/src/types.ts:47

BrickActionCaller

type BrickActionCaller<A> =
  undefined extends InferActionInput<A>
    ? (
        input?: InferActionInput<A>,
        options?: BrickCallOptions,
      ) => Promise<InferActionOutput<A>>
    : (
        input: InferActionInput<A>,
        options?: BrickCallOptions,
      ) => Promise<InferActionOutput<A>>;

Typed caller for one action. Required inputs stay required; actions whose input includes undefined (no schema / all-optional) can be called bare.

Source: packages/core/src/client.ts:259

BrickApp

type BrickApp = Elysia<any, any, any, any, any, any, any> & {
  /** Service definitions, prefix, and telemetry setting chosen at construction. */
  readonly definition: {
    readonly routes: readonly RouteIR[];
    readonly services: readonly Service<any, any>[];
    readonly prefix: string;
    readonly telemetry: boolean;
    readonly documentation?: DocumentationOptions;
    /** What `brick start` serves for monitoring; its `auth` is not enumerable. */
    readonly dashboard?: DashboardOptions;
  };
  /** Register a raw endpoint (outside the JSON action mesh). */
  endpoint(def: EndpointDefinition): void;
  /**
   * The OpenAPI documents behind the dashboard's APIs view: this app's own
   * unless `docs` is false, then those from `reference.documents`.
   */
  referenceDocuments(): Promise<ApiDocument[]>;
  /** All endpoints registered via `endpoint()` (declaration order). */
  listEndpoints(): EndpointDefinition[];
};

The app object returned by brick: Elysia plus endpoint().

Source: packages/core/src/endpoints.ts:175

BrickClient

type BrickClient<T> = T extends
  | BrickClientAction<any, any, any>
  | Action<any, any, any, any>
  ? BrickActionCaller<T>
  : T extends (...args: any[]) => any
    ? BrickActionCaller<T>
    : T extends object
      ? { [K in keyof T]: BrickClient<T[K]> }
      : T;

Recursively maps action leaves and their namespaces to browser callers.

Source: packages/core/src/client.ts:271

BrickDatabase

type BrickDatabase<
  TSchema extends Record<string, unknown> = Record<string, unknown>,
> = BunSQLiteDatabase<TSchema> | PostgresDatabase<TSchema>;

Source: packages/core/src/db/index.ts:61

BrickSQLiteDatabase

type BrickSQLiteDatabase<
  TSchema extends Record<string, unknown> = Record<string, unknown>,
> = BunSQLiteDatabase<TSchema> & {
  $client: Database;
};

Source: packages/core/src/db/sqlite.ts:39

CompiledHandler

type CompiledHandler = (context: any) => unknown | Promise<unknown>;

Source: packages/core/src/compiler/runtime.ts:10

DatabaseDefinition

type DatabaseDefinition<
  TSchema extends Record<string, unknown> = Record<string, unknown>,
> = SQLiteDefinition<TSchema> | PostgresDefinition<TSchema>;

Source: packages/core/src/db/define.ts:50

EndpointMethod

type EndpointMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";

Source: packages/core/src/endpoints.ts:11

EnvInput

type EnvInput<T> = T | SecretRef<T>;

Source: packages/core/src/db/define.ts:18

ErrorBuilder

type ErrorBuilder<
  TErrors extends Record<string, ActionErrorDefinition>,
> = StandardErrorMap & {
  [K in keyof TErrors]: (
    overrideMessage?: string,
    details?: unknown,
    options?: ErrorOptions,
  ) => never;
};

Source: packages/core/src/types.ts:171

HandlerFactory

type HandlerFactory = (
  binding: CompiledRoutePlan,
  runtime: typeof compilerRuntime,
) => CompiledHandler;

Source: packages/core/src/compiler/runtime.ts:11

InferActionErrorCodes

type InferActionErrorCodes<A> =
  A extends BrickClientAction<any, any, infer E>
    ? Extract<keyof E, string>
    : A extends {
          config: { errors?: infer E };
        }
      ? E extends Record<string, ActionErrorDefinition>
        ? Extract<keyof E, string>
        : never
      : never;

Union of error codes declared in an action's errors map.

Source: packages/core/src/client.ts:220

InferActionFailure

type InferActionFailure<A> = ActionExecutionError & {
  code:
    | InferActionErrorCodes<A>
    | "BAD_REQUEST"
    | "UNAUTHORIZED"
    | "FORBIDDEN"
    | "NOT_FOUND"
    | "CONFLICT"
    | "INTERNAL_SERVER_ERROR"
    | "VALIDATION_FAILED";
};

The declared failure shape of an action for catch narrowing:

try { await api.page.create(input); }
catch (err) {
  if (err instanceof ActionExecutionError) {
    const code: InferActionErrorCodes<typeof createPage> | "UNAUTHORIZED" | ... = err.code;
  }
}

(Standard framework codes are always possible alongside declared ones.)

Source: packages/core/src/client.ts:243

InferActionInput

type InferActionInput<A> =
  A extends BrickClientAction<infer I, any, any>
    ? I
    : A extends {
          config: { input?: infer S extends TSchema };
        }
      ? Static<S>
      : A extends {
            execute(params: { input?: infer I; ctx?: any }): any;
          }
        ? I
        : A extends { run(input?: infer I, ctx?: any): any }
          ? I
          : A extends (params: { input?: infer I; ctx?: any }) => any
            ? I
            : unknown;

Static input type from the schema, with a fallback for structural actions.

Source: packages/core/src/client.ts:192

InferActionOutput

type InferActionOutput<A> =
  A extends BrickClientAction<any, infer O, any>
    ? O
    : A extends (...args: any[]) => Promise<infer O>
      ? O
      : A extends { execute(params: any): Promise<infer O> }
        ? O
        : unknown;

Resolved output type of an action.

Source: packages/core/src/client.ts:210

InferTableInsert

type InferTableInsert<TTable> = TTable extends { $inferInsert: infer S }
  ? S
  : any;

Source: packages/core/src/types.ts:372

InferTableRow

type InferTableRow<TTable> = TTable extends { $inferSelect: infer S }
  ? S
  : any;

Source: packages/core/src/types.ts:369

NarrowAuthorizedContext

type NarrowAuthorizedContext<TCtx> = TCtx extends { user: infer U }
  ? [U] extends [null | undefined]
    ? TCtx
    : Omit<TCtx, "user"> & { user: NonNullable<U> }
  : TCtx;

Type utility that automatically narrows ctx.user from User | null to User in execute() when authorize() is declared on the action.

Source: packages/core/src/types.ts:56

OpenApiDocument

type OpenApiDocument = Record<string, unknown>;

An OpenAPI document as plain JSON.

Source: packages/core/src/docs.ts:4

PluginRouteMethod

type PluginRouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";

Source: packages/core/src/plugin.ts:15

PluginRoutes

type PluginRoutes<S extends PluginRouteScope = PluginRouteScope> =
  | false
  | Readonly<Record<string, false | { path?: string; scope?: S }>>;

Source: packages/core/src/plugin.ts:17

PluginRouteScope

type PluginRouteScope = "app" | "service" | "resource";

Source: packages/core/src/plugin.ts:16

PostgresDatabase

type PostgresDatabase<
  _TSchema extends Record<string, unknown> = Record<string, unknown>,
> = any;

Source: packages/core/src/db/postgres.ts:32

PostgresDefinition

type PostgresDefinition<
  TSchema extends Record<string, unknown> = Record<string, unknown>,
> = DefinitionOptions<TSchema> &
  EnvOptions<Omit<PostgresDatabaseConfig<TSchema>, "schema" | "client">> & {
    engine: "postgres";
    path?: never;
    filename?: never;
    wal?: never;
    foreignKeys?: never;
    client?: PostgresDatabaseConfig<TSchema>["client"];
  };

Source: packages/core/src/db/define.ts:38

ResourceIdentity

type ResourceIdentity<T, O> = O & {
  id: O extends { id: infer I extends import("drizzle-orm").Column }
    ? I
    : PrimaryColumn<T>;
};

Source: packages/core/src/types.ts:382

ResourcePluginAPI

type ResourcePluginAPI<P, T, C, R = unknown> = P extends {
  readonly types: infer H extends ResourcePluginTypes;
}
  ? (H & {
      readonly table: T;
      readonly context: C;
      readonly resource: R;
    })["api"]
  : P extends ResourcePlugin<any, any, infer A>
    ? A
    : never;

Source: packages/core/src/plugin.ts:102

ResourceTypeOptions

type ResourceTypeOptions = Pick<ResourceConfig, "name" | "id">;

Source: packages/core/src/types.ts:375

RouteMethod

type RouteMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";

Source: packages/core/src/compiler/ir.ts:4

SQLiteDefinition

type SQLiteDefinition<
  TSchema extends Record<string, unknown> = Record<string, unknown>,
> = DefinitionOptions<TSchema> &
  EnvOptions<Omit<SQLiteDatabaseConfig<TSchema>, "schema" | "client">> & {
    engine?: "sqlite";
    client?: SQLiteDatabaseConfig<TSchema>["client"];
    url?: never;
    connectionString?: never;
  };

Source: packages/core/src/db/define.ts:28

ToolConfigWithAuthorize

type ToolConfigWithAuthorize<
  I extends TSchema | undefined = undefined,
  O extends TSchema | undefined = undefined,
  E extends Record<string, ActionErrorDefinition> = Record<
    string,
    ActionErrorDefinition
  >,
  C extends ActionContext = ActionContext,
> = ActionConfigWithAuthorize<I, O, E, C> & ToolOptions;

Source: packages/core/src/types.ts:329

ToolConfigWithoutAuthorize

type ToolConfigWithoutAuthorize<
  I extends TSchema | undefined = undefined,
  O extends TSchema | undefined = undefined,
  E extends Record<string, ActionErrorDefinition> = Record<
    string,
    ActionErrorDefinition
  >,
  C extends ActionContext = ActionContext,
> = ActionConfigWithoutAuthorize<I, O, E, C> & ToolOptions;

Source: packages/core/src/types.ts:338

Variables

ACTION_ACCESS_KEY

const ACTION_ACCESS_KEY: typeof ACTION_ACCESS_KEY

Cross-copy access metadata protocol. CRUD enforces its access policy inside execute, so config.authorize is absent and introspection can't see it. The plugin stamps each action under this process-global symbol; introspection and OpenAPI read it back. Uses Symbol.for so the binding survives a second copy of core (bundler SSR, Vitest), same as the plugin action-binding key.

Source: packages/core/src/access.ts:18

compilerRuntime

const compilerRuntime: Readonly<{ emptyServices: Readonly<{}>; defaultRequest: Request; nextSequence: () => string; mergeInput: typeof mergeInput; checkDepth: typeof checkDepth; validate: typeof validate; mapError: typeof mapError; isThenable…

Source: packages/core/src/compiler/runtime.ts:97

envSource

const envSource: SecretSource

Default source: process.env (Bun loads .env into it automatically).

Source: packages/core/src/secrets.ts:27

Re-exported from @sinclair/typebox

These come from @sinclair/typebox, which documents them. They are exported here so one import covers them.

NameKindDescription
StatictypeCreates a static type from a TypeBox type
tvariableJavaScript Type Builder with Static Resolution for TypeScript
TSchemainterface
TypevariableJavaScript Type Builder with Static Resolution for TypeScript

Re-exported from drizzle-orm

These come from drizzle-orm, which documents them. They are exported here so one import covers them.

NameKindDescription
andfunctionCombine a list of conditions with the and operator.
ascfunctionUsed in sorting, this specifies that the given column or expression should be sorted in ascending order.
blobfunctionIt's recommended to use text('...', \{ mode: 'json' \}) instead of blob in JSON mode, because it supports JSON functions: >All JSON functions currently throw…
BunSQLiteDatabaseclass
descfunctionUsed in sorting, this specifies that the given column or expression should be sorted in descending order.
eqvariableTest that two values are equal.
foreignKeyfunction
getTableColumnsfunction
getTableNamefunction
gtvariableTest that the first expression passed is greater than the second expression.
gtevariableTest that the first expression passed is greater than or equal to the second expression.
ilikefunctionCase-insensitively compare a column to a pattern, which can include % and _ characters to match multiple variations.
inArrayfunctionTest whether the first parameter, a column or expression, has a value from a list passed as the second argument.
indexfunction
integerfunction
isfunction
isNotNullfunctionTest whether an expression is not NULL.
isNullfunctionTest whether an expression is NULL.
likefunctionCompare a column to a pattern, which can include % and _ characters to match multiple variations.
ltvariableTest that the first expression passed is less than the second expression.
ltevariableTest that the first expression passed is less than or equal to the second expression.
nevariableTest that two values are not equal.
notfunctionNegate the meaning of an expression using the not keyword.
notInArrayfunctionTest whether the first parameter, a column or expression, has a value that is not present in a list passed as the second argument.
orfunctionCombine a list of conditions with the or operator.
primaryKeyfunction
realfunction
relationsfunction
sqlfunction
sqliteTablevariable
Tableinterface
textfunction
uniqueIndexfunction

On this page

FunctionsattachDatabasebindCompiledApplicationbrickbuildErrorHelpersbuildFtsMatchQuerycompileBrickApplicationcompileRoutePlancreateActionHandlercreateBrickClientcreateDatabasecreateEndpointHandlercreateMcpHandlercreateMcpRegistrycreatePostgresDatabasecreateServiceProxycreateSQLiteDatabasedefineActiondefineDatabasedefineResourcedefineResourcePlugindefineServicedefineServicePlugindefineToolemitHandlerFactoryendpointPathsensureResourceIndexesensureSQLiteFtsexecuteCompiledRoutegenerateOpenApiSpecgenerateSQLiteIndexDdlgenerateSQLiteTableDdlgetActionAccessgetCompiledCheckgetGlobalRegistrygetPluginActionRoutegetPluginEndpointshoistAnchoredSchemasisBrickAppisBrickServerErrorisBrickTransportErrorisDatabaseHandleisToollistSecretsloadCompiledBrickAppoverrideSecretoverrideSecretsreferencePluginregisterReferenceRouterequestLoggingPluginrequireBrickAppresetGlobalRegistryresetSecretsresolveEndpointDbresolveSecretsscalarDocsHTMLsecretsetActionAccessswaggerDocsHTMLsyncSchematoErrorResponsetoOpenApiPathtraceRoutevalidateWithSchemaClassesActionExecutionErrorBrickServerErrorBrickTransportErrorSecretRefServiceImplServiceRegistryUnknownToolErrorValidationErrorInterfacesActionActionAccessInfoActionConfigWithAuthorizeActionConfigWithoutAuthorizeActionErrorDefinitionActionSchemaApiDocumentArchitectureSchemaBaseActionConfigBaseContextBrickCallOptionsBrickClientActionBrickClientOptionsBrickIRCacheOptionsCompiledApplicationCompiledRouteCompiledRoutePlanCreateServerOptionsDashboardAuthDashboardOptionsDatabaseAdapterDatabaseConfigDatabaseHandleDefaultServiceContextDocumentationOptionsEndpointContextEndpointDefinitionEndpointLoggerErrorEnvelopeLifecycleOptionsLoggerMcpHandlerOptionsMcpRegistryMcpRegistryOptionsMcpToolDefinitionOpenApiGeneratorOptionsPluginEndpointContextPluginRouteRegistrarPostgresDatabaseConfigPreparationContributionProxyOptionsRateLimitOptionsReferenceDocumentReferenceOptionsRequestLoggingOptionsResilienceOptionsResourceResourceConfigResourcePluginResourcePluginContextResourcePluginTypesRouteIRSecretOptionsSecretSourceServiceServiceAuthOptionsServiceOptionsServicePluginServicePluginContextServiceSchemaSQLiteDatabaseConfigStandardErrorMapTelemetryOptionsToolToolAnnotationsToolOptionsValidationErrorItemTypesActionAccessPolicyActionConfigActionContextBrickActionCallerBrickAppBrickClientBrickDatabaseBrickSQLiteDatabaseCompiledHandlerDatabaseDefinitionEndpointMethodEnvInputErrorBuilderHandlerFactoryInferActionErrorCodesInferActionFailureInferActionInputInferActionOutputInferTableInsertInferTableRowNarrowAuthorizedContextOpenApiDocumentPluginRouteMethodPluginRoutesPluginRouteScopePostgresDatabasePostgresDefinitionResourceIdentityResourcePluginAPIResourceTypeOptionsRouteMethodSQLiteDefinitionToolConfigWithAuthorizeToolConfigWithoutAuthorizeVariablesACTION_ACCESS_KEYcompilerRuntimeenvSourceRe-exported from @sinclair/typeboxRe-exported from drizzle-orm

Generated from the JSDoc above each export. Edit the comment there.